If else Exercises
C program to check whether a character is alphabet or not
Write a C program to input a character from user and check whether the given character is alphabet or not using if else. How to check whether a character is alphabet or not in C programming. Logic to check if a character is alphabet or not in C program.
Example
Input
Input character: a
Output
'a' is alphabet
Required knowledge
Basic C programming, Relational operators, Logical operators, If else
Logic to check alphabets
In C every printable and non-printable symbol is treated as a character and has an ASCII value. ASCII value is unique integer value for every character. It is used to represent a character in memory. In memory every character is stored as an integer.
One of the beginner way to tackle the problem is check input for every alphabet characters. However, I will not explain this method neither I recommend you to try.
An input character is alphabet if it is in between a-z or A-Z.
Note: a and A both are different and have different ASCII values.
Step by step descriptive logic to check alphabets.
1.Input a character from user. Store it in some variable say ch.
2.Check if((ch >= 'a') && (ch <= 'z')) or if((ch >= 'A') && (ch <= 'Z')). Then it is alphabet otherwise not.
Let us implement above logic through C program.
Program to check alphabets
/** * C program to check whether a character is alphabet or not */ #includeint main() { char ch; /* Input a character from user */ printf("Enter any character: "); scanf("%c", &ch); if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { printf("Character is an ALPHABET."); } else { printf("Character is NOT ALPHABET."); } return 0; }
Note: You can also use ASCII values to check alphabets. ASCII value of a=97, z=122, A=65 and Z=90.
Program to check alphabets using ASCII value
/** * C program to check whether a character is alphabet or not */ #include <stdio.h> int main() { char ch; /* Input a character from user */ printf("Enter any character: "); scanf("%c", &ch); if((ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90)) { printf("Character is an ALPHABET."); } else { printf("Character is NOT ALPHABET."); } return 0; }
Enhance your skills by learning other approach to solve the given program.
Learn more - Program to check alphabets using conditional operator.
Output
Enter any character: b
Character is an ALPHABET.