0% found this document useful (0 votes)
36 views59 pages

cmps445 Lecture8

The document discusses expressions, control structures, and statements in programming languages. It covers: - Expressions like arithmetic, relational, and boolean expressions. - Selection statements like if-then-else and switch statements that allow conditional execution. - Iterative statements like for loops and while loops that allow repeated execution based on counters or logical conditions. - Issues in designing control structures like nested statement scopes, loop variable types and changes, and parameter evaluation.

Uploaded by

Daddy Bruce
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views59 pages

cmps445 Lecture8

The document discusses expressions, control structures, and statements in programming languages. It covers: - Expressions like arithmetic, relational, and boolean expressions. - Selection statements like if-then-else and switch statements that allow conditional execution. - Iterative statements like for loops and while loops that allow repeated execution based on counters or logical conditions. - Issues in designing control structures like nested statement scopes, loop variable types and changes, and parameter evaluation.

Uploaded by

Daddy Bruce
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

STATEMENT

LEVEL CONTROL
STRUCTURES
EXPRESSIONS
 Expressions are the fundamental means of specifying
computations in a programming language
 Arithmetic Expressions
 Unary e.g. -5
 Binary e.g. 2 * 3
 Ternary e.g. x ? y : z
 Precedence levels (BEDMAS)
OPERATORS AND TYPES
 Overloaded operators
 use of an operator for more than one purpose

 Type conversions
 Narrowing conversion e.g. float to int
 Widening conversion e.g. int to float
 Implicit (coercion ) vs explicit (cast) type conversion
MORE EXPRESSIONS
 Relational and Boolean expressions
 Short circuit evaluation

 Assignment statements
 Multiple assignments
 Mixed-mode assignments
TOPICS
 Introduction
 Selection Statements
 Iterative Statements
 Unconditional Branching
 Guarded Commands
 Conclusions
INTRODUCTION
▪ Levels of Control Flow
▪ Within expressions (Chapter 7)
▪ Among program units (Chapter 9)
▪ Among program statements (this chapter)
INTRODUCTION
 Def: Statements that provide capabilities such as selecting
among alternative control flow paths or causing the repeated
execution of certain collection of statements are called control
statements
 Def: A control structure is a control statement and the
statements whose execution it controls
Control
Structures

Selection Iterative Unconditional


Statements Statements Branching
SELECTION STATEMENTS
INTRODUCTION
 FORTRAN I: control statements were based directly on IBM 704 hardware
 Much research and argument in the1960s about the issue
 goto or not having goto

 One important result: It was proven that all flowcharts can be coded with
only two-way selection and pretest logical loops
 Language features that help make control statement design easier is a
method of forming statement collections.
 Compound statements introduced by ALGOL60 in the form of begin.. .end
 A block is a compound statement that can define a new scope (with local variables)
SELECTION STATEMENTS
 A selection statement provides the means of choosing between
two or more paths of execution
 Two general categories:
 Two-way selectors
 Select one of two execution paths: if-then-else statements.
 Multiple-way selectors
 Select one or multiple out of multiple execution paths: if-elseif and
switch statements.
TWO-WAY SELECTION STATEMENTS
 The general form is:
if control_expr
then clause
else clause
 Design issues
 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?
