Structured Programming Constructs: Selection MIS 121
Structured Programming Constructs: Selection MIS 121
Sequence
• Statements may be grouped together by surrounding them with a pair of curly braces ({}).
• Such a group is syntactically equivalent to one statement and can be inserted whereever
2. one statement is legal.
Sequence—2
• Such a group, known as a block, has one entry point (the first statement) and one exit point
(the last statement).
• From now on, whenever we mention statement, understand that you may substitute a block
3. instead.
Selection
The selection constructs allow us to follow different paths in different situations. We may also
think of them as enabling us to express decisions.
statement1 is executed if and only if expression evaluates to some non-zero number. If expres-
sion evaluates to 0, statement1 is not executed. In that case, statement2 is executed.
if and else are independent constructs, in that if can occur without else (but not the re-
verse).
Any else is paired with the most recent else-less if, unless curly braces enforce a different
scheme.
Note that only curly braces, not parentheses, must be used to enforce the pairing. Parentheses
5. are only used to surround expression.
if (n > 0)
if (a > b)
z=a;
else
z=b;
has the meaning suggested by indentation, if you want the meaning suggested by
if (n > 0)
if (a > b)
z=a;
else
6. z=b;
Now the previous else-less if is invisible to the else construct, which sees the preceding
block as one statement, a statement following an if construct. Now if (n>0) is the preced-
7. ing else-less if and z gets the value of b only if it is not the case that n>0.
A Common Construct
if (a == b)
z=a;
else if (a == c)
z=b;
else if (a == d)
z=c;
else if (a == e)
z=d;
else
8. z=e;
In a construct like the preceding, the first non-zero expression causes its associated statement
to be executed. Furthermore, no subsequent expression is even evaluated. The else at the end
9. can be used to trap any miscellaneous conditions or supposedly impossible conditions.
10. where exit(1) causes the program to terminate at this point, giving a return code of 1.
Switch
switch (expression) {
case const-expr : statement
case const-expr : statement
...
default : statement
In a switch construct, you almost never have a single statement after each case—it is almost
11. always a block even if you only mean to include one statement.
This is because once a case’s const-expr matches the value of expression, all subsequent state-
ments are executed—the opposite of the else if construct. To mimic the behavior of else
if, which is usually desired, place a break; statement at the end of each block; that will
cause the switch construct to terminate at that point. It’s even a good idea to put a break;
statement at the end of the block following default since additional cases are eventually dis-
covered and added to the ends of typical switch constructs. the code after a true case for ev-
12. ery subsequent case.