1.

Briefly explain the working of switch statement with an example.

Answer»

Switch statement compares the value of an expression against a list of integers or character constants. The list of constants are listed using the “case” statement along with a “break” statement to end the execution.

#include<iostream.h>

int main(void)

{

int day;

cout<<"Enter the day of week between 1-7::";

cin>>day;

switch(day)

{

case 1:

cout <<"Monday";

break;

case 2:

cout <<"Tuesday";

break;

case 3:

cout <<"wednesday";

break;

case 4:

cout <<"Thursday";

break;

case 5:

cout <<"Friday";

break;

case 6:

cout <<"Saturday";

break;

case 7:

cout <<"Sunday";

break;

}

}

Result:

Enter the day of the week between 1 – 7 :: 7

Sunday

In the above Control Structure example the “switch” statement is used to find the day of the week from the integer input got from the user. The value present in the day is compared for equality with constants written in the word case.

Since no equality is achieved in the above example (from 1 to 6) as they’entered value is 7, default is selected and gives “Sunday” as a result.



Discussion

No Comment Found

Related InterviewSolutions