a shot of dev knowledge

RELATED TAGS

What is the toupper() function in C?

In C, the toupper() function is used to convert lowercase alphabets to uppercase letters.

When a lowercase alphabet is passed to the toupper() function it converts it to uppercase.

When an uppercase alphabet is passed to the function it returns the same alphabet.

Note: A ctype.h header file needs to be included in order to use this function.

Syntax

The function takes in an alphabet as a parameter and returns that character in uppercase.

See the function definition below:

int toupper(int ch);

Note: The character is passed in and returned as int; i.e, the ASCII value of the character moves around.

svg viewer

Usage and Examples

Let’s start with the most basic example of converting a lower case alphabet to uppercase using this function.

See the code below:

#include <ctype.h> 

int main() 
{ 
	char ch; 

	// letter to convert to uppercase
	ch = 'a'; 

	printf("%c in uppercase is represented as %c", 
		ch, toupper(ch)); 

	return 0; 
} 

Simple, right?

Now, let’s talk about whole words or sentences. How can you convert them to uppercase using this function? You cannot simply pass the whole word to the function as toupper() only takes one character at a time.

To accomplish this, you would need to loop over the whole word/sentence using a while loop; thus individually converting each character to uppercase.

The process is illustrated in the diagram below:

svg viewer

Now let’s put this in code:

#include <ctype.h> 

int main() 
{ 
    // counter for the loop
    int i = 0;

    // word to convert to uppercase
    char word[] = "edUcaTivE\n"; 
    char chr; 

    // Loop
    while (word[i]) { 
        chr = word[i]; 
        printf("%c", toupper(chr)); 
        i++; 
    } 
  
    return 0; 
} 

Each alphabet character of the word is passed to the toupper() function, and its uppercase form is returned and displayed.

RELATED TAGS

RELATED COURSES
View all Courses
Related Courses
RELATED COURSES
View all Courses
Keep Exploring