toupper and tolower in C: solved exercise
toupper and tolower in C: solved exercise
If you searched for a solved toupper and tolower exercise in C, here are the essential patterns: converting a single character, normalizing a full string to upper or lower case, and performing case-insensitive search.
toupper and tolower are declared in <ctype.h> and operate on an int (the character value cast to unsigned char). If the character is not a letter, it is returned unchanged.
Problem statement
- Convert the character
'a'to uppercase and'Z'to lowercase. - Normalize the string
"Hello, WORLD! 123"to all lowercase and all uppercase. - Compare two strings ignoring case without modifying the originals.
C solution
Expected output
Common mistakes
- Passing
charwithout casting tounsigned char: on platforms wherecharis signed, characters with code > 127 (accented letters) are represented as negative integers. The standard requires the argument to beunsigned charorEOF. - Modifying the original string when only comparison is needed: the correct approach is to convert to a copy or compare character by character as in
strcmp_ci. - Assuming
toupper/tolowerworks with all locales: the<ctype.h>functions depend on the active locale. They always work for basic ASCII letters (a-z, A-Z). For ñ, á, etc., usesetlocaleor internationalization functions. - Forgetting the
\0terminator when building the destination string:to_lowerappends it explicitly; without it,printf("%s")reads beyond the buffer.
Practical use
Normalizing strings to a uniform case is used in text search, identifier comparison (shell commands, usernames), protocol token parsing, and any system where user input has no fixed case.
Recommended next exercise
- Count vowels in C: solved exercise
- Palindrome in C: solved exercise
- strcmp and strncmp in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why must you cast to unsigned char before calling toupper/tolower?
Because the C standard specifies that the argument must be representable as unsigned char or must be EOF. On platforms where char is signed, a character with code > 127 becomes a negative integer, which causes undefined behavior when passed to toupper/tolower. The (unsigned char) cast normalizes the value to the correct range (0–255).
Do toupper and tolower modify the original string?
No. They are pure functions that take a character and return another. To modify a string you must iterate character by character and replace each element with the result, as to_upper does in this exercise.
How does normalization work with accented characters (á, é, ñ)?
The <ctype.h> functions work with the active locale (setlocale). In the default "C" locale they only handle ASCII letters. To support UTF-8 characters like á or ñ, use towupper/towlower from <wctype.h> with wchar_t types, or an internationalization library like ICU.