In this source code example, we will see how to use the toupper() function in C programming with an example.
toupper() Function Overview
The toupper() function is a part of the <ctype.h> library in C. It is used to convert a lowercase character to its corresponding uppercase counterpart. If the character passed to the function is already uppercase or is not an alphabetic character, it returns the character unchanged.
Key Points:
- Requires the <ctype.h> header.
- Accepts an int, which is typically the ASCII value of a character.
- If the character is a lowercase letter (a-z), it returns its uppercase counterpart.
- If the character is not a lowercase letter, it returns the character unchanged.
- Non-alphabetic characters remain unaffected by this function.
Source Code Example
#include <stdio.h>
#include <ctype.h> // Required for toupper()
int main() {
char ch;
printf("Enter a lowercase character: ");
scanf("%c", &ch);
char upperCh = toupper(ch);
printf("The uppercase of '%c' is '%c'.\n", ch, upperCh);
return 0;
}
Output
Enter a lowercase character: a The uppercase of 'a' is 'A'. Or Enter a lowercase character: 1 The uppercase of '1' is '1'.
Explanation
1. The necessary header files, stdio.h for input/output and ctype.h for the toupper() function, are included.
2. Inside the main() function, a character variable ch is declared to store the user's input.
3. The user is prompted to input a lowercase character.
4. The toupper() function is applied to the character, and the result is stored in the upperCh variable.
5. The program then prints out the original character and its uppercase counterpart (or the character unchanged if it's not lowercase).
The toupper() function is essential in text processing tasks, such as converting user input to a consistent format, making string comparisons case-insensitive, or performing text transformations.
Comments
Post a Comment