SlideShare a Scribd company logo
1 of 50
Chapter 8
Control Structures
Two Way Selection Statement
Two Way Selection Statement
• ALGOL 60 2-way selector:
if (Boolean_expr)
then statement
else statement
• Nested if-else
• Special delimiters and selection closure ALGOL
68, FORTRAN 77, Ada use end if
Two Way Selection Statement
• 2-Way Selection Statements ALGOL 60's
solution - disallow direct nesting
Nesting Selectors
Nesting Selectors
• FORTRAN 90 and Ada solution – closing
special words
Multiple-Way Selection Statements
Design issues:
• What is the form and type of expression that controls the
selection
• May single statements, sequences of statements, or compound
statements be selected
• Is the entire construct encapsulated in a syntactic structure
• Is execution flow through the structure restricted to include just a
single selectable segment
• How should unrepresented selector expression values be
handled
Multiple Selection Statements
Design choices:
• Expression is any ordinal type
(int, boolean, char, enum)
• Segments can be single or compound
• Only one segment can be executed per execution of the
construct
• In Wirth's Pascal, result of an unrepresented control
expression value is undefined (In 1984 ISO Standard, it is a
runtime error)
• Many dialects now have otherwise or else clause
Modern multiple selectors
• C, C++, Java switch statement
• FORTRAN arithmetic IF
• Ada case statement
• Pascal case statement
Multiple Way Selection -Example
More reliable than C’s switch (once a stmt_sequence execution
is completed, control is passed to the first statement after the
case statement
Multiple-Way Selection Using if
• Multiple Selectors can appear as direct extensions to two-way
selectors,
• using else-if clauses, for example in Python:
Multiple-Way Selection Using if
• The Python example can be written as a Ruby
case
Far more readable than deeply nested if 's Allows a Boolean gate on every
selectable group
Iterative Statements
• The repeated execution of a statement or
compound statement is accomplished either
by iteration or recursion
• General design issues for iteration control
statements:
1. How is iteration controlled?
2. Where is the control mechanism in the loop?
Counter-Controlled Loops
• A counting iterative statement has a loop variable, and a
means of specifying the initial and terminal, and stepsize
values
Design Issues:
• What are the type and scope of the loop variable?
• What is the value of the loop variable at loop termination?
• 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?
Iterative Statements: Examples
Design choices:
• 1. Loop variable must be INTEGER
• 2. Loop variable always has its last value
• 3. 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
• 4. Loop parameters are evaluated only once
Iterative Statements: Examples
Iterative Statements: Examples
• Ada
Iterative Statements: Examples
Ada Design choices:
• Type of the loop variable is that of the discrete range;
• its scope is the loop body (it is implicitly declared)
• 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
Iterative Statements: Examples
• C-based languages
for ([expr_1] ; [expr_2] ; [expr_3]) statement-
The expressions can be whole statements, or even statement
sequences, with the statements separated by commas
Design choices:-
• There is no explicit loop variable
• Everything can be changed in the loop
• The first expression is evaluated once, but the other two are
evaluated with each iteration
Iterative Statements: Examples
C++ differs from C in two ways:
• The control expression can also be Boolean
• The initial expression can include variable definitions (scope is
from the definition to the end of the loop body)
• Java and C#
-Differs from C++ in that the control expression must be
Boolean
Iterative Statements: Examples
Iterative Statements: Logically-Controlled
Loops
• Repetition control is based on a Boolean
expression
Design issues:
• Pretest or posttest?
• Should the logically controlled loop be a
special case of the counting loop statement or
a separate statement?
Iterative Statements: Logically-Controlled
Loops: Examples
• C and C++ have both pretest and posttest forms, in which the
control expression can be arithmetic:
• Java is like C and C++, except the control expression must be
Boolean
Iterative Statements: Logically-Controlled
Loops: Examples
• Ada has a pretest version, but no posttest
• FORTRAN 95 has neither
• Perl and Ruby have two pretest logical loops,
while and until. Perl also has two posttest
loops
Iterative Statements: 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)
• Simple design for single loops (e.g., break)
• Design issues for nested loops
• Should the conditional be part of the exit?
• Should control be transferable out of more
than one loop?
Iterative Statements: User-Located Loop
Control Mechanisms break and continue
• C , C++, Python, Ruby, and C# have unconditional unlabeled
exits (break)
• Java and Perl have unconditional labeled exits (break in Java,
last in Perl)
• C, C++, and Python have an unlabeled control statement,
continue, that skips the remainder of the current iteration,
but does not exit the loop
• Java and Perl have labeled versions of continue
Iterative Statements: Iteration Based on
Data Structures
• Number of elements of in a data structure control
loop iteration
• Control mechanism is a call to an iterator function
that returns the next element in some chosen order,
if there is one; else loop is terminate
• C's for can be used to build a user-defined iterator:
for (p=root; p==NULL; traverse(p)){
}
Iterative Statements: Iteration Based on
Data Structures
Unconditional Branching
• Transfers execution control to a specified place in the program
• Represented one of the most heated debates in 1960’s and
1970’s
• Well-known mechanism: goto statement
• Major concern: Readability
• Some languages do not support goto statement (e.g., Java)
• C# offers goto statement (can be used in switch statements)
• Loop exit statements are restricted and somewhat
camouflaged goto’s
Guarded Commands Designed by Dijkstra
• Purpose: to support a new programming
methodology that supported verification
(correctness) during development
• Basis for two linguistic mechanisms for concurrent
programming (in CSP and Ada)
• Basic Idea: if the order of evaluation is not
important, the program should not specify one
Guarded Commands
if <Boolean expression> -> <statement>
[ ] <Boolean expression> -> <statement>
[ ] . . .
[] <Boolean expression> -> <statement>
fi
• The closing reserved word, fi, is the opening reserved word spelled
backward. This form of closing reserved word is taken from ALGOL 68.
• The small blocks, called fatbars, are used to separate the guarded clauses
and allow the clauses to be statement sequences.
• Each line in the selection statement, consisting of a Boolean expression (a
guard) and a statement or statement sequence, is called a guarded
command.
Selection Guarded Command
Guarded Commands
• If more than one expression is true, one of the corresponding
statements can be non-deterministically chosen for execution.
• If i = 0 and j > i, this statement chooses non-deterministically
between the first and third assignment statements.
• If i is equal to j and is not zero, a runtime error occurs
because none of the conditions is true
Guarded Commands
• This computes the desired result without over-
specifying the solution.
• In particular, if x and y are equal, it does not matter
which we assign to max. This is a form of abstraction
provided by the nondeterministic semantics of the
statement
Selection Guarded Command: Illustrated
Guarded Command
The loop structure proposed by Dijkstra has the form
The semantics of this statement is that all Boolean expressions are
evaluated on each iteration. If more than one is true, one of the
associated statements is non-deterministically (perhaps randomly)
chosen for execution, after which the expressions are again evaluated.
When all expressions are simultaneously false, the loop terminates.
Guarded Commands
• Now, consider the following code, which uses guarded commands to solve
the same problem but in a more concise and elegant way.
Guarded Commands
• Dijkstra’s guarded command control statements are interesting, in part
because they illustrate how the syntax and semantics of statements can
have an impact on program verification and vice versa
Guarded Commands: Rationale
• Connection between control statements and
program verification is intimate
• Verification is impossible with goto statements
• Verification is possible with only selection and
logical pretest loops
• Verification is relatively simple with only
guarded commands
Lecture-13.ppt

