Check whether a character is an alphabet or not in C++
Understanding Alphabets
An alphabet is any letter from A to Z (both uppercase and lowercase). Any other character is not considered an alphabet.
We will explore three different methods to check whether a character is an alphabet or not in C++.
Method 1: Using if-else
This method checks if the character falls within the range of alphabets.
#include <iostream> using namespace std; void checkAlphabet(char ch) { if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { cout << ch << " is an alphabet" << endl; } else { cout << ch << " is not an alphabet" << endl; } } int main() { char ch; cout << "Enter a character: "; cin >> ch; checkAlphabet(ch); return 0; }
Output: A is an alphabet
Method 2: Using ASCII Values
This method checks the ASCII values of the character.
#include <iostream> using namespace std; void checkAlphabet(char ch) { if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) { cout << ch << " is an alphabet" << endl; } else { cout << ch << " is not an alphabet" << endl; } } int main() { char ch; cout << "Enter a character: "; cin >> ch; checkAlphabet(ch); return 0; }
Output: 1 is not an alphabet
Method 3: Using a Function
This method defines a function to check if a character is an alphabet.
#include <iostream> using namespace std; bool isAlphabet(char ch) { return ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')); } void checkAlphabet(char ch) { if (isAlphabet(ch)) { cout << ch << " is an alphabet" << endl; } else { cout << ch << " is not an alphabet" << endl; } } int main() { char ch; cout << "Enter a character: "; cin >> ch; checkAlphabet(ch); return 0; }
Output: z is an alphabet