We will write a C++ program to check whether a character is an alphabet or not. Before that, you should have knowledge of the following in C++.
Program to Check Alphabet or Not in C++
First of all the program ask the user to enter a character that needed to be checked and then starts the process of checking.
Using if-else statement if checks whether entered character is greater than or equals to a and less than or equal to z or not. Along with that, using or operator (||) another condition is checked for the uppercase alphabet that is whether entered character is greater than or equals to A and less than or equal to Z or not.
If either of the condition is true then if the part is executed otherwise else part is executed. The program is checking for both lowercase alphabet and uppercase alphabet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main() { char ch; cout << "Enter a Character: "; cin >> ch; if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) cout << ch << " is an Alphabet"; else cout << ch << " is NOT an Alphabet"; return 0; } |
Output:
//Run 1
Enter a Character: A
A is an Alphabet
//Run 2
Enter a Character: 5
5 is NOT an Alphabet
Using ASCII Value
We will do the same except we will compare the character with ASCII value.
- The ASCII values for lowercase characters ranges between 67 to 122. (‘a’ = 97 and ‘z’ = 122).
- The ASCII values for uppercase characters ranges between 65 to 92. (‘A’ = 65 and ‘Z’ = 90).
C++ program to check whether the entered character is alphabet or not using ASCII value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <iostream> using namespace std; int main() { char ch; cout << "Enter a Character: "; cin >> ch; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) cout << ch << " is an Alphabet"; else cout << ch << " is NOT an Alphabet"; return 0; } |
After executing this program, it will produce the same result as the first program mentioned above.