SlideShare a Scribd company logo
Chapter 7: Sequence Control 
Principles of Programming Languages
Contents 
•Arithmetic Expressions 
•Short-Circuit Evaluation 
•Assignment Statements 
•Selection Statements 
•Iterative Statements 
•Unconditional Branching
Levels of Control Flow 
•Within expressions 
•Among program units 
•Among program statements
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
Expression Syntax 
•Expressions have functional composition nature 
•Common syntax 
–Infix 
–Prefix 
–Postfix 
(a + b) * (c – a) 
* 
+ 
– 
a 
b 
c 
a
Infix Notation 
(a + b) * (c – a) 
•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
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
Precedence in Some Languages
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 * 10-20 * 10-20
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
Conditional Expressions 
if (count == 0) average = 0; else average = sum / count; 
average = (count == 0) ? 0 : sum / count; 
•C-based languages, Perl, JavaScript, Ruby
Prefix Notation 
* + a b – c a 
(* (+ a b) (– c a)) 
•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)
Postfix Notation 
a b + c a – * 
•Reverse Polish 
•Common usage: factorial operator (5!) 
•Used in intermediate code by some compilers 
•PostScript: 
(Hello World!) show
Operand Evaluation Order 
•C program 
int a = 5; int fun1() { a = 17; return 3; } void main() { a = a + fun1(); 
} 
•Reason: Side effect!!! 
What is the value of a?
Undefined Operands 
•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 
* 
+ 
– 
a 
b 
c 
a
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”
Statements 
•An expression is a syntactic entity whose evaluation: 
–does not return a value, but 
–have side effect 
•Examples: 
a = 5; 
print "pippo" 
begin...end
Assignment Statements 
expr1 OpAss expr2 
•Example: Pascal 
X := Y 
•Evaluate left or right first is up to implementers 
Address? 
Value? 
5 
5
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
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
Two-way Selection 
if control_expression then clause else clause 
•Proved to be fundamental and essential parts of all programming languages
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
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?
Case Study: C 
switch (index) { 
case 1: 
case 3: odd += 1; 
sumodd += index; 
break; 
case 2: 
case 4: even += 1; 
sumeven += index; 
break; 
default: printf(“Error in switch”). 
} 
integer 
- Stmt sequences - Blocks 
Multiple segments 
exited by break 
for unrepresented values 
exact value
Case Study: Pascal 
case exp of 1: clause_A 2, 7: clause_B 3..5: clause_C 10: clause_D else clause_E end 
Integer or character 
- Single statements 
- Blocks 
Only one segment 
for unrepresented values 
multiple values, subrange
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
Counter-Controlled Loops 
•Counter-controlled loops must have: 
–Loop variable 
–Initial and terminal values 
–Stepsize
Case Study: Algol-based 
General Form 
for i:=first to last by step 
do 
loop body 
end 
Semantic 
[define i] 
[define first_save] 
[define end_save] 
i = start_save 
loop: 
if i > end_save goto out 
[loop body] 
i := i + step 
goto loop 
out: 
[undefine i] 
constant 
Know number of loops before looping
Case Study: C 
General Form 
for (expr1; expr2; expr3) 
loop body 
Semantic 
expr_1 
loop: 
if expr_2 = 0 goto out 
[loop body] 
expr_3 
goto loop 
out: . . . 
Can be infinite loop
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?
Case Study: C 
Forms 
while (ctrl_expr) 
loop body 
do 
loop body 
while (ctrl_expr) 
Semantics 
loop: 
if ctrl_expr is false goto out 
[loop body] 
goto loop 
out: . . . 
loop: 
[loop body] 
if ctrl_expr is true goto loop
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
Case Study: C 
while (sum < 1000) { 
getnext(value); 
if (value < 0) break; 
sum += value; 
} 
•What if we replace break by continue?
Iteration Based on Data Structures 
•Rather than have a counter or Boolean expression, these loops are controlled by the number of elements in a data structure 
•Iterator: 
–Is 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
Case Study: C# 
String[] strList = {"Bob", "Carol", "Ted"}: 
. . . 
foreach (String name in strList) 
Console.WriteLine("Name: {0}", name);
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.
Conclusions 
•Expressions 
•Operator precedence and associativity 
•Side effects 
•Various forms of assignment 
•Variety of statement-level structures 
•Choice of control statements beyond selection and logical pretest loops is a trade-off between language size and writability