More Related Content

Similar to Lecture-13.ppt

Chapter 8 review questions
Chapter 8 review questionsChapter 8 review questions
Chapter 8 review questionsloayshabaneh
 
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...FabMinds
 
Chapter05-Control Structures.pptx
Chapter05-Control Structures.pptxChapter05-Control Structures.pptx
Chapter05-Control Structures.pptxAdrianVANTOPINA
 
07 control+structures
07 control+structures07 control+structures
07 control+structuresbaran19901990
 
OCA JAVA - 2 Programming with Java Statements
 OCA JAVA - 2 Programming with Java Statements OCA JAVA - 2 Programming with Java Statements
OCA JAVA - 2 Programming with Java StatementsFernando Gil
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loopsManzoor ALam
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
MODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptxMODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptxsenthilkumar969017
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
control structure by shuja ahmad
control structure by shuja ahmadcontrol structure by shuja ahmad
control structure by shuja ahmadInocentshuja Ahmad
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesJason J Pulikkottil
 
Lect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute BeginnersLect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute BeginnersDr.YNM
 

Similar to Lecture-13.ppt (20)

Chapter 8 review questions
Chapter 8 review questionsChapter 8 review questions
Chapter 8 review questions
 
Java 2.pptx
Java 2.pptxJava 2.pptx
Java 2.pptx
 
