tolower() Function
The tolower()
function in C converts an uppercase letter to its lowercase equivalent if one exists. If the provided character is not an uppercase letter, the function returns the character unchanged. This behavior is dependent on the locale, and in the default “C” locale, only the letters A-Z are converted to a-z.
Syntax of tolower()
int tolower(int c);
Parameters
Parameter | Description |
---|---|
c | An integer representing the character to be converted, typically cast from a char or EOF. |
If the character provided is an uppercase letter and has a corresponding lowercase character, tolower()
returns its lowercase equivalent. Otherwise, it returns the character unchanged.
Return Value
The function returns the lowercase equivalent of the character if a conversion exists; if not, it returns the original character. The value is returned as an int
that can be implicitly cast to a char
.
Examples for tolower()
Example 1: Basic Conversion of a Single Uppercase Letter
This example demonstrates the basic usage of tolower()
by converting a single uppercase letter to its lowercase equivalent.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
int ch = 'G';
printf("Original character: %c\n", ch);
printf("Lowercase character: %c\n", tolower(ch));
return 0;
}
Explanation:
- The character
'G'
is stored in the variablech
. - The
tolower()
function converts'G'
to'g'
. - The program prints both the original and the converted character.
Program Output:
Original character: G
Lowercase character: g
Example 2: Converting a String Character-by-Character
This example illustrates how to convert each character of a string to lowercase by using tolower()
within a loop.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
char str[] = "Hello World!";
int i = 0;
printf("Original string: %s\n", str);
while (str[i] != '\0') {
str[i] = tolower(str[i]);
i++;
}
printf("Lowercase string: %s\n", str);
return 0;
}
Explanation:
- A string
"Hello World!"
is defined. - The program iterates over each character of the string.
- Each character is converted to lowercase using
tolower()
. - The modified string is printed, showing the complete conversion.
Program Output:
Original string: Hello World!
Lowercase string: hello world!
Example 3: No Conversion Needed for Non-Uppercase Characters
This example shows that if a character is already lowercase or non-alphabetical, tolower()
returns it unchanged.
Program
#include <stdio.h>
#include <ctype.h>
int main() {
int ch = 'z';
printf("Original character: %c\n", ch);
printf("After tolower(): %c\n", tolower(ch));
return 0;
}
Explanation:
- The character
'z'
is stored in the variablech
. - Since
'z'
is already lowercase,tolower()
returns it unchanged. - The program prints the same character before and after the conversion.
Program Output:
Original character: z
After tolower(): z