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

What's hot

Yacc
YaccYacc
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code Generation
Eelco Visser
 
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion | Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
FabMinds
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
omercomail
 
Compiler Design Unit 4
Compiler Design Unit 4Compiler Design Unit 4
Compiler Design Unit 4
Jena Catherine Bel D
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
mcollison
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
Rutvik Pensionwar
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
Eelco Visser
 
Programming languages
Programming languagesProgramming languages
Programming languages
Eelco Visser
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
SURBHI SAROHA
 
Lex & yacc
Lex & yaccLex & yacc
Lex & yacc
Taha Malampatti
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
SURBHI SAROHA
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code Generation
Akhil Kaushik
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
Sami Said
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generationrawan_z
 
Introduction of bison
Introduction of bisonIntroduction of bison
Introduction of bisonvip_du
 
Lex Tool
Lex ToolLex Tool
Lex Tool
Rajan Shah
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flexvip_du
 

What's hot (20)

Yacc
YaccYacc
Yacc
 
Compiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code GenerationCompiler Construction | Lecture 13 | Code Generation
Compiler Construction | Lecture 13 | Code Generation
 
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion | Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
Python Programming | JNTUA | UNIT 2 | Conditionals and Recursion |
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
 
Compiler Design Unit 4
Compiler Design Unit 4Compiler Design Unit 4
Compiler Design Unit 4
 
Pi j1.2 variable-assignment
Pi j1.2 variable-assignmentPi j1.2 variable-assignment
Pi j1.2 variable-assignment
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Compiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow AnalysisCompiler Construction | Lecture 10 | Data-Flow Analysis
Compiler Construction | Lecture 10 | Data-Flow Analysis
 
Programming languages
Programming languagesProgramming languages
Programming languages
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
Lex & yacc
Lex & yaccLex & yacc
Lex & yacc
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
Symbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code GenerationSymbol Table, Error Handler & Code Generation
Symbol Table, Error Handler & Code Generation
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
 
Introduction of bison
Introduction of bisonIntroduction of bison
Introduction of bison
 
Lex Tool
Lex ToolLex Tool
Lex Tool
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flex
 

Similar to 07 control+structures

Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
Rasan Samarasinghe
 
chapter 6.pptx
chapter 6.pptxchapter 6.pptx
chapter 6.pptx
ThedronBerhanu
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
8 statement level
8 statement level8 statement level
8 statement level
Munawar Ahmed
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
raksharao
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
Vladislav Hadzhiyski
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
baran19901990
 
Plc part 3
Plc  part 3Plc  part 3
Plc part 3
Taymoor Nazmy
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
PurvaShyama
 
Lecture1
Lecture1Lecture1
Lecture1
Amisha Dalal
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
Akash Pandey
 
Python basics
Python basicsPython basics
Python basics
TIB Academy
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
luqman bawany
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
Julie Iskander
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
Mohamed Ali
 
Programming Language
Programming  LanguageProgramming  Language
Programming LanguageAdeel Hamid
 
C language
C languageC language
C language
Robo India
 

Similar to 07 control+structures (20)

Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
chapter 6.pptx
chapter 6.pptxchapter 6.pptx
chapter 6.pptx
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
8 statement level
8 statement level8 statement level
8 statement level
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Plc part 3
Plc  part 3Plc  part 3
Plc part 3
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
 
Lecture1
Lecture1Lecture1
Lecture1
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
AVR_Course_Day3 c programming
AVR_Course_Day3 c programmingAVR_Course_Day3 c programming
AVR_Course_Day3 c programming
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
C language
C languageC language
C language
 

More from baran19901990

Config websocket on apache
Config websocket on apacheConfig websocket on apache
Config websocket on apache
baran19901990
 
Nhập môn công tác kỹ sư
Nhập môn công tác kỹ sưNhập môn công tác kỹ sư
Nhập môn công tác kỹ sư
baran19901990
 
Tìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google MapTìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google Map
baran19901990
 
How to build a news website use CMS wordpress
How to build a news website use CMS wordpressHow to build a news website use CMS wordpress
How to build a news website use CMS wordpress
baran19901990
 
How to install nginx vs unicorn
How to install nginx vs unicornHow to install nginx vs unicorn
How to install nginx vs unicorn
baran19901990
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentationbaran19901990
 
Control structure
Control structureControl structure
Control structure
baran19901990
 
Subprogram
SubprogramSubprogram
Subprogram
baran19901990
 
Lexical
LexicalLexical
Lexical
baran19901990
 
Introduction
IntroductionIntroduction
Introduction
baran19901990
 
Datatype
DatatypeDatatype
Datatype
baran19901990
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
baran19901990
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
baran19901990
 
How to install git on ubuntu
How to install git on ubuntuHow to install git on ubuntu
How to install git on ubuntu
baran19901990
 

More from baran19901990 (20)

Config websocket on apache
Config websocket on apacheConfig websocket on apache
Config websocket on apache
 
Nhập môn công tác kỹ sư
Nhập môn công tác kỹ sưNhập môn công tác kỹ sư
Nhập môn công tác kỹ sư
 
Tìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google MapTìm đường đi xe buýt trong TPHCM bằng Google Map
Tìm đường đi xe buýt trong TPHCM bằng Google Map
 
How to build a news website use CMS wordpress
How to build a news website use CMS wordpressHow to build a news website use CMS wordpress
How to build a news website use CMS wordpress
 
How to install nginx vs unicorn
How to install nginx vs unicornHow to install nginx vs unicorn
How to install nginx vs unicorn
 
Untitled Presentation
Untitled PresentationUntitled Presentation
Untitled Presentation
 
Control structure
Control structureControl structure
Control structure
 
Subprogram
SubprogramSubprogram
Subprogram
 
Lexical
LexicalLexical
Lexical
 
Introduction
IntroductionIntroduction
Introduction
 
Datatype
DatatypeDatatype
Datatype
 
10 logic+programming+with+prolog
10 logic+programming+with+prolog10 logic+programming+with+prolog
10 logic+programming+with+prolog
 
09 implementing+subprograms
09 implementing+subprograms09 implementing+subprograms
09 implementing+subprograms
 
How to install git on ubuntu
How to install git on ubuntuHow to install git on ubuntu
How to install git on ubuntu
 
Ruby notification
Ruby notificationRuby notification
Ruby notification
 
Rails notification
Rails notificationRails notification
Rails notification
 
Linux notification
Linux notificationLinux notification
Linux notification
 
Lab4
Lab4Lab4
Lab4
 
Lab5
Lab5Lab5
Lab5
 
09
0909
09
 

Recently uploaded

Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
nhiyenphan2005
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Florence Consulting
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
keoku
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
CIOWomenMagazine
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 

Recently uploaded (20)

Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 

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