Sie sind auf Seite 1von 8

Lecture 13: Control Structure CS 101: Introduction to Computing

Lecture #13
switch Control Structure

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 13: Control Structure CS 101: Introduction to Computing 2

The switch Multiple-Selection Statement


 switch
• Useful when a variable or expression is tested for all the values it can
assume and different actions are taken
 Format
• Series of case labels and an optional default case
switch ( value )
{
case '1':
actions
case '2':
actions
default:
Actions
}
 break; // exits from statement
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 13: Control Structure CS 101: Introduction to Computing 3
Same actions taken for two cases
switch ( value ){
case '1':
case '2':
actions /* one or more statements */
break;

case '3':
case '4':
actions /* one or more statements */
break;

default:
actions /* one or more statements */
break;
}

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


2.16 The switch Multiple-Selection
Lecture 13: Control StructureCS 101: Introduction to Computing

switch Structure
Useful when variable or expression is tested for multiple values
Consists of a series of case labels and an optional default case

true
case a case a action(s) break
false

true
case b case b action(s) break
false

.
.
.

true
case z case z action(s) break
false

default action(s)

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 13: Control Structure CS 101: Introduction to Computing

Some info about switch


 Case cannot have conditions. E.g. case (x<=2)
 Switch condition cannot evaluate float values/variables
 Switch condition can only check int and char values
 Continue cannot be used in switch
 Every statement in a switch body must belong to a specific case
otherwise it will not be executed (no compile time error though)
 Switch condition can have arithmetic expressions. E.g. switch (j + k * l)
 Case can have only constant values
 Order of the cases or default does not matter

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 13: Control Structure CS 101: Introduction to Computing 6

1. Initialize variables

2. Input data

2.1 Use switch loop to


update count

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 13: Control Structure CS 101: Introduction to Computing 7

2.1 Use switch loop to


update count

3. Print results

Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi


Lecture 13: Control Structure CS 101: Introduction to Computing 8

Program Output
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b

Totals for each letter grade are:


A: 3
B: 2
C: 3
D: 2
F: 1
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi

Das könnte Ihnen auch gefallen