Table of Contents
Introduction
This program will check whether the character entered by the user is a vowel or a consonant same as the previous one. The difference is that in the previous program we were assuming that the user will enter an alphabet only.
But what if the character entered by the user is not an alphabet?
To tackle this problem, we will use a predefined function of the C++ language i.e., isalpha() function.
To understand this example, you should know about
1. Operators
2. if…else statement
3. Predefined functions (such as isalpha() function)
isalpha() function checks whether the character passed is an alphabet or not.
Vowels are a, e, i, o, u, in lower case and A, E, I, O, and U in Upper case.
All other alphabets, including lower case and upper case, except vowels, are consonants.
Program
#include<iostream> using namespace std; int main() { char sValue; cout<<"Enter a character: "<<endl; cin>>sValue; if(isalpha(ch)) // checks whether ch is alphabet or not { if ( (sValue=='a' || sValue=='e'|| sValue=='i'|| sValue=='o'|| sValue=='u') || (sValue=='A' || sValue=='E'|| sValue=='I'|| sValue=='O'|| sValue=='U') ) // '||'(or) operator is used { cout<<sValue<<" is a vowel."<<endl; } else { cout<<sValue<<" is a consonant"<<endl; } } else { cout<<"Entered character is not an alphabet"; } return 0; }
Output
Explanation
In this program, we first declare a ‘char’ variable ‘sValue’ to store the character value entered by the user.
cout<<“Enter a character: “<<endl;
A message is displayed on the screen using ‘cout’ for the user to enter a character value, and ‘endl’ is used to take a new line.
cin>>sValue;
The value entered by the user gets stored in ‘sValue’ using ‘cin’.
if(isalpha(ch))
‘ch’ is passed in the isalpha function to check whether it is an alphabet or not. If it results true, then further execution takes place otherwise the else part of the statement gets executed.
0 Comments