Upload
eshikshak
View
2.408
Download
0
Embed Size (px)
DESCRIPTION
control statement
Citation preview
Switch…Case Statement
Prakash KhaireB V Patel Inst. of BMC & IT, Gopalvidyanagar
Switch Multiple Selection Structure
●A multiple selection structure is useful when an algorithm contains a series of decisions in which a variable or expression is tested separately for one of several possible integral values.
●Each integral value represents a different action to be taken in the algorithm.
●C provides the switch multiple selection structure to implement this type of decision making.
Switch-Case Structures
●The switch - case syntax is: switch (integer expression test value) {
case case _1_fixed_value : action(s) ;
case case_2_fixed_value : action(s) ;
default : action(s) ;
}
Switch-Case Structures
●The switch is the "controlling expression"■Can only be used with constant integer expressions.■Remember, a single character is a small positive integer.■The expression appears in ( )
●The case is a "label"■The label must be followed by a " : "■Braces, { }, not required around statements
Switch-Case Structures
●Unlike if-else if-else structures, when the value in a case matches the test value, all of the actions in the rest of the structure take place.
●This is shown in the following program where the user enters a value that matches the first case and every action in the structure is executed.
A Sample Program to Illustrate Switch-Case
/* This program associates a letter grade with a message appropriate to the score. */
#include <stdio.h>
int main ( ){
char grade ;printf ("Enter your current letter grade\n") ;grade = getchar ( ) ;
Winter Quarter Lect 9 P. *Winter Quarter
A Sample Program to Illustrate Switch-Case
case ('c') :case ('C') :
printf ("Better get to work.\n") ;case ('d') :case ('D') :
printf ("You are in trouble.\n") ;default :
printf ("You are failing!!\n") ; } /* End of switch-case structure */} /* End of main program */
Winter Quarter Lect 9 P. *Winter Quarter
Switch-Case Structures
break ; ●The problems with the previous program can be corrected by use of the break statement. ●It can be used in either a repetition structure or a selection structure to break out of (that is, to exit from) the structure.●The syntax is:
break ; ●The following program is the previous one with the addition of the break statements.
Why Use a switch Statement?
●A nested if-else structure is just as efficient as a switch statement.●However, a switch statement may be easier to read.●Also, it is easier to add new cases to a switch statement than to a nested if-else structure.