Give an explanation on how this code works as in what does it do. I already know
ID: 3815401 • Letter: G
Question
Give an explanation on how this code works as in what does it do.
I already know where the code resides and where it converts.
#include<stdio.h>
void upper_string(char*);
int main()
{
char string[2000];
int con=1;
while(con == 1)
{
// reading entire line in to char array string
printf("Enter a sentence to convert it into upper case ");
scanf(" %[^ ]",string);
// function to convert lower case sentence to upper case
upper_string(string);
printf(" Entered sentence in upper case is "%s" ", string);
printf(" Press 1 to Continue or any other number to exit...... ");
scanf("%d",&con);
}
return 0;
}
void upper_string(char *string)
{
while(*string)
{
if ( *string >= 'a' && *string <= 'z' )
{
*string = *string - 32;
}
string++;
}
}
Explanation / Answer
Output:
Enter a sentence to convert it into upper case
Good Morning!!! have a nice day.
Entered sentence in upper case is
GOOD MORNING!!! HAVE A NICE DAY.
Press 1 to Continue or any other number to exit......
1
Enter a sentence to convert it into upper case
Today there is C language exam.
Press 1 to Continue or any other number to exit......
2
In this program, inside the main method a char array of size 1000 characters is declared to input a sentence from user
and call the function upper() to capitalize each character of the sentence.
void upper_string(char *string) // a pointer to char is used to store the base address of sentence sent as argument by main method
{
while(*string) // while the char pointer by pointer string is not null
{
if ( *string >= 'a' && *string <= 'z' ) // if the char is lowercase alphabet between a and z
{
*string = *string - 32; // the value of char is decremented by 32 , so if Ascii value of a = 97 ,97-32 = 65 = A (ascii value of A
}
string++; // increment the pointer so that it points to next character
}
}
The method used to capitalize lowercase alphabets is to use ASCII values. Notice that the characters other than small alphabets remain same eg !!!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.