More Related Content

PPSX
Complete C++ programming Language Course
PPTX
Programming in java basics
DOC
Lex tool manual
PPT
Lexyacc
PPT
Lex and Yacc ppt
PPT
Compiler Design Tutorial
PPTX
C LANGUAGE - BESTECH SOLUTIONS
Complete C++ programming Language Course
Programming in java basics
Lex tool manual
Lexyacc
Lex and Yacc ppt
Compiler Design Tutorial
C LANGUAGE - BESTECH SOLUTIONS

What's hot (20)

PPTX
PDF
Compiler Construction | Lecture 13 | Code Generation
PPTX
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
PPTX
Intro f# functional_programming
PPTX
Yacc (yet another compiler compiler)
PPTX
Compiler Design Unit 4
PPTX
Pi j1.2 variable-assignment
PPTX
Introduction to C programming
PDF
Compiler Construction | Lecture 10 | Data-Flow Analysis
PDF
Programming languages
PPTX
C language (Part 2)
PPTX
Lex & yacc
PPTX
C programming language tutorial
PPT
Symbol Table, Error Handler & Code Generation
PPT
Lex (lexical analyzer)
PPTX
Intermediate code- generation
PPTX
Introduction of bison
PPTX
Lex Tool
PDF
20160520 what youneedtoknowaboutlambdas
PPTX
Introduction of flex
Compiler Construction | Lecture 13 | Code Generation
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Intro f# functional_programming
Yacc (yet another compiler compiler)
Compiler Design Unit 4
Pi j1.2 variable-assignment
Introduction to C programming
Compiler Construction | Lecture 10 | Data-Flow Analysis
Programming languages
C language (Part 2)
Lex & yacc
C programming language tutorial
Symbol Table, Error Handler & Code Generation
Lex (lexical analyzer)
Intermediate code- generation
Introduction of bison
Lex Tool
20160520 what youneedtoknowaboutlambdas
Introduction of flex
Ad

Similar to 07 control+structures (20)

PPSX
Esoft Metro Campus - Programming with C++
PPTX
OOP in C++ – Complete Unit 1 Guide with Examples & Key Concepts
PPTX
chapter 6.pptx
PPTX
Review of C programming language.pptx...
PPTX
Module_2_1_Building Python Programs_Final.pptx
PPT
02 functions, variables, basic input and output of c++
PPT
8 statement level
PPTX
Dr.C S Prasanth-Physics ppt.pptx computer
PPT
Data types and Operators
PPTX
Operators loops conditional and statements
PPT
85ec7 session2 c++
PDF
08 subprograms
PPTX
Plc part 3
PPTX
Lecture 01 Programming C for Beginners 001
PPTX
Introduction to C ++.pptx
PPT
OpenMP-Quinn17_L4bOpen <MP_Open MP_Open MP
PPT
ch4 is the one of biggest tool in AI.ppt
PDF
c programming L-1.pdf43333333544444444444444444444
PDF
Lecture1
PPSX
Java Tutorial
Esoft Metro Campus - Programming with C++
OOP in C++ – Complete Unit 1 Guide with Examples & Key Concepts
chapter 6.pptx
Review of C programming language.pptx...
Module_2_1_Building Python Programs_Final.pptx
02 functions, variables, basic input and output of c++
8 statement level
Dr.C S Prasanth-Physics ppt.pptx computer
Data types and Operators
Operators loops conditional and statements
85ec7 session2 c++
08 subprograms
Plc part 3
Lecture 01 Programming C for Beginners 001
Introduction to C ++.pptx
OpenMP-Quinn17_L4bOpen <MP_Open MP_Open MP
ch4 is the one of biggest tool in AI.ppt
c programming L-1.pdf43333333544444444444444444444
Lecture1
Java Tutorial
Ad

