Here we are going to check whether the given character by the user at run-time is an alphabet or not in C++.
To check whether the entered input is an alphabet or not, we have to check the value of the entered character is greater than or equal to A and less than or equal to Z otherwise check for lower case, greater than or equal to a, and less than or equal to z. If the condition evaluates to be true then it is an alphabet.
To check whether the entered character is an alphabet or not in C++ programming, we are using the if-else
statement.
The if-else statement allows choosing the set of instructions for execution depending upon an expression’s truth value. It will execute a set of codes if a condition or expression evaluates to true. And executes another set of instructions if the expression evaluates to false.
The syntax is :
if(expression)
{
statement 1;
}
else
{
statement 2;
}
If the expression evaluates to true i.e., a nonzero value, statement 1 is executed, otherwise, statement 2 is executed. Statement 1 and statement 2 can be a single statement, a compound statement, or a null statement.
For our program, the user is asked to enter a character. Get the entered character into the variable ch.
Check if the value of ch is greater than or equal to A and less than or equal to Z OR greater than or equal to a and less than or equal to z.
if((ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))
If evaluates to be true, then print it as an alphabet.
Otherwise, if both the conditions evaluate to be false, then print it is not an alphabet.
Step 1: Call the header file iostream.
Step 2: Use the namespace std.
Step 3: Open the integer type main function; int main().
Step 4: Declare character type variables ch;
Step 5: Ask the user to enter a character.
Step 6: Get the character into the variable ch.
Step 7: Check if ch >= ’a’ && ch >= ’z’ // ch >= ’A’ && ch >= ’Z’;
Step 8: print ch is an alphabet for true
Step 9: else print ch is not an alphabet;
Step 10: exit
#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<<endl<<ch<<" is an Alphabet";
else
cout<<endl<<ch<<" isn't an Alphabet";
cout<<endl;
return 0;
}
RUN 1 Enter a Character: 4 4 isn't an Alphabet RUN 2 Enter a Character: a a is an Alphabet RUN 3 Enter a Character: H H is an Alphabet