Upcoming SlideShare
×

# Lecture13 control statementswitch.ppt

2,632 views
2,494 views

Published on

control statement

1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total views
2,632
On SlideShare
0
From Embeds
0
Number of Embeds
220
Actions
Shares
0
114
0
Likes
1
Embeds 0
No embeds

No notes for slide

### Lecture13 control statementswitch.ppt

1. 1. Switch…Case Statement Prakash Khaire B V Patel Inst. of BMC & IT, Gopalvidyanagar
2. 2. Switch Multiple Selection StructureA multiple selection structure is useful when an●algorithm contains a series of decisions in whicha variable or expression is tested separately forone of several possible integral values.●Each integral value represents a different actionto be taken in the algorithm.●C provides the switch multiple selection structureto implement this type of decision making.
3. 3. Switch-Case StructuresThe 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) ; }
4. 4. Switch-Case StructuresThe 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
5. 5. Switch-Case Structures●Unlike if-else if-else structures, when thevalue in a case matches the test value, all ofthe actions in the rest of the structure takeplace.●This is shown in the following program wherethe user enters a value that matches the firstcase and every action in the structure isexecuted.
6. 6. 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 graden") ; grade = getchar ( ) ; Winter Quarter Winter Quarter Lect 9 P. *
7. 7. 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 Winter Quarter Lect 9 P. *
8. 8. Switch-Case Structures break ;●The problems with the previous program can becorrected by use of the break statement.●It can be used in either a repetition structure or aselection structure to break out of (that is, to exitfrom) the structure.●The syntax is: break ;●The following program is the previous one with theaddition of the break statements.
9. 9. Why Use a switch Statement?●A nested if-else structure is just as efficientas a switch statement.●However, a switch statement may be easierto read.●Also, it is easier to add new cases to a switchstatement than to a nested if-else structure.