C-- 03 Edu
C-- 03 Edu
3. Selection
Condition must be in ( )
(condition)
Indent each statement in the body
When using { and } around the body, put { and } on lines
by themselves
16
Logical Precedence
Highest !
&&
Lowest ||
Example:
(2 < 3) || (5 > 6) && (7 > 8)
An example of an assignment
statement that uses the value of a
conditional expression:
a = (x > 100) ? 0 : 1; Equivalent to
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 19
The switch Statement
The switch statement is used to select among statements
from several alternatives.
It may sometimes be used instead of if/else if
statements
It tests the value of an integer expression and then uses that
value to determine which set of statements to branch to.
The switch Statement Format:
switch (IntExpression)
{
case exp1: statement set 1;
break;
case exp2: statement set 2;
break;
...
case expn: statement set n;
break;
default: statement set n+1;
C++ Programming - Prof. Moheb Ramzy
} Girgis Dept. of Computer Science -
Faculty of Science Minia University 20
switch Statement
Requirements
1)IntExpression can be either of the following:
A variable of any of the integer data types (including
char).
An expression whose value is of any of the integer data
types.
2)exp1 through expn must be constant integer type
expressions and must be unique in the switch statement
3)default is optional but recommended. It is branched to if
none of the case expressions match the switch expression.
Thus, it functions like a trailing else in an ifI else if
statement.
intExpression is
compared against exp1
No
4) If no matching value is No
found, the program statement(s)-for-
branches to the statement default
after default
C++ Programming - Prof. Moheb Ramzy
Girgis Dept. of Computer Science -
Faculty of Science Minia University 22
How the switch Statement Works
(Continued)
Notice that each case ends with a break statement.