tolower() Function Example in C Programming

In this source code example, we will see how to use the tolower() function in C programming with an example.

tolower() Function Overview

The tolower() function is a part of the <ctype.h> library in C. It is used to convert an uppercase character to its corresponding lowercase counterpart. If the character passed to the function is already lowercase or is not an alphabetic character, it returns the character unchanged. 

Key Points: 

- Requires the <ctype.h> header. 

- Accepts an int, which is typically the ASCII value of a character. 

- If the character is an uppercase letter (A-Z), it returns its lowercase counterpart. 

- If the character is not an uppercase letter, it returns the character unchanged. 

- Non-alphabetic characters remain unaffected by this function.

Source Code Example

#include <stdio.h>
#include <ctype.h>  // Required for tolower()

int main() {
    char ch;

    printf("Enter an uppercase character: ");
    scanf("%c", &ch);

    char lowerCh = tolower(ch);

    printf("The lowercase of '%c' is '%c'.\n", ch, lowerCh);

    return 0;
}

Output

Enter an uppercase character: A
The lowercase of 'A' is 'a'.
Or
Enter an uppercase character: 1
The lowercase of '1' is '1'.

Explanation

1. The necessary header files, stdio.h for input/output and ctype.h for the tolower() function, are included.

2. Inside the main() function, a character variable ch is declared to store the user's input.

3. The user is prompted to input an uppercase character.

4. The tolower() function is applied to the character, and the result is stored in the lowerCh variable.

5. The program then prints out the original character and its lowercase counterpart (or the character unchanged if it's not uppercase).

The tolower() function is very useful in text processing tasks, such as formatting, string comparisons, or ensuring consistent casing in user inputs.


Comments