This tutorial explains various C programs that check whether a given character is an uppercase or lowercase letter.
Below is a simple example illustrating how to use the isupper()
and islower()
functions from the ctype.h
library to check the case of a character in a C program.
Example Program:
#include <stdio.h>
#include <ctype.h>
void main()
{
char c;
printf("Enter a character: ");
scanf("%c", &c);
if (isupper(c))
{
printf("'%c' is an uppercase letter\n", c);
}
else if (islower(c))
{
printf("'%c' is a lowercase letter\n", c);
}
else
{
printf("'%c' is not a letter\n", c);
}
}
Program Output:
Enter a character: G
'G' is an uppercase letter
This program begins by including the header files stdio.h
and ctype.h
. The stdio.h
header file provides functions for input and output, and the ctype.h
header file provides functions for testing and manipulating characters.
In the main()
function, the program declares a variable c
and prompts the user to enter a character using the printf()
function, and reads the input using the scanf()
function.
Next, the program uses the isupper()
function from the ctype.h
library to check if the character is an uppercase letter, and the islower()
function to check if the character is a lowercase letter. Suppose the character is an uppercase or lowercase letter; the program prints a message indicating the case of the letter. If the character is not a letter, the program prints a message showing it is not a letter.
Here's another way to do the above task differently:
Example Program:
#include <stdio.h>
void main()
{
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (ch >= 'a' && ch <= 'z')
{
printf("%c is a lowercase letter.\n", ch);
}
else if (ch >= 'A' && ch <= 'Z')
{
printf("%c is an uppercase letter.\n", ch);
}
else
{
printf("%c is not a letter.\n", ch);
}
}
Program Output:
Enter a character: p
p is a lowercase letter.
This program reads a character from the user and then checks if it is a lowercase letter (a
to z
), an uppercase letter (A
to Z
), or neither. It does this using the if
and else if
statements.
The scanf
function is used to read a character from the user and store it in the variable ch
. The if
statement checks if ch
is greater than or equal to 'a'
and less than or equal to 'z'
. If this condition is true, it means that ch
is a lowercase letter. The else if
statement checks if ch
is greater than or equal to 'A'
and less than or equal to 'Z'
. If this condition is true, it means that ch
is an uppercase letter. If none of these conditions are true, it means that ch
is not a letter.