Exercise:
Write a C Program to check whether a character is an alphabet or not.
Click Here to View the Solution!
#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.", ch);
else
printf("%c is not an alphabet.", ch);
return 0;
}
Click Here to View the Output!
Enter a character: f
f is an alphabet.
Click Here to View the Explanation!
- This program is used to determine whether an entered character is an Alphabet.
- In the
main method
, the program requests the user to enter a character and stores it in a character variablech
using thescanf()
function. - In
C language programming
, each character has an equivalent ASCII value. For lowercase alphabets the range starts from a = 97 to z = 122 and for uppercase alphabets the range starts from A = 65 to Z = 90. - Initially, in the
if statement
, the program compares c with a and z along with A and Z like (ch >= ‘a’ && ch <= ‘z’ || ch >= ‘A’ && ch<= ‘Z’). Both conditions for the lowercase and uppercase alphabets are separated by the|| OR operator
. If either of the conditions are true, the messagech
is an alphabet is printed. - If the condition is false, the
else statement
is executed which prints the messagech
is not an alphabet. - This can also be done using the
isalpha()
function in C.