University of Washington-7
University of Washington-7
Washington
Computer
Programming I
Switch Statement
J-2
Review: Conditional Control
Flow
The if statement An if statement could also
choses one of two be used to decide whether
statements to execute or not to to skip a statement
before continuing before continuing
J-3
Multi-way Control Flow
The choice may be “multi-way” rather than simply
between two alternatives
In C, if statements can be used, and sometimes a
statement called the switch can be used
J-4
Multi-way Choice with if
/* How many days in a month? */
if ( month == 1 ) { /* Jan */
days = 31 ;
} else if ( month == 2 ) { /* Feb */
days = 28 ;
} else if ( month == 3 ) { /* Mar */
days = 31 ;
} else if ( month == 4 ) /* Apr */
days = 30 ;
... /* need 12 of
these */ J-5
Better…
if ( month == 9 || month == 4 || /* Sep, Apr */
month == 6 || month == 11 ) { /* Jun, Nov */
days = 30 ;
} else if ( month == 2 ) { /* Feb */
days = 28 ;
} else {
days = 31; /* All the rest */
}
J-6
Alternative: switch
A switch is a form of conditional
statement.