C Library - toupper() function



The C ctype library tolower() function converts lowercase letter to uppercase. If the given character is already an uppercase letter or is not a lowercase letter, the function returns the character unchanged.

Syntax

Following is the C library syntax of the tolower() function −

int toupper(int c);

Parameters

This function accepts a single parameter −

  • c − This is an integer value representing the character to be converted. It must be a character that can be represented as an unsigned char or the value of EOF.

Return Value

This function returns the uppercase equivalent of the given character if it is a lowercase letter. If the character is already in uppercase or is not a lowercase letter, the function returns the character unchanged.

Example 1: Conversion in a String

Each character in the string "Hello World!" is checked and converted to uppercase if it is a lowercase letter.

#include <stdio.h>
#include <ctype.h>

int main() {
   char str[] = "Hello World!";
   for (int i = 0; str[i] != '\0'; i++) {
      str[i] = toupper(str[i]);
   }
   printf("Converted String: %s\n", str);
   return 0;
}

Output

The above code produces following result−

Converted String: HELLO WORLD!

Example 2: Handling Non-Letter Characters

Only the lowercase letters 'a', 'b', and 'c' are converted to uppercase. Numbers and already uppercase letters remain unchanged.

#include <stdio.h>
#include <ctype.h>

int main() {
   char mixed[] = "123abcXYZ!";
   for (int i = 0; mixed[i] != '\0'; i++) {
      mixed[i] = toupper(mixed[i]);
   }
   printf("Converted String: %s\n", mixed);
   return 0;
}

Output

After execution of above code, we get the following result

Converted String: 123ABCXYZ!
Advertisements