0% found this document useful (0 votes)
25 views

11-Sequence Control (Expressions, Statements)

The document discusses sequence control in programming, including expressions, statements, and program units. It covers expression evaluation, conditional expressions, assignment statements, control structures like if/else and switch statements, and iterative statements like for loops. Key points include expression syntax and evaluation order, short-circuit evaluation, dangling else problems, counter-controlled loop syntax, and semantic differences between languages.
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)
25 views

11-Sequence Control (Expressions, Statements)

The document discusses sequence control in programming, including expressions, statements, and program units. It covers expression evaluation, conditional expressions, assignment statements, control structures like if/else and switch statements, and iterative statements like for loops. Key points include expression syntax and evaluation order, short-circuit evaluation, dangling else problems, counter-controlled loop syntax, and semantic differences between languages.
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/ 37

Sequence Control

Dr. Nguyen Hua Phung

HCMC University of Technology, Viet Nam

December 7, 2020

Dr. Nguyen Hua Phung Sequence Control 1 / 40


Outline

1 Expressions

2 Statements

3 Program Units

Dr. Nguyen Hua Phung Sequence Control 2 / 40


Expressions

An expression is a syntactic entity whose evaluation


either:
produces a value
fails to terminate → undefined
Examples
4+3*2
(a + b) * (c - a)
(b != 0) ? (a/b) : 0

Dr. Nguyen Hua Phung Sequence Control 4 / 40


Expressions (cont’d)

Expression Evaluation Mechanism


Expressions have functional composition nature
*

+ - (a + b) * (c - d)

a b c d

Expression Syntax
Infix
Prefix
Postfix

Dr. Nguyen Hua Phung Sequence Control 5 / 40


Infix Notation

(a + b) * (c - d)

Good for binary operators


Used in most imperative programming language
More than two operands?
(b != 0) ? (a/b) : 0
Smalltalk:
myBox displayOn: myScreen at: 100@50

Dr. Nguyen Hua Phung Sequence Control 6 / 40


Precedence

3 + 4 * 5 = 23, not 35

Evaluation priorities in mathematics


Programming languages define their own precedence
levels based on mathematics
A bit different precedence rules among languages
can be confusing

Dr. Nguyen Hua Phung Sequence Control 7 / 40


Associativity

If operators have the same level of precedence, then


apply associativity rules
Mostly left-to-right, except exponentiation operator
An expression contains only one operator
Mathematics: associative
Computer: optimization but potential problems
1020 ∗ 1020 ∗ 10−20

Dr. Nguyen Hua Phung Sequence Control 8 / 40


Parentheses

Alter the precedence and associativity


(A + B) * C
Using parentheses, a language can even omit
precedence and associativity rules
APL
Advantage: simple
Disadvantage: writability and readability

Dr. Nguyen Hua Phung Sequence Control 9 / 40


Conditional Expressions

If statement

if (count == 0)
average = 0;
else
average = sum / count;

Conditional Expression
average = (count == 0) ? 0 : sum / count;
C-based languages, Perl, JavaScript, Ruby

Dr. Nguyen Hua Phung Sequence Control 10 / 40


Prefix Notation

Polish Prefix: * + a b - c d
Cambridge Polish Prefix: (* (+ a b) (- c d))
Normal Prefix: *(+(a,b),-(c,d))
Derived from mathematical function f(x,y)
Parentheses and precedence is no required,
provided the -arity of operator is known
Mostly see in unary operators
LISP: (append a b c my_list)

Dr. Nguyen Hua Phung Sequence Control 11 / 40


Postfix Notation

Polish Postfix: a b + c d - *
Cambridge Polish Postfix: ((a b +) (c d -) *)
Normal Postfix: ((a,b)+,(c,d)-)*
Common usage: factorial operator (5!)
Used in intermediate code by some compilers
PostScript: (Hello World!) show

Dr. Nguyen Hua Phung Sequence Control 12 / 40


Operand Evaluation Order

C program

int a = 5;
int fun1() {
a = 17;
return 3;
}
void main() {
a = a + fun1();
}

What is the value of a? 8 20


Reason: Side-effect on the operand of the expression

Dr. Nguyen Hua Phung Sequence Control 13 / 40


Evaluation Mechanisms

Eager evaluation
First evaluate all operands
Then operators
How about a == 0 ? b : b / a
Lazy evaluation
Pass the un-evaluated operands to the operator
Operator decide which operands are required
Much more expensive than eager
Lazy for conditional, eager for the rest

Dr. Nguyen Hua Phung Sequence Control 14 / 40


Short-Circuit Evaluation

(a == 0) || (b/a > 2)

If the first operand is evaluated as true, the second


will be short-circuited
Otherwise, "divide by zero"
How about (a > b) || (b++ / 3) ?
Some languages provide two sets of boolean
operators: short- and non short-circuit
Ada: "and", "or" versus "and then", "or else"

Dr. Nguyen Hua Phung Sequence Control 15 / 40


Statements

A statement is a syntactic entity whose evaluation:


does not return a value, but
changes the state of the system
Example,
a = 5;
print "pippo"
begin ... end

Dr. Nguyen Hua Phung Sequence Control 17 / 40


Assignment Statements

leftExpr AssignOperator rightExpr

a := b ;

address? value?

5 5

Evaluate left or right first is up to implementers

Dr. Nguyen Hua Phung Sequence Control 18 / 40


Assignment Statements

C-based languages consider assignment as an


expression
while ((ch = getchar()) != EOF) {...}
Introduce compound and unary assignment
operators (+=, -=, ++, –)
Increasing code legibility
Avoiding unforeseen side effects