More from baran19901990 (20)

PDF
Config websocket on apache
PDF
Nhập môn công tác kỹ sư
PDF
Tìm đường đi xe buýt trong TPHCM bằng Google Map
PDF
How to build a news website use CMS wordpress
PDF
How to install nginx vs unicorn
PDF
Untitled Presentation
PDF
Control structure
PDF
Subprogram
PDF
Lexical
PDF
Introduction
PDF
Datatype
PDF
10 logic+programming+with+prolog
PDF
09 implementing+subprograms
PDF
How to install git on ubuntu
DOC
Ruby notification
DOC
Rails notification
DOC
Linux notification
PDF
PDF
Config websocket on apache
Nhập môn công tác kỹ sư
Tìm đường đi xe buýt trong TPHCM bằng Google Map
How to build a news website use CMS wordpress
How to install nginx vs unicorn
Untitled Presentation
Control structure
Subprogram
Lexical
Introduction
Datatype
10 logic+programming+with+prolog
09 implementing+subprograms
How to install git on ubuntu
Ruby notification
Rails notification
Linux notification

Recently uploaded (20)

PDF
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
PDF
SlidesGDGoCxRAIS about Google Dialogflow and NotebookLM.pdf
PDF
The New Creative Director: How AI Tools for Social Media Content Creation Are...
PPTX
Introduction to cybersecurity and digital nettiquette
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
PPTX
artificial intelligence overview of it and more
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PDF
The Ikigai Template _ Recalibrate How You Spend Your Time.pdf
PDF
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
PPTX
IPCNA VIRTUAL CLASSES INTERMEDIATE 6 PROJECT.pptx
PPTX
artificialintelligenceai1-copy-210604123353.pptx
PDF
si manuel quezon at mga nagawa sa bansang pilipinas
PPTX
newyork.pptxirantrafgshenepalchinachinane
PPT
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
PDF
Exploring VPS Hosting Trends for SMBs in 2025
PDF
Session 1 (Week 1)fghjmgfdsfgthyjkhfdsadfghjkhgfdsa
PDF
Introduction to the IoT system, how the IoT system works
PPTX
Layers_of_the_Earth_Grade7.pptx class by
PDF
The Evolution of Traditional to New Media .pdf
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
SlidesGDGoCxRAIS about Google Dialogflow and NotebookLM.pdf
The New Creative Director: How AI Tools for Social Media Content Creation Are...
Introduction to cybersecurity and digital nettiquette
Power Point - Lesson 3_2.pptx grad school presentation
artificial intelligence overview of it and more
Design_with_Watersergyerge45hrbgre4top (1).ppt
SASE Traffic Flow - ZTNA Connector-1.pdf
The Ikigai Template _ Recalibrate How You Spend Your Time.pdf
FINAL CALL-6th International Conference on Networks & IOT (NeTIOT 2025)
IPCNA VIRTUAL CLASSES INTERMEDIATE 6 PROJECT.pptx
artificialintelligenceai1-copy-210604123353.pptx
si manuel quezon at mga nagawa sa bansang pilipinas
newyork.pptxirantrafgshenepalchinachinane
isotopes_sddsadsaadasdasdasdasdsa1213.ppt
Exploring VPS Hosting Trends for SMBs in 2025
Session 1 (Week 1)fghjmgfdsfgthyjkhfdsadfghjkhgfdsa
Introduction to the IoT system, how the IoT system works
Layers_of_the_Earth_Grade7.pptx class by
The Evolution of Traditional to New Media .pdf

