0% found this document useful (0 votes)
18 views

Decisions Using Switch

The switch statement allows a program to evaluate different cases of an integer expression and execute corresponding code blocks. It compares the expression to case constants, running code for the first matched case and any subsequent cases. If no cases match, the default code block runs. Switch statements contain keywords switch, case, and default followed by code to run under different conditions.

Uploaded by

Rahul Gupta
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Decisions Using Switch

The switch statement allows a program to evaluate different cases of an integer expression and execute corresponding code blocks. It compares the expression to case constants, running code for the first matched case and any subsequent cases. If no cases match, the default code block runs. Switch statements contain keywords switch, case, and default followed by code to run under different conditions.

Uploaded by

Rahul Gupta
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

Decisions Using switch

The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switchcasedefault, since these three keywords go together to make up the control statement. They most often appear as follows: switch ( integer expression ) { case constant 1 : do this ; case constant 2 : do this ; case constant 3 : do this ; default : do this ; } The integer expression following the keyword switch is any C expression that will yield an integer value. It could be an integer constant like 1, or !, or an expression that evaluates to an integer. The keyword case is followed by an integer or a character constant. "ach constant in each case must be different from all the others. The #do this$ lines in the above form of switch represent any valid C statement. %hat happens when we run a program containing a switch& 'irst, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. %hen a match is found, the program executes the statements following that case, and all subse(uent case and default statements as well. If no match is found with any of the case statements, only the statements following the default are executed. ) few examples will show how this control structure works. Consider the following program: main( ) { int i = 2 ; switch ( i ) { case 1 : printf ( " am in case 1 !n" ) ; "rea#; case 2 : printf ( " am in case 2 !n" ) ; "rea#; case 3 : printf ( " am in case 3 !n" ) ; "rea#; default : printf ( " am in default !n" ) ; "rea#;

} } The output of this program would be: am in case 2

You might also like