Checking if character entered is a vowel – switch-case – Computer Sir Ki Class
  

Login
[lwa]



Code Learning #CPP#1973 siteicon   siteicon   siteicon  

Checking if character entered is a vowel – switch-case

Entering a character from console and then checking if entered character is a vowel or something else.

Learning Objectives

  • Learning to use switch-case construct for character data type.
  • Learning a large number of fall through cases for writing them in any form (one-line, multiple line, one in each line etc.

Source Code

TC++ #1973

#include 
#include
int main()
{
clrscr();
char c;
cout<<"Enter an alphabet(a-z/A-Z) : ";
cin>>c;
switch (c)
{
case 'A': case 'a':
case 'E': case 'e':
case 'I': case 'i':
case 'O': case 'o':
case 'U': case 'u': cout <<"It is a vowel";
break;
default: cout <<"It is not a vowel";
}
getch();
return 0;
}

Source Code

#include 
using namespace std;
int main ( )
{
char c;
cout<<"Enter an alphabet(a-z/A-Z) : ";
cin>>c;
switch (c)
{
case 'A': case 'a':
case 'E': case 'e':
case 'I': case 'i':
case 'O': case 'o':
case 'U': case 'u': cout <<"It is a vowel";
break;
default: cout <<"It is not a vowel";
}
return 0 ;
}

Test it !

Run Output

Enter an alphabet(a-z/A-Z) : A
It is a vowel

-OR-
Enter an alphabet(a-z/A-Z) : t
It is not a vowel

Code Understanding

switch (c) {
Here we are checking for a character type data in the switch

case ‘A’: case ‘a’: case ‘E’: case ‘e’: case ‘I’: case ‘i’: case ‘O’: case ‘o’: case ‘U’: case ‘u’:
cout <<“It is a vowel”; break;
Since this is a check for character type data so each data element will be written in case within single quotes such as case ‘A’: etc. Multiple case can be written in a sequence so as to implement the fall through method of switch case. After the last case is checked the instructions can be written which is followed by a break instruction.

default: cout <<“It is not a vowel”;
This one is the default case, which means that none of the case specified has matched, so the message is accordingly printed. The break instruction is not required here as it is already the last case.

Notes

  • The case <value>: syntax uses the formatting of c++ which allows any number of spaces between the different entities. The most common writing formats are -Typical fall through style:
    case ‘A’:
    case ‘a’:
    case ‘E:
    case ‘e’:  and so on..

    Multiple line style:
    case ‘A’: case ‘a’:
    case ‘E: case ‘e’:  and so on..

    Single line style:
    case ‘A’: case ‘a’: case ‘E: case ‘e’:  and so on..


Suggested Filename(s): vowel-check.cpp



Share

sunmitra| Created: 28-Dec-2017 | Updated: 15-Sep-2018|






Back