C Program to Check Whether a Character is an Alphabet or not
Example: Program to Check Alphabet
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a' && c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
Output
Enter a character: * * is not an alphabet
In C programming, a character variable holds ASCII value (an integer number between 0 and 127) rather than that character itself.
The ASCII value of lowercase alphabets are from 97 to 122. And, the ASCII value of uppercase alphabets are from 65 to 90.
If the ASCII value of the character entered by the user lies in the range from 97 to 122 or from 65 to 90, that number is an alphabet. In the program,’a’ is used instead of 97 and ‘z’ is used instead of 122. Similarly, ‘A’ is used instead of 65 and ‘Z’ is used instead of 90.
You can also check whether a character is an alphabet or not using isalpha() function.
program in C that checks whether a given character is an alphabet or not:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
printf("%c is an alphabet.\n", ch);
} else {
printf("%c is not an alphabet.\n", ch);
}
return 0;
}
In this program, we declare a character variable “ch”, which represents the character we want to check for being an alphabet or not. We prompt the user to enter this value using the “scanf” function.
We then use an “if-else” statement to determine whether the character is an alphabet. We check whether the character falls within the ASCII range of lowercase letters (‘a’ to ‘z’) or uppercase letters (‘A’ to ‘Z’). If it does, we print out a message indicating that it is an alphabet. If it doesn’t, we print out a message indicating that it is not an alphabet.
Finally, we return 0 from the main function to indicate that the program has executed successfully. The output of this program would be:
Enter a character: q
q is an alphabet.
If the user had entered a non-alphabet character, such as ‘$’, the output would be:
Enter a character: $
$ is not an alphabet.