1.

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>

void main()

{

int day;

cout<<"Enter the day of the 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. 

A switch statement tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed.

Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found.

Syntax:

switch( expression ) 

{  

    case value-1:   

                    Block-1;    Break;  

    case value-2:    

                    Block-2;    Break;  

    case value-n:    

                    Block-n;    Break;  

    default:    

                    Block-1;    Break;

 }

 Statement-x;



Discussion

No Comment Found

Related InterviewSolutions