16-Jan-19 Prepared by Dr. Zakir H. Ahmed 1
Concepts of Programming
Languages (CS344)
Chapter -VI
Statement-Level
Control Structures
Dr. ZakirH. Ahmed
Office# 2055 Phone# 2582172
E-mail: [email protected]
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 2
This Chapter Contains the following
Topics:
1.Introduction
2.SelectionStatements
3.IterativeStatements
4.UnconditionalBranching
5.GuardedCommands
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 3
➢The flow of control, or execution sequence, in a program
can be examined at several levels.
➢In Chapter 5, the flow of control within expressions,
which is governed by operator associativity and
precedence rules, was discussed.
➢At the highest level is the flow of control among
program units, which is discussed in next Chapter.
➢Between these two extremes is the important issue of
the flow of control among statements, which is the
subject of this chapter.
Introduction
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 4
➢Statements that can select among alternative
statement execution and the repeated execution of
sequences of statements are called control statements.
➢A control structure is a control statement and the
collection of statements whose execution it controls.
➢There is only one design issue that is relevant to all of
the selection and iteration control statements:
➢Should the control structure have multiple entries?
➢A selection statement provides the means of choosing
between two or more paths of execution
➢Two general categories:
➢Two-way selectors
➢Multiple-way selectors
Control Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 5
➢The general form of a two-way selector is:
ifcontrol_expression
then clause
else clause
➢Design issues for two-way selectors:
➢What is the form and type of the control
expression?
➢How are the then and else clauses specified?
➢How should the meaning of nested selectors be
specified?
➢The Control Expression
➢If the thenreserved word or some other syntactic
marker is not used to introduce the then clause, the
control expression is specified in parentheses
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 6
➢The Control Expression
➢In those cases where the thenreserved word or
alternative marker is used, there is less need for the
parentheses, they are often omitted, as in Ruby.
➢C89 did not have a Boolean data type, arithmetic
expressions were used as control expressions.
➢It can be done in Python, C99, and C++.
➢However, in those languages either arithmetic or
Boolean expressions can be used.
➢In other contemporary languages, such as Ada, Java,
Ruby, and C#, only Boolean expressions can be used
➢Clause Form
➢In many modern languages, the thenand elseclauses
appear as either single statements or compound
statements
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 7
➢Clause Form
➢In Perl, all clauses are compound statements that
must be delimited by braces, even if they contain
single statements
➢In Fortran 95, Ada, and Ruby, the thenand else
clauses are statement sequences, rather than
compound statements, which are terminated with a
reserved word
➢Python uses indentationto define clauses, e.g.,
ifx > y :
x = y
print "case 1“
➢All statements equally indented are included in the
compound statement
➢Here, a colonis used to introduce the thenclause
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 8
➢Nesting Selectors
➢When a selection statement is nested in the then
clause of a selection statement, it is not clear to
which ifan elseclause should be associated.
➢Consider the following Java code example
if(sum == 0)
if(count == 0)
result = 0;
elseresult = 1;
➢The question is that which ifgets the else?
➢The indentation indicates that the elseclause
belongs with the first then clause.
➢However, with the exceptions of Python and F#,
indentation has no effect
➢Semantic rule: elsematches with the nearest if
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 9
➢To force the alternative semantics in Java, the inner ifis
put in a compound, as in
if(sum == 0)
{ if(count == 0)
result = 0;
}
else result = 1;
➢The above rule is used in C, C++, and C#
➢Perl requires that all then and else clauses to be compound
➢The previous code can written as follows
if(sum == 0)
{ if(count == 0)
{ result = 0;
}
else
{ result = 1;
}
}
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 10
➢Fortran 95+ Ada, Ruby, and Lua use a special word to
resolve the question of semantics of nested selectors
and also add to the readability of the statement
➢For example, consider the following Ruby statement:
ifa > b then
sum = sum + a
acount= acount+ 1
else
sum = sum + b
bcount= bcount+ 1
end
➢The design of this statement is more regular than that
of the selection statements of the C-based languages,
because the form is the same regardless of the number
of statements in the thenand elseclauses
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 11
➢In Ruby, previous code can written as follows, as in
ifsum == 0 then
ifcount == 0 then
result = 0
else
result = 1
end
end
➢The endreserved word closes the nested if, the elseclause is
matched to the inner then clause
➢In Python, the above Ruby statement can be written as
ifsum == 0 :
ifcount == 0 :
result = 0
else :
result = 1
➢If the line else:were indented to begin in the same column as the
outer if, the else clause would be matched with the outer if
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 12
➢Selector Expressions
➢In the functional languages ML, F#, and LISP, the
selector is not a statement, it is an expression that
results in a value
➢Consider the following example selector in F#:
lety =
ifx > 0 thenx
else2 * x
➢This creates the nameyand sets it to either xor
2*x, depending on whether x is greater than zero
➢If the if expression returns a value, there must be
an else clause
➢The types of the values returned by then and else
clauses must be the same.
Two-Way Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 13
➢The multiple-selection statement allows the selection of one
of any number of statements or statement groups
➢Design Issues:
➢What is the form and type of the control expression?
➢How are the selectable segments specified?
➢Is execution flow through the structure restricted to
include just a single selectable segment?
➢How are case values specified?
➢How should unrepresented selector expression values be
handled, if at all?
➢switchis a multiple-selection in C, C++, and Java:
switch(expression)
{ caseconst_expr_1: stmt_1;
…
caseconst_expr_n: stmt_n;
[default: stmt_n+1]
}
Multiple-Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 14
➢The optional default segment (last slide) is for
unrepresented values of the control expression
➢The switch statement does not provide implicit branches at
the end of its code segments.
➢This allows control to flow through more than one selectable
code segment on a single execution, for example:
switch(index)
{ case1:
case3: odd += 1;
sumodd+= index;
case2:
case4: even += 1;
sumeven+= index;
default: printf("Error in switch, index = %d\n", index);
}
➢This code prints the error message on every execution
Multiple-Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 15
➢The breakstatement, a restricted goto, is normally used for
exiting switch statements
➢The following switch statement uses breakto restrict each
execution to a single selectable segment:
switch(index)
{ case1:
case3: odd += 1;
sumodd+= index;
break;
case2:
case4: even += 1;
sumeven+= index;
break;
default: printf("Error in switch, index = %d\n", index);
}
Multiple-Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 16
➢The C# switch statement differs from that of its C-based
predecessors in two ways
➢The control expression and the case constants can be
strings
➢C# has a static semantics rule that disallows the implicit
execution of more than one segment; every selectable
segment must end with an unconditional branch
statement: either a breakor goto; for example:
switch(value)
{case-1: Negatives++;
break;
case0: Zeros++;
gotocase1;
case1: Positives++;
default: Console.WriteLine("Error in switch \n");
}
Multiple-Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 17
➢Rubyhas two forms of case statements –(we consider only
one that is semantically similar to a list of nested if):
case
whenBoolean_expressionthenexpression
. . .
whenBoolean_expressionthenexpression
[elseexpression]
end
➢For example,
leap = case
whenyear % 400 == 0 thentrue
whenyear % 100 == 0 thenfalse
elseyear % 4 == 0
end
➢This case expression evaluates to true if year is a leap year
Multiple-Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 18
➢Adaswitch is very reliable, when a stmt_sequenceexecution is
completed, control is passed to the first statement after case
caseexpression is
whenchoice list => stmt_sequence;
…
whenchoice list => stmt_sequence;
whenothers => stmt_sequence;]
end case;
➢For example,
caseiis
when1 | 3 => odd += 1;
sumodd+= index;
when2 | 4 =>even += 1;
sumeven+= index;
whenothers=> null;
end case;
➢Ada does not fall through to next case
➢when others required if all values not accounted for
➢Ada uses null; instead of solely ;
Multiple-Selection Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 19
➢Multiple Selection Using if: In many situations, a switch
or case statement is inadequate for multiple selection,
where it can be applied as direct extensions to two-way
selectors, using else-ifclauses, for example in Python
ifcount < 10 :
bag1 = True
else :
ifcount < 100 :
bag2 = True
else :
if count < 1000 :
bag3 = True
else :
bag4 = True
Implementing Multiple Selection Structures
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 20
➢The last example in Pythoncan be written as follows (else-
if is spelled as elif), which is the more readable of the two :
ifcount < 10 :
bag1 = True
elifcount < 100 :
bag2 = True
elifcount < 1000 :
bag3 = True
➢This example can be written as the Rubycase statement:
case
whencount < 10 thenbag1 = true
whencount < 100 thenbag2 = true
whencount < 1000 thenbag3 = true
end
➢Else-if statements are based on the common mathematical
statement, the conditional expression
Implementing Multiple Selection Structures
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 21
➢The repeated execution of a statement or compound
statement is accomplished either by iterationor recursion
➢General design issues for iteration control statements:
➢How is iteration controlled?
➢Where should the control mechanism appear in the loop
statement?
➢The primary possibilities for iteration control are logical,
counting, or a combination of the two
➢The bodyof an iterative statement is the collection of
statements whose execution is controlled by the iteration
statement
➢We use the term pretestto mean that the test for loop
completion occurs before the loop body is executed
➢The posttestto mean that it occurs after the loop body is
executed
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 22
➢Counter-Controlled Loops: A counter-controlled iterative
statement has a loop variable, and a means of specifying the
initialand terminal, and stepsizevalues
➢Design Issues:
➢What are the type and scope of the loop variable?
➢Should it be legal for the loop variable or loop parameters
to be changed in the loop body, and if so, does the change
affect loop control?
➢Should the loop parameters be evaluated only once, or
once for every iteration?
➢Do loop in FORTRAN
DO label var= start, finish [, stepsize]
stmt_sequence
label CONTINUE
➢The labelis any number between 1 and 99999
➢The varmay be of type integer, real or double precision.
➢Stepsizecan be any value but not zero, by default one
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 23
➢For example, adding up the numbers from 1 to 100
SUM = 0
DO 10 I = 1, 100
SUM =SUM + I
10 CONTINUE
➢Do-while loop in FORTRAN 77:
DO label WHILE ()
stmt_sequence
label CONTINUE
➢The above example can be written as follows:
SUM =0
I = 1
DO 10 WHILE ( I .LE. 100 )
SUM =SUM + I
I = I + 1
10 CONTINUE
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 24
➢For loop inAda
forvariable in[reverse] discrete_rangeloop
. . .
end loop;
➢A discrete range is a subrange of an integer or enumeration
type, such as 1..10 or Sunday..Thursday.
➢The reversereserved word, when present, indicates that
the values of the discrete range are assigned to the loop
variable in reverse order
➢Loop variabledoes not exist outside the loop, for example,
I : Float := 1.35;
forI in1..100 loop
Sum := Sum + I;
end loop;
➢The Float variable I is unaffected by the for loop
➢Upon loop termination, I is still Float type with 1.35.
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 25
➢For loop inC-based languages
for(expression_1; expression_2; expression_3)
loop body;
➢The expressions can be whole statements, or statement
sequences separated by commas
➢If the second expression is absent, it is an infinite loop
➢The loop body can be a single statement, a compound
statement, or a null statement.
➢C++ differs from C in two ways:
➢Loop control expression can be arithmetic or Boolean
➢The initial expression can include variable definitions
➢The last example can be written in C as follows:
sum = 0;
for(inti= 1; i<= 100; i++)
sum = sum + i;.
➢In Java and C#, loop control expression must be Boolean
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 26
➢For loop inPython
forloop_variableinobject:
loop body
[else:
else clause]
➢The objectis often a range, which is either a list of values
in brackets ([2, 4, 6]), or a call to the range function, e.g.,
➢range(5)returns [0, 1, 2, 3, 4]
➢range(2, 7) returns [2, 3, 4, 5, 6]
➢range(0, 8, 2) returns [0, 2, 4, 6]
➢Rangenever returns the highest value in a given parameter
range
➢The loop variabletakes on the values specified in the given
range, one for each iteration
➢The elseclause, which is optional, is executed if the loop
terminates normally
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 27
➢Logically-Controlled Loops: In many cases, the loop control is
based on a Boolean expression rather than a counter.
➢For these situations, a logically controlled loop is convenient
➢Design Issues:
➢Should the control be pretest or posttest?
➢Should the logically controlled loop be a special form of a
counting loop or a separate statement?
➢C and C++ have both pretest and posttest forms, in which
the control expression can be arithmetic:
while(control_expression) anddo
loop body loop body
while(control_expression);
➢In both cases, the loop body can be compound statement
➢It is legal in both C and C++ to branch into both while and do
loop bodies
➢Java has same, but the control expression must be Boolean
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 28
➢User-Located Loop Control Mechanisms: Sometimes it
is convenient for the programmers to decide a location
for loop control (other than top or bottom of the loop)
➢For these situations, a logically controlled loop is
convenient
➢Design Issues:
➢Should the conditional mechanism be an integral part
of the exit?
➢Should only one loop body be exited, or can enclosing
loops also be exited?
➢C, C++, Python, Ruby, and C# have unconditional
unlabeled exits (break)
➢Java and Perl have unconditional labeled exits (breakin
Java, lastin Perl)
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 29
➢Following is an example of nested loops in Java, in which there is a
breakout of the outer loop from the nested loop:
outerLoop:
for(row = 0; row < numRows; row++)
for(col = 0; col < numCols; col++)
{ sum += mat[row][col];
if(sum > 1000.0)
breakouterLoop;
}
➢C, C++, and Python have an unlabeled control statement, continue,
that skips only remainder of the current iteration
➢For example, consider the following code, where the assignment
statement is skipped for any negative value:
while(sum < 1000)
{ getnext(value);
if(value < 0) continue;
sum += value;
}
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 30
➢In the following code a negative value terminates the loop.:
while(sum < 1000)
{ getnext(value);
if(value < 0) break;
sum += value;
}
➢breakkeyword transfers control to next statement outside loop
while continuekeyword transfers control to beginning of loop,
ignoring rest of lines in loop.
➢Java and Perl have labeled versions of continue
➢A labeled continue statement skips the current iteration of an
outer loop marked with the given label
outerLoop:
for(row = 0; row < numRows; row++)
for(col = 0; col < numCols; col++)
{ sum += mat[row][col];
if(sum > 1000.0)
continueouterLoop;
}
Iterative Statements
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 31
➢An unconditional branching transfers execution control to a
specified place in the program
➢It is represented one of the most heated debates in 1960’s
and 1970’s over the issue of whether unconditional
branching should be part of any high-level language
➢The well-known mechanism is gotostatement
➢The gotohas stunning power and great flexibility, however,
the major concern is Readability
➢Some languages do not support gotostatement. e.g., Java,
Python, and Ruby
➢C# offers gotostatement which also can be used in switch
statements
➢One appropriate use of C#’s gotois in the switch statement
Unconditional Branching
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 32
➢They are designed by Dijkstra (1975)
➢The primary motivation was to provide control statements that
would support a program design methodology that ensured
correctness during development rather than when verifying or
testing completed programs
➢Another motivation is that nondeterminism is sometimes needed in
concurrent programs
➢Dijkstra’s selection statement has the form
if<Boolean expression> -> <statement>
[] <Boolean expression> -> <statement>
[] . . .
[] <Boolean expression> -> <statement>
fi
➢The closing reserved word, fi, backward spell of if
➢Semantics: when construct is reached,
➢Evaluate all Boolean expressions
➢If more than one are true, choose one non-deterministically
➢If none are true, it is a runtime error
Guarded Commands
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 33
➢Consider the following example in Ada:
ifi= 0 -> sum := sum + i
[] i> j -> sum := sum + j
[] j > i-> sum := sum + i
fi
➢If i= 0 and j > i, this statement chooses nondeterministically
between the first and third assignment statements
➢If iis equal to j and is not zero, a runtime error occurs because
none of the conditions is true.
➢For example, to find the largest of two numbers, we can use
ifx >= y -> max := x
[] y >= x -> max := y
fi
➢This computes the desired result without overspecifyingthe
solution
➢In particular, if x and y are equal, it does not matter which we
assign to max.
Guarded Commands
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 34
➢The loop structure proposed by Dijkstra has the form
do<Boolean expression> -> <statement>
[] <Boolean expression> -> <statement>
[] . . .
[] <Boolean expression> -> <statement>
Od
➢Semantics: for each iteration
➢Evaluate all Boolean expressions
➢If more than one are true, choose one non-deterministically;
then start loop again
➢If none are true, exit loop
➢To rearrange the 4 values in q1, q2, q3, q4 so that q1≤q2≤q3≤q4
using Dijkstra’s guarded “do” statement, which is iterated until all
the Boolean expressions are false:
doq1>q2 -> temp:=q1; q1:=q2; q2:=temp
[ ] q2>q3 -> temp:=q2; q2:=q3; q3:=temp
[ ] q3>q4 -> temp:=q3; q3:=q4; q4:=temp
od
Guarded Commands
16-Jan-19 Prepared by Dr. Zakir H. Ahmed 35
End
of
Chapter-VI