Wednesday, 24 August 2016

The Switch statement


Switch is used when we know what our conditions will be or whey they are specific. The select statement test the value of an expression against  a list of integer or character constants. The statement is executed as soon as the match is found.



Syntax: switch(expression)
              {
                case constant1: statement;
                                         break;
                case constant2: statement;
                                         break;
                case constant3: statement;
                                          break;
                default:             statement;
             }
When a match is found the statement executes and then it breaks to come out of the switch. The default statement is executed when no matches are found. It doesn't need break statement.

Program:

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();  // Used for clearing the screen before running the program
int month;  //Variable made of type int
cin>>month;   Taking the value from User
switch(month)
{
case 1: cout<<"January";
            break;
case 2: cout<<"February";
            break;
case 3: cout<<"March";
            break;
case 4: cout<<"April";
            break;
case 5: cout<<"May";
            break;
case 6: cout<<"June";
            break;
case 7: cout<<"July";
            break;
case 8: cout<<"August";
            break;
case 9: cout<<"September";
            break;
case 10: cout<<"October";
            break;
case 11: cout<<"November";
            break;
case 12: cout<<"December";
            break;
default: cout<<"Sorry!";
}
}

So variable month is taking the value from user and comparing it to the switch case.
Output:         2
                February

Let's understand this with another example.
Q. Find whether the giver character is a vowel or a consonant.(With switch)


Program:


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char character;  //Variable made of type char
cout<<"Enter a character: ";
cin>>character;
switch(character)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U': cout<<"It's a Vowel";
break;
default: cout<<"It is not a Vowel";
}
getch();
}

Now this program will accept a character variable from user and will start to match it with the cases. If the character is Vowel then it will display "It's a Vowel". It will work just fine.


Output:


Enter a character: i
It's a Vowel

No comments:

Post a Comment