Write a function toupper which converts its char argument, ch to upper case if ch is lower case and leaves it unchanged otherwise.

Source Code

Brief explanation is provided after the source code.

 
#include <stdio.h>

int toUpper(int ch);

int main(int argc, char ** argv){
    char c;
    printf("Enter a character: ");
    scanf("%c", &c);
    printf("toupper: %c\n", toUpper(c));
    return 0;
}

int toUpper(int ch)
{
    if(ch>='a' && ch<='z')
        return('A' + ch - 'a');
    else
        return(ch);
}

When you compile and execute the above program it produces the following result on Linux:

Enter a character: u
toupper: U

Brief Explanation

  • The program starts by requesting the user to enter a character.
  • Using the function scanf, the character is read and assigned to the variable c. scanf reads characters from the standard input, interprets them according to the specification in format, and stores the results through the remaining arguments. scanf stops when it exhausts its format string, or when some input fails to match the control specification.
    • int scanf(const char *format, ...)
  • The function toUpper converts its char argument, ch to upper case if ch is lower case and leaves it unchanged otherwise.
  • Its important to know that the upper and lower case alphabets have corresponding integer values.
    • A-Z - 65 - 90
    • a-z - 97 - 122
  • If the user enter the character b, then ch - 'a' = 1 and 'A' + 1 = 'B'
  • The return value of zero in the main function implies normal termination; non-zero values signal unusual or erroneous termination conditions.

Add comment


Security code
Refresh