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.
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.
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 uppercasech = '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:
Now let’s put this in code:
#include <ctype.h>int main(){// counter for the loopint i = 0;// word to convert to uppercasechar word[] = "edUcaTivE\n";char chr;// Loopwhile (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.
Free Resources