toupper() Function
The toupper()
function in C converts a lowercase letter to its uppercase equivalent if one exists. If the provided character does not have a corresponding uppercase version, it remains unchanged. This behavior may depend on the current locale settings.
Syntax of toupper()
int toupper(int c);
Parameters
Parameter | Description |
---|---|
c | An integer representing the character to be converted, typically cast from a char or EOF. |
It is worth noting that the function only converts lowercase letters to uppercase. In locales other than the default “C” locale, the conversion may be influenced by the locale settings, and if a lowercase character has more than one uppercase equivalent, the function will consistently return the same result for that character.
Return Value
The function returns the uppercase equivalent of the provided character if one exists, or the character itself (unchanged) if no conversion is possible. The returned value is of type int
and can be implicitly cast to char
.
Examples for toupper()
Example 1: Converting a Single Lowercase Character
This example demonstrates the conversion of a single lowercase character to its uppercase equivalent using toupper()
.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
int ch = 'm';
int upper = toupper(ch);
printf("Original character: %c\n", ch);
printf("Uppercase character: %c\n", upper);
return 0;
}
Explanation:
- A character
'm'
is assigned to the variablech
. - The
toupper()
function converts'm'
to its uppercase equivalent'M'
. - The original and converted characters are printed.
Program Output:
Original character: m
Uppercase character: M
Example 2: Handling a Non-Alphabetic Character
This example shows that when a non-lowercase letter is passed to toupper()
, it remains unchanged.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
int ch = '9';
int result = toupper(ch);
printf("Input character: %c\n", ch);
printf("Output character: %c\n", result);
return 0;
}
Explanation:
- The character
'9'
is assigned toch
. - The
toupper()
function is called with'9'
as input. - Since
'9'
is not a lowercase letter, the function returns it unchanged. - The program prints both the input and output characters.
Program Output:
Input character: 9
Output character: 9
Example 3: Converting an Entire String to Uppercase
This example demonstrates how to iterate over a string and convert each lowercase letter to uppercase using toupper()
.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Hello, World!";
int i = 0;
while (str[i] != '\0') {
str[i] = toupper(str[i]);
i++;
}
printf("Converted string: %s\n", str);
return 0;
}
Explanation:
- A string
"Hello, World!"
is defined. - A while loop iterates through each character of the string.
- Each character is passed to
toupper()
, converting it to uppercase if applicable. - The modified string is then printed.
Program Output:
Converted string: HELLO, WORLD!