Loop invariant computation
Loop invariant computationLoop invariant computation
Loop invariant computation
 
data types.pdf
data types.pdfdata types.pdf
data types.pdf
 
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...
 
Control structure
Control structureControl structure
Control structure
 
Chapter05-Control Structures.pptx
Chapter05-Control Structures.pptxChapter05-Control Structures.pptx
Chapter05-Control Structures.pptx
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
OCA JAVA - 2 Programming with Java Statements
 OCA JAVA - 2 Programming with Java Statements OCA JAVA - 2 Programming with Java Statements
OCA JAVA - 2 Programming with Java Statements
 
03 conditions loops
03   conditions loops03   conditions loops
03 conditions loops
 
Control structures in C
Control structures in CControl structures in C
Control structures in C
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
MODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptxMODULE 3 process synchronizationnnn.pptx
MODULE 3 process synchronizationnnn.pptx
 
Tutorial PM.pptx
Tutorial PM.pptxTutorial PM.pptx
Tutorial PM.pptx
 
Csc240 -lecture_2
Csc240  -lecture_2Csc240  -lecture_2
Csc240 -lecture_2
 
Software Testing
Software Testing Software Testing
Software Testing
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
control structure by shuja ahmad
control structure by shuja ahmadcontrol structure by shuja ahmad
control structure by shuja ahmad
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniques
 
Lect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute BeginnersLect 7: Verilog Behavioral model for Absolute Beginners
Lect 7: Verilog Behavioral model for Absolute Beginners
 

Recently uploaded

Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 

Recently uploaded (20)

Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 

