Course contentsShow
← C
Lesson 845 of 1,21912. The Standard LibraryFree lesson

Converting case with `toupper` and `tolower`

Converting case with toupper and tolower

What you'll learn: How to reliably transform lowercase letters to uppercase and vice versa using the built-in C standard library functions.

The Case-Changing Machine

In C, characters are actually stored as numbers (ASCII values). While you could technically do math on these numbers to change their case—like subtracting 32 to turn 'a' into 'A'—it is messy, error-prone, and hard for others to read.

Instead, the <ctype.h> header provides two specialized tools: toupper() and tolower(). Think of these as automated "gates." If you send a lowercase 'b' through the toupper() gate, it comes out as a capital 'B'. If you send a character that is already uppercase, or even a punctuation mark like '!', the gate simply lets it pass through unchanged.

How to use them

Both functions take a single int (a character) as an argument and return the converted version. Because they are designed to be safe, you don't have to worry about accidentally "breaking" a symbol or a number; the functions only act on alphabetic characters that actually have an opposite case.

Here is how you apply them in a program:

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

int main() {
    char lower = 'g';
    char upper = 'R';
    char symbol = '#';

    // Converting to uppercase
    printf("Lower to Upper: %c\n", toupper(lower)); // Outputs 'G'
    
    // Converting to lowercase
    printf("Upper to Lower: %c\n", tolower(upper)); // Outputs 'r'

    // Non-alphabetic characters remain the same
    printf("Symbol remains: %c\n", toupper(symbol)); // Outputs '#'

    return 0;
}

Why use them?

Using these functions is vital for "case-insensitive" logic. For example, if you ask a user to type 'Y' to continue, they might type a lowercase 'y'. By passing their input through toupper() before checking it, your program becomes much more user-friendly. It ensures that 'y' and 'Y' are treated as the exact same command without you having to write complex "if" statements for every possible variation.

Key takeaway

Use toupper() and tolower() from <ctype.h> to safely transform character cases without affecting non-alphabetic symbols.