Switch Statement in C++

Switch case is a multi way decision maker, that test whether an expression matches one of the number of values. In switch statement we use case, default, break reserved keywords.

 

Switch first calculates the expression and then matches expression with label1(case 1), if both are equal then first case body is executed and switch is terminated because of break.If expression is not equal, then this matches with next value, if expression is not match with any value from 1 to n value then default block is executed.

//Programe to Compute the grade of a student by using switch statement

#include<iostream.h>

#include<conio.h>

#include<dos.h>

void main()

{

int p,c,m,t,per;

char g;

clrscr();

cout<<"\n Pls enter the marks of three student";

cin>>p>>c>>m;

t=p+c+m;

per=t/3;

switch(per/10)

{

case 10:

case 9:

case 8:

   g='A';

   cout<<"Distinction";

   break;

case 7:

case 6:

   g='B';

   cout<<"First Divison";

   break;

case 5:

case 4:

   g='C';

   cout<<"Second Divison";

   break;

default:

   g='F';

   cout<<"Fail";

}

cout<<"\n Grade is:"<<g<<endl;

sleep(10);

}

switch statement in cpp

Explanation….

In above example we find the grade of a student having three subject marks. The condition to compute the grade are as:

If Percentage is>=80% the ‘A’ grade assigned and also print “Distinction”

If Percentage is<80% but >=60% then ‘B’ grade assigned and also print “First Divison”

If Percentage is<60% but >=40% then ‘C’ grade assigned and also print “Second Divison”.

At end if percentage <40%, then ‘F’ grade be assigned and also print”Fail”.

 

Another Example of Switch Statement….

//Display the different Color by using the switch statement

#include<conio.h>

#include<iostream.h>

void main()

{

char ch;

clrscr();

cout<<"\n\t     MAIN MENU";

cout<<"\n R. for RED Color";

cout<<"\n W. for WHITE Color";

cout<<"\n B. for BLUE Color";

cout<<"\n Y. for YELLOW Color";

cout<<"\n Pls Enter ur choice";

cin>>choice;

switch(choice)

{

case 'r':

case 'R':

   cout<<"\n Color is RED";

   break;

case 'w':

case 'W':

   cout<<"\n Color is WHITE";

   break;

case 'b':

case 'B':

   cout<<"\n Color is BLUE";

   break;

case 'y':

case 'Y':

   cout<<"\n Color is YELLOW";

   break;

default:

   cout<<"\n Color doesn't found";

}

getch();

}

switch satement

Explanation..

In above example we print RED,BLUE YELLOW,WHITE Colors according to their first letter(alphabet). If the letter does not match, then message ”color doesn’t found” will be displayed.