07 control+structures

  • 1. Chapter 7: Sequence Control Principles of Programming Languages
  • 2. Contents •Arithmetic Expressions •Short-Circuit Evaluation •Assignment Statements •Selection Statements •Iterative Statements •Unconditional Branching
  • 3. Levels of Control Flow •Within expressions •Among program units •Among program statements
  • 4. 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
  • 5. Expression Syntax •Expressions have functional composition nature •Common syntax –Infix –Prefix –Postfix (a + b) * (c – a) * + – a b c a
  • 6. Infix Notation (a + b) * (c – a) •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
  • 7. 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
  • 8. Precedence in Some Languages
  • 9. 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 * 10-20 * 10-20
  • 10. 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
  • 11. Conditional Expressions if (count == 0) average = 0; else average = sum / count; average = (count == 0) ? 0 : sum / count; •C-based languages, Perl, JavaScript, Ruby
  • 12. Prefix Notation * + a b – c a (* (+ a b) (– c a)) •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)
  • 13. Postfix Notation a b + c a – * •Reverse Polish •Common usage: factorial operator (5!) •Used in intermediate code by some compilers •PostScript: (Hello World!) show
  • 14. Operand Evaluation Order •C program int a = 5; int fun1() { a = 17; return 3; } void main() { a = a + fun1(); } •Reason: Side effect!!! What is the value of a?
  • 15. Undefined Operands •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 * + – a b c a
  • 16. 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”
  • 17. Statements •An expression is a syntactic entity whose evaluation: –does not return a value, but –have side effect •Examples: a = 5; print "pippo" begin...end
  • 18. Assignment Statements expr1 OpAss expr2 •Example: Pascal X := Y •Evaluate left or right first is up to implementers Address? Value? 5 5
  • 19. 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
  • 20. 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
  • 21. Two-way Selection if control_expression then clause else clause •Proved to be fundamental and essential parts of all programming languages
  • 22. 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
  • 23. 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?
  • 24. Case Study: C switch (index) { case 1: case 3: odd += 1; sumodd += index; break; case 2: case 4: even += 1; sumeven += index; break; default: printf(“Error in switch”). } integer - Stmt sequences - Blocks Multiple segments exited by break for unrepresented values exact value
  • 25. Case Study: Pascal case exp of 1: clause_A 2, 7: clause_B 3..5: clause_C 10: clause_D else clause_E end Integer or character - Single statements - Blocks Only one segment for unrepresented values multiple values, subrange
  • 26. 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
  • 27. Counter-Controlled Loops •Counter-controlled loops must have: –Loop variable –Initial and terminal values –Stepsize
  • 28. Case Study: Algol-based General Form for i:=first to last by step do loop body end Semantic [define i] [define first_save] [define end_save] i = start_save loop: if i > end_save goto out [loop body] i := i + step goto loop out: [undefine i] constant Know number of loops before looping
  • 29. Case Study: C General Form for (expr1; expr2; expr3) loop body Semantic expr_1 loop: if expr_2 = 0 goto out [loop body] expr_3 goto loop out: . . . Can be infinite loop
  • 30. 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?
  • 31. Case Study: C Forms while (ctrl_expr) loop body do loop body while (ctrl_expr) Semantics loop: if ctrl_expr is false goto out [loop body] goto loop out: . . . loop: [loop body] if ctrl_expr is true goto loop
  • 32. 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
  • 33. Case Study: C while (sum < 1000) { getnext(value); if (value < 0) break; sum += value; } •What if we replace break by continue?
  • 34. Iteration Based on Data Structures •Rather than have a counter or Boolean expression, these loops are controlled by the number of elements in a data structure •Iterator: –Is 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
  • 35. Case Study: C# String[] strList = {"Bob", "Carol", "Ted"}: . . . foreach (String name in strList) Console.WriteLine("Name: {0}", name);
  • 36. 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.
  • 37. Conclusions •Expressions •Operator precedence and associativity •Side effects •Various forms of assignment •Variety of statement-level structures •Choice of control statements beyond selection and logical pretest loops is a trade-off between language size and writability