Lecture-13.ppt

  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. Two Way Selection Statement
  • 9. Two Way Selection Statement • ALGOL 60 2-way selector: if (Boolean_expr) then statement else statement • Nested if-else • Special delimiters and selection closure ALGOL 68, FORTRAN 77, Ada use end if
  • 10. Two Way Selection Statement • 2-Way Selection Statements ALGOL 60's solution - disallow direct nesting
  • 12.
  • 13.
  • 14.
  • 15. Nesting Selectors • FORTRAN 90 and Ada solution – closing special words
  • 16. Multiple-Way Selection Statements Design issues: • What is the form and type of expression that controls the selection • May single statements, sequences of statements, or compound statements be selected • Is the entire construct encapsulated in a syntactic structure • Is execution flow through the structure restricted to include just a single selectable segment • How should unrepresented selector expression values be handled
  • 17. Multiple Selection Statements Design choices: • Expression is any ordinal type (int, boolean, char, enum) • Segments can be single or compound • Only one segment can be executed per execution of the construct • In Wirth's Pascal, result of an unrepresented control expression value is undefined (In 1984 ISO Standard, it is a runtime error) • Many dialects now have otherwise or else clause
  • 18.
  • 19. Modern multiple selectors • C, C++, Java switch statement • FORTRAN arithmetic IF • Ada case statement • Pascal case statement
  • 20. Multiple Way Selection -Example More reliable than C’s switch (once a stmt_sequence execution is completed, control is passed to the first statement after the case statement
  • 21. Multiple-Way Selection Using if • Multiple Selectors can appear as direct extensions to two-way selectors, • using else-if clauses, for example in Python:
  • 22. Multiple-Way Selection Using if • The Python example can be written as a Ruby case Far more readable than deeply nested if 's Allows a Boolean gate on every selectable group
  • 23. Iterative Statements • The repeated execution of a statement or compound statement is accomplished either by iteration or recursion • General design issues for iteration control statements: 1. How is iteration controlled? 2. Where is the control mechanism in the loop?
  • 24. Counter-Controlled Loops • A counting iterative statement has a loop variable, and a means of specifying the initial and terminal, and stepsize values Design Issues: • What are the type and scope of the loop variable? • What is the value of the loop variable at loop termination? • 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?
  • 25. Iterative Statements: Examples Design choices: • 1. Loop variable must be INTEGER • 2. Loop variable always has its last value • 3. 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 • 4. Loop parameters are evaluated only once
  • 28. Iterative Statements: Examples Ada Design choices: • Type of the loop variable is that of the discrete range; • its scope is the loop body (it is implicitly declared) • 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
  • 29. Iterative Statements: Examples • C-based languages for ([expr_1] ; [expr_2] ; [expr_3]) statement- The expressions can be whole statements, or even statement sequences, with the statements separated by commas Design choices:- • There is no explicit loop variable • Everything can be changed in the loop • The first expression is evaluated once, but the other two are evaluated with each iteration
  • 30. Iterative Statements: Examples C++ differs from C in two ways: • The control expression can also be Boolean • The initial expression can include variable definitions (scope is from the definition to the end of the loop body) • Java and C# -Differs from C++ in that the control expression must be Boolean
  • 32. Iterative Statements: Logically-Controlled Loops • Repetition control is based on a Boolean expression Design issues: • Pretest or posttest? • Should the logically controlled loop be a special case of the counting loop statement or a separate statement?
  • 33. Iterative Statements: Logically-Controlled Loops: Examples • C and C++ have both pretest and posttest forms, in which the control expression can be arithmetic: • Java is like C and C++, except the control expression must be Boolean
  • 34. Iterative Statements: Logically-Controlled Loops: Examples • Ada has a pretest version, but no posttest • FORTRAN 95 has neither • Perl and Ruby have two pretest logical loops, while and until. Perl also has two posttest loops
  • 35. Iterative Statements: 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) • Simple design for single loops (e.g., break) • Design issues for nested loops • Should the conditional be part of the exit? • Should control be transferable out of more than one loop?
  • 36. Iterative Statements: User-Located Loop Control Mechanisms break and continue • C , C++, Python, Ruby, and C# have unconditional unlabeled exits (break) • Java and Perl have unconditional labeled exits (break in Java, last in Perl) • C, C++, and Python have an unlabeled control statement, continue, that skips the remainder of the current iteration, but does not exit the loop • Java and Perl have labeled versions of continue
  • 37. Iterative Statements: Iteration Based on Data Structures • Number of elements of in a data structure control loop iteration • Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate • C's for can be used to build a user-defined iterator: for (p=root; p==NULL; traverse(p)){ }
  • 38. Iterative Statements: Iteration Based on Data Structures
  • 39. Unconditional Branching • Transfers execution control to a specified place in the program • Represented one of the most heated debates in 1960’s and 1970’s • Well-known mechanism: goto statement • Major concern: Readability • Some languages do not support goto statement (e.g., Java) • C# offers goto statement (can be used in switch statements) • Loop exit statements are restricted and somewhat camouflaged goto’s
  • 40. Guarded Commands Designed by Dijkstra • Purpose: to support a new programming methodology that supported verification (correctness) during development • Basis for two linguistic mechanisms for concurrent programming (in CSP and Ada) • Basic Idea: if the order of evaluation is not important, the program should not specify one
  • 41. Guarded Commands if <Boolean expression> -> <statement> [ ] <Boolean expression> -> <statement> [ ] . . . [] <Boolean expression> -> <statement> fi • The closing reserved word, fi, is the opening reserved word spelled backward. This form of closing reserved word is taken from ALGOL 68. • The small blocks, called fatbars, are used to separate the guarded clauses and allow the clauses to be statement sequences. • Each line in the selection statement, consisting of a Boolean expression (a guard) and a statement or statement sequence, is called a guarded command.
  • 43. Guarded Commands • If more than one expression is true, one of the corresponding statements can be non-deterministically chosen for execution. • If i = 0 and j > i, this statement chooses non-deterministically between the first and third assignment statements. • If i is equal to j and is not zero, a runtime error occurs because none of the conditions is true
  • 44. Guarded Commands • This computes the desired result without over- specifying the solution. • In particular, if x and y are equal, it does not matter which we assign to max. This is a form of abstraction provided by the nondeterministic semantics of the statement
  • 46. Guarded Command The loop structure proposed by Dijkstra has the form The semantics of this statement is that all Boolean expressions are evaluated on each iteration. If more than one is true, one of the associated statements is non-deterministically (perhaps randomly) chosen for execution, after which the expressions are again evaluated. When all expressions are simultaneously false, the loop terminates.
  • 47. Guarded Commands • Now, consider the following code, which uses guarded commands to solve the same problem but in a more concise and elegant way.
  • 48. Guarded Commands • Dijkstra’s guarded command control statements are interesting, in part because they illustrate how the syntax and semantics of statements can have an impact on program verification and vice versa
  • 49. Guarded Commands: Rationale • Connection between control statements and program verification is intimate • Verification is impossible with goto statements • Verification is possible with only selection and logical pretest loops • Verification is relatively simple with only guarded commands