TWO-WAY SELECTION STATEMENTS
 The Control Expression:

 Specified in parenthesis when the then reserved word is not used (as in
C, C++, C#).
 Either arithmetic or Boolean expressions can be used (such as C++ and
Python).
 In other languages only Boolean expressions can be used for control
expression (such as Ada, Java and C#).
TWO-WAY SELECTION STATEMENTS
 Clause Form
 ALGOL 60 if: Control expression

if boolean_expr then clause

then statement else clause

else statement
The statements could be single or compound
CLAUSE FORM
 In many contemporary languages, the then and else clauses can be single
statements or compound statements
 In Perl, all clauses must be delimited by braces
 C-based languages use braces to form compound statements
 In Fortran 95, Ada, Python, and Ruby, clauses are statement sequences
 Python uses indentation to define clauses
if x > y :
x = y
print " x was greater than y"
TWO-WAY SELECTION STATEMENTS
 Nested Selectors
 e.g. (Java) if ...
if ...
...
else ...
 Which if gets the else?
 Java's static semantics rule: else goes with the nearest if
NESTING SELECTORS
 To force an alternative semantics, compound statements may be
used:
if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;

 The above solution is used in C, C++, and C#


NESTING SELECTORS
 Ada solution – closing special words
 e.g. (Ada)
if ... then if ... then
if ... then if ... then
... ...
else end if
... else
end if ...
end if end if

 Advantage: readability
NESTING SELECTORS
 In Ruby:  In Python
if sum == 0 then if sum == 0 :
if count == 0 then if count == 0 :
result = 0 result = 0
else
else :
result = 1
result = 1
end
end
SELECTOR EXPRESSIONS
 In ML, F#, and LISP, the selector is an expression
 F#
let y =
if x > 0 then x
else 2 * x;;

- If the if expression returns a value, there must be an else clause (the


expression could produce output, rather than a value)
MULTIPLE-WAY SELECTION STATEMENTS
 Allows the selection of one of any number of statements or
statement groups.
 The C, C++, Java and JavaScript switch
switch (expression)
{
case constant_expression_1 : statement_1;
...
case constant_expression_n : statement_n;
[default: statement_n+1]
}
MULTIPLE-WAY SELECTION STATEMENTS
 Design Choices for C’s switch statement
1. Control expression can be integer, characters or enumeration types
2. Selectable segments can be statement sequences, blocks, or compound
statements
3. Any number of segments can be executed in one execution of the
construct (there is no implicit branch at the end of selectable segments).
To avoid it, the programmer must supply a break statement for each
segment
4. default clause is for unrepresented values
MULTIPLE-WAY SELECTION: EXAMPLES
 C#
 Differs from C in that it has a static semantics rule that disallows the
implicit execution of more than one segment
 Each selectable segment must end with an unconditional branch
(goto or break)
 Also, in C# the control expression and the case constants can be
strings
MULTIPLE-WAY SELECTION: EXAMPLES
 C#

switch (value) {
case -1:
Negatives++;
break;
case 0:
Positives++;
goto case 1;
case 1:
Positives ++;
break;
default:
Console.WriteLine(“Error in switch \n”);
}
MULTIPLE-WAY SELECTION: EXAMPLES
 Ruby
leap = case
when year % 400 == 0 then true
when year % 100 == 0 then false
else year % 4 == 0
end

 Another form in Ruby is similar to the switch in Java

 Perl, Python, Lua


 No multiple-selection statements
MULTIPLE-WAY SELECTION USING IF
 Multiple Selectors can appear as direct extensions to two-way
selectors, using else-if clauses
e.g., Ada:
if ...
then ...
elsif ...
then ...
elsif ...
then ...
else ...
end if
MULTIPLE-WAY SELECTION USING IF

 In Python: if ocunt < 10 :

if count < 10 : bag1 = True

bag1 = True else:

elif count < 100 : if count < 100 :

bag2 = True bag2 = True

elif count < 1000 : else :

bag3 = True if count < 1000 :


bag3 = True

 Multiple-way selector is far more readable than deeply nested if's


MULTIPLE-WAY SELECTION USING IF
 The Python example can be written as a Ruby case
case
when count < 10 then bag1 = true
when count < 100 then bag2 = true
when count < 1000 then bag3 = true
end
ITERATIVE STATEMENTS
ITERATIVE STATEMENTS
 The repeated execution of a statement or compound statement
is accomplished by iteration zero, one, or more times.
 Iteration is the essence of the power of the computer
 The repeated execution of a statement is often accomplished in
a functional language by recursion rather then by iteration.
 The primary possibilities for iteration control are logical,
counting, or a combination of the two.
ITERATIVE STATEMENTS
 General design issues for iteration control statements:
 1. How is iteration controlled?
 2. Where is the control mechanism in the loop?

 The primary possibilities for iteration control are logical,


counting, or a combination of the two.
 The main choices for the location of the control mechanism are
the top of the loop or the bottom of the loop.
ITERATIVE STATEMENTS
 The body of a loop is the collection of statements whose execution is
controlled by the iteration statement.
 The term pretest tests loop condition before each iteration
i.e. the loop completion occurs before the loop body is executed.
 The term posttest means that the loop completion occurs after the
loop body is executed.
 The iteration statement and the associated loop body together form
an iteration construct.
COUNTER-CONTROLLED LOOPS
 A counting iterative control statement has a
var, called the loop var or sentinel, in which
the count value is maintained.
 It also includes means of specifying the intial
and terminal values of the loop var, and the
difference between sequential loop var values,
called the stepsize.
 The intial, terminal and stepsize are called the
loop parameters.
COUNTER-CONTROLLED LOOPS
 Design Issues:
1. What are the type and scope of the loop variable?
2. What is the value of the loop variable at loop termination?
3. 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?
4. Should the loop parameters be evaluated only once, or once for every
iteration?
COUNTER-CONTROLLED LOOPS
1. C
 Syntax:
for (expr_1 ; expr_2 ; expr_3)
loop body
 The expressions can be whole statements, or even statement
sequences, with the statements separated by commas
 The value of a multiple-statement expression is the value of the
last statement in the expression
for (i = 0, j = 10; j == i; i++) …
ITERATIVE STATEMENTS
1. C
1. There is no explicit loop variable
2. Everything can be changed in the loop
3. The first expression is evaluated once, but the other two are evaluated
with each iteration
4. All the expressions are optional. If the middle expression is empty it
means TRUE

 This loop statement is the most flexible


COUNTER-CONTROLLED LOOPS
2. FORTRAN 90
 Syntax:
DO label var = start, finish [, stepsize]
 stepsize can be any value but zero
 Parameters can be expressions
 Loop variable must be INTEGER
 Loop parameters are evaluated only once
 The loop variable cannot be changed in the loop, but the parameters can;
because they are evaluated only once, it does not affect loop control
COUNTER-CONTROLLED LOOPS
3. Ada
 Syntax:
for var in [reverse] discrete_range loop
...
end loop
 The loop variable does not exist outside the loop
 The loop variable cannot be changed in the loop, but the discrete range
can; it does not affect loop control
 The discrete range is evaluated just once
COUNTER-CONTROLLED LOOPS
4. C++
 Differs from C in two ways:
1. The control expression can also be Boolean
2. The initial expression can include variable definitions (scope is from the
definition to the end of the loop body)
5. Java, C#
 Differs from C++ in that the control expression must be
Boolean
LOGICALLY-CONTROLLED LOOPS
 Repetition control is based on Boolean
expression rather than a counter.
 Every counting loop can be written as a logically-
controlled loop, but the reverse is not true
 Design Issues:
1. Pretest or posttest?
2. Should it be a special case of the counting loop (or a
separate statement)?
LOGICALLY-CONTROLLED LOOPS
 C#
pretest

posttest
LOGICALLY-CONTROLLED LOOPS
 Language Examples:
1. C and C++ have both pretest and posttest, but the
control expression for the posttest version is treated just
like in the pretest case (while and do - while)
2. Java is like C, except the control expression must be
Boolean and the body can only be entered at the
beginning--Java has no goto
LOGICALLY-CONTROLLED LOOPS

 Language Examples:
3. Ada has a pretest version, but no posttest
4. FORTRAN 77 and 90 have neither
5. Perl has two pretest logical loops, while and until, but no
posttest logical loop
USER-LOCATED LOOP CONTROL MECHANISMS

 It is convenient for a programmer to choose a


location for loop control other than the top or the
bottom of the loop

 Design issues:
1. Should the conditional be part of the exit?
2. Should control be transferable out of more than one
loop?
USER-LOCATED LOOP CONTROL MECHANISMS

 Language Examples:
 C , C++, C# and Java – break
 Perl - last

 In Java and Perl, you can use a labelled exit (specify which loop
to exit)
 Not available in C, C++, python, Ruby and C#

 There is also a continue statement for loops; it skips the


remainder of this iteration, but does not exit the loop
USER-LOCATED LOOP CONTROL MECHANISMS
ITERATION BASED ON DATA STRUCTURES
 Concept: use order and number of elements of some data
structure to control iteration
 Control mechanism is a call to a function that returns the next
element in some chosen order, if there is one; else exit loop
 C's for can be used to build a user-defined iterator
 e.g. for (p=hdr; p; p=next(p))
{ ... }
UNCONDITIONAL BRANCHING
UNCONDITIONAL BRANCHING
 An unconditional branch statement transfers
execution control to specified place in the
program (e.g., goto)

 Problem: readability
 Some languages do not have them: e.g., Java
GUARDED COMMANDS
GUARDED COMMANDS
 Dijkstra, 1975
 Basis for two linguistic mechanisms for concurrent programming
(in CSP, Ada, Haskell)
 Basic Idea: if the order of evaluation is not important, the
program should not specify one
 Purpose: to support a new programming methodology
(verification during program development)
GUARDED COMMANDS
Selection: if <boolean> -> <statement>
[]<boolean> -> <statement>
...
[] <boolean> -> <statement>
fi
 Semantics: when this construct is reached,
 Evaluate all Boolean expressions
 If more than one are true, choose one nondeterministically
 If none are true, it is a runtime error
GUARDED COMMANDS
EXAMPLE
 To find the largest of two numbers, we can use
if x >= y -> max := x
[] y >= x -> max := y
fi
 This computes the desired result without over specifying
the solution.
 If x and y are equal, it does not matter which we assign to
max.
GUARDED COMMANDS
Loops
do <boolean> -> <statement>
[] <boolean> -> <statement>
...
[] <boolean> -> <statement>
od
GUARDED COMMANDS
 Semantics: For each iteration:
 Evaluate all boolean expressions
 If more than one are true, choose one nondeterministically; then start
loop again
 If none are true, exit loop
GUARDED COMMANDS
EXAMPLE
 Consider the following problem: Given four integer variables,
q1, q2, q3,and q4, we need to rearrange the values of the four
so that q1 ≤ q2 ≤ q3 ≤ q4.
 Solution using guarded commands:
do q1 > q2 -> temp := q1; q1 := q2; q2 := temp;
[] q2 > q3 -> temp := q2; q2 := q3; q3 := temp;
[] q3 > q4 -> temp := q3; q3 := q4; q4 := temp;
od
REFERENCES

58
SUBPROGRAMS

You might also like