In the previous article, we have discussed C++ Program to Convert String to a Number. In this article, we will see C++ Program to Check Whether a Character is an Alphabet or Not.
Method to check whether a character is an alphabet or not in c++
In this article, we discuss different methods of how can we check whether a given character is alphabet or not in c++. The methods that are discussed are given below.
- Using if-else statement with ASCII value concept
- Using if-else statement with comparing character concept
- Using isalpha( ) method
Let understand these methods one by one.
Method 1-Using if-else statement with ASCII value concept
As we know that ASCII value of upper case alphabets is between 65 and 90 i.e. ASCII value of ‘A’ is 65 while that of ‘Z’ is 90, while the ASCII value of lower case alphabets is between 97 and 122 i.e. ASCII value of ‘a’ is 97 while that of ‘z’ is 122. So we use this concept to check whether a given character is an alphabet or not. If the ASCII value of a character is between 65 and 90 or it is between 97 and 122 then the given character is an alphabet else given character is not an alphabet. Let’s write code for this.
#include <iostream> using namespace std; int main() { char ch='j'; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) { cout <<"Character "<<ch<<" is an alphabet"; } else { cout <<"Character "<<ch<<" is not an alphabet"; } return 0; }
Output
Character j is an alphabet
Method 2- Using if-else statement with comparing character concept
In this method instead of comparing the ASCII value of character, we will directly compare characters i.e. if a character is between ‘a’ and ‘z’ or a character is between ‘A’ and ‘Z’ then a given character is an alphabet otherwise given character is not an alphabet. Let’s write code for this.
#include <iostream> using namespace std; int main() { char ch='j'; if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { cout <<"Character "<<ch<<" is an alphabet"; } else { cout <<"Character "<<ch<<" is not an alphabet"; } return 0; }
Output
Character j is an alphabet
Method 3-Using isalpha( ) method
isalpha( ) is a function in C++ that can be used to check if the passed character is an alphabet or not. It returns a non-zero value if the passed character is an alphabet else it returns 0. Let’s write code for this.
#include <iostream> using namespace std; int main() { char ch='j'; if (isalpha(ch)) { cout <<"Character "<<ch<<" is an alphabet"; } else { cout <<"Character "<<ch<<" is not an alphabet"; } return 0; }
Output
Character j is an alphabet
So these are the methods to check whether a given character is an alphabet or not in c++.
Do you want to learn how to write a simple program in C++ language? If yes, then tap on the C++ Sample Programs link and get the source code for sample and easy programs.