Dr. Nguyen Hua Phung Sequence Control 19 / 40


Control Structures

Control statements
Selecting among alternative control flow paths
Causing the repeated execution of sequences of
statements
Control structure is a control statement and the
collection of its controlled statements

Dr. Nguyen Hua Phung Sequence Control 20 / 40


Two-way Selection

if control_expression
then clause
else clause

Proved to be fundamental and essential parts of all


programming languages

Dr. Nguyen Hua Phung Sequence Control 21 / 40


Dangling else

if (sum == 0)
if (count == 0)
result = 0;
else
result = 1;

Solution: including block in every cases


Not all languages have this problem
Fortran 95, Ada, Ruby: use a special word to end
the statement
Python: indentation matters

Dr. Nguyen Hua Phung Sequence Control 22 / 40


Multiple-Selection

Allows the selection of one of any number of


statements or statement groups
Perl, Python: don’t have this
Issues:
Type of selector expression?
How are selectable segments specified?
Execute only one segment or multiple segments?
How are case values specified?
What if values fall out of selectable segments?

Dr. Nguyen Hua Phung Sequence Control 23 / 40


Case Study: C

Type must be int


Exact value
- Stmt sequences
switch (index) { - Block
case 1:
case 3: odd += 1;
sumodd += index;
break; Multiple segments exited by break
case 2:
case 4: even += 1;
sumeven += index;
break;
default: printf("Error in switch").
}
for unrepresented values

Dr. Nguyen Hua Phung Sequence Control 24 / 40


Case Study: Pascal

Integer or character

- Single statement
case exp of - Block
1 : clause_A
2 , 7 : clause_B multiple values,
subrange
3 . . 5 : clause_C
1 0 : clause_D
else clause_E
end
for unrepresented values

Dr. Nguyen Hua Phung Sequence Control 25 / 40


Iterative Statements

Cause a statement or collection of statements to be


executed zero, one or more times
Essential for the power of the computer
Programs would be huge and inflexible
Large amounts of time to write
Mammoth amounts of memory to store
Design questions:
How is iteration controlled?
Logic, counting
Where should the control appear in the loop?
Pretest and posttest

Dr. Nguyen Hua Phung Sequence Control 26 / 40


Counter-Controlled Loops

Counter-controlled loops must have:


Loop variable
Initial and terminal values
Stepsize

Dr. Nguyen Hua Phung Sequence Control 27 / 40


Case Study: Algol-based

General form Semantic

constant [define end_save]


end_save := last
f o r i : = f i r s t to l a s t by s t e p i = first
do loop:
l o o p body if i > end_save goto out
end [loop body]
Known number of iterations i := i + step
before executing goto loop
out:
[undefine end_save]

Dr. Nguyen Hua Phung Sequence Control 28 / 40


Case study: C

General form Semantic

expr_1
f o r ( expr_1 ; expr_2 ; expr_3 ) loop:
l o o p body if expr_2 = 0 goto out
[loop body]
expr_3
Can be infinite loop goto loop
out: ...

Dr. Nguyen Hua Phung Sequence Control 29 / 40


Logically Controlled Loops

Repeat based on Boolean expression rather than a


counter
Are more general than counter-controlled
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?

Dr. Nguyen Hua Phung Sequence Control 30 / 40


Case Study: C

Forms Semantics

loop:
while (ctrl_expr) if ctrl_expr is false
loop body goto out
[loop body]
goto loop
out:...

do loop:
loop body [loop body]
while (ctrl_expr); if ctrl_expr goto loop

Dr. Nguyen Hua Phung Sequence Control 31 / 40


User-Located Loop Control

Programmer can choose a location for loop control


rather than top or bottom
Simple design: infinite loops but include user-located
loop exits
Languages have exit statements: break and
continue
A need for restricted goto statement

Dr. Nguyen Hua Phung Sequence Control 32 / 40


Case Study: C

while (sum < 1000) {


getnext(value);
if (value < 0) break;
sum += value;
}
What if we replace break by continue?

Dr. Nguyen Hua Phung Sequence Control 33 / 40


Iteration Based on Data Structures

Controlled by the number of elements in a data


structure
Iterator:
Called at the beginning of each iteration
Returns an element each time it is called in
some specific order
Pre-defined or user-defined iterator

Dr. Nguyen Hua Phung Sequence Control 34 / 40


Case Study: Java

A r r a y L i s t a l = new A r r a y L i s t ( ) ;
...
Iterator i t = al . i t e r a t o r ( ) ;
while ( i t . hasNext ( ) ) {
O b j e c t element = i t . n e x t ( ) ;
...
}

Dr. Nguyen Hua Phung Sequence Control 35 / 40


Case Study: C]

String[] strList = {"Bob","Carol","Ted"};


...
foreach (String name in strList)
Console.WriteLine("Name:{0}", name);

Dr. Nguyen Hua Phung Sequence Control 36 / 40


Unconditional Branching

Unconditional branch, or goto, is the most powerful


statement for controlling the flow of execution of a
program’s statements
Dangerous: difficult to read, as the result, highly
unreliable and costly to maintain
Structured programming: say no to goto
Java, Python, Ruby: no goto
It still exists in form of loop exit, but they are severely
restricted gotos.

Dr. Nguyen Hua Phung Sequence Control 37 / 40


Program Units

to be continued

Dr. Nguyen Hua Phung Sequence Control 39 / 40


Summary

Expressions
Operator precedence and associativity
Side effects
Statements
Assignment
Selection Statement
Loop structures

Dr. Nguyen Hua Phung Sequence Control 40 / 40

You might also like