Chapter 8 Statement-Level Control Structures
Total Page:16
File Type:pdf, Size:1020Kb
Chapter 8 Statement-Level Control Structures 8.1 Introduction 330 8.2 Selection Statements 332 8.3 Iterative Statements 343 8.4 Unconditional Branching 355 8.5 Guarded Commands 356 8.6 Conclusions 358 Summary • Review Questions • Problem Set • Programming Exercises 359 CMPS401 Class Notes (Chap08) Page 1 / 17 Dr. Kuo-pao Yang Chapter 8 Statement-Level Control Structures 8.1 Introduction 330 A control structure is a control statement and the statements whose execution it controls – Selection Statements – Iterative Statements There is only one design issue that is relevant to all of the selection and iteration control statements: – Should a control structure have multiple entries? 8.2 Selection Statements 332 A selection statement provides the means of choosing between two or more paths of execution. Selection statement fall into two general categories: – Two-way selection – Multiple-way selection 8.2.1 Two-Way Selection Statements The general form of a two-way selector is as follows: if control_expression then clause else clause Design issues – What is the form and type of the control expression? – How are the then and else clauses specified? – How should the meaning of nested selectors be specified? The control expression – Control expressions are specified in parenthesis if the then reserved word is not used to introduce the then clause, as in the C-based languages – In C89, which did not have a Boolean data type, arithmetic expressions were used as control expressions – In contemporary languages, such as Java and C#, only Boolean expressions can be used for control expressions CMPS401 Class Notes (Chap08) Page 2 / 17 Dr. Kuo-pao Yang Clause Form – In most contemporary languages, the then and else clauses either appear as single statements or compound statements. – C-based languages use braces to form compound statements. – One exception is Perl, in which all then and else clauses must be compound statements, even if they contain single statements – In Python and Ruby, clauses are statement sequences – Python uses indentation to define clauses if x > y : x = y print " x was greater than y" . All statements equally indented are included in the compound statement. Notice that rather than then, a colon is used to introduce the then clause in the Python CMPS401 Class Notes (Chap08) Page 3 / 17 Dr. Kuo-pao Yang Nesting Selectors – In Java and contemporary languages, the static semantics of the language specify that the else clause is always paired with the nearest unpaired then clause if (sum == 0) if (count == 0) result = 0; else result = 1; . A rule, rather than a syntactic entity, is used to provide the disambiguation . So, in the example, the else clause would be the alternative to the second then clause . To force the alternative semantics in Java, a different syntactic form is required, in which the inner if is put in a compound, as in if (sum == 0) { if (count == 0) result = 0; } else result = 1; – C, C++, and C# have the same problem as Java with selection statement nesting – Ruby, statement sequences as clauses: if sum == 0 then if count == 0 then result = 0 else result = 1 end end – Python, all statements uses indentation to define clauses if sum == 0 : if count == 0 : result = 0 else : result = 1 CMPS401 Class Notes (Chap08) Page 4 / 17 Dr. Kuo-pao Yang 8.2.2 Multiple Selection Constructs The multiple selection construct allows the selection of one of any number of statements or statement groups. Design Issues – What is the form and type of the control expression? – How are the selectable segments specified? – Is execution flow through the structure restricted to include just a single selectable segment? – How are case values specified? – What is done about unrepresented expression values? C, C++, Java, and JavaScript switch switch (expression) { case constant_expression1 : statement1; ... case constant_expressionn : statementn; [default: statementn+1] } – The control expression and the constant expressions some discrete type including integer types as well as character and enumeration types – The selectable statements can be statement sequences, blocks, or compound statements – Any number of segments can be executed in one execution of the construct (there is no implicit branch at the end of selectable segments) – default clause is for unrepresented values (if there is no default, the whole statement does nothing) – Any number of segments can be executed in one execution of the construct (a trade-off between reliability and flexibility—convenience.) – To avoid it, the programmer must supply a break statement for each segment. C# switch – C# switch statement differs from C-based in that C# has static semantic rule disallows the implicit execution of more than one segment – The rule is that every selectable segment must end with an explicit unconditional branch statement either a break, which transfers control out of the switch construct, or a goto, which can transfer control to on of the selectable segments. C# switch statement example: switch (value) { case -1: Negatives++; break; case 0: Positives++; goto case 1; case 1: Positives ++; default: Console.WriteLine(“Error in switch \n”); } CMPS401 Class Notes (Chap08) Page 5 / 17 Dr. Kuo-pao Yang Multiple Selection Using if – Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses – Ex, Python selector statement (note that else-if is spelled elif in Python): if count < 10 : bag1 = True elif count < 100 : bag2 = True elif count < 1000 : bag3 = True which is equivalent to the following: if count < 10 : bag1 = True else : if Count < 100 : bag2 = True else : if Count < 1000 : bag3 = True . The elsif version is the more readable of the two. – The Python example can be written as a Ruby case case when count < 10 then bag1 = true when count < 100 then bag2 = true when count < 1000 then bag3 = true end – Notice that this example is not easily simulated with a switch-case statement, because each selectable statement is chosen on the basis of a Boolean expression – In fact, none of the multiple selectors in contemporary languages are as general as the if- then-else-if statement CMPS401 Class Notes (Chap08) Page 6 / 17 Dr. Kuo-pao Yang 8.3 Iterative Statements 343 An iterative statement is one that cause a statement or collection of statements to be executed zero, one, or more times The repeated execution of a statement or compound statement is accomplished either by iteration or recursion An iterative statement is often called loop Iteration is the very essence of the power of computer The repeated execution of a statement is often accomplished in a functional language by recursion rather than by iteration General design issues for iteration control statements: – How is iteration controlled? – Where should the control mechanism appear in the loop statement? The primary possibilities for iteration control are logical, counting, or a combination of the two The main choices for the location of the control mechanism are the top of the loop or the bottom of the loop The body of a loop is the collection of statements whose execution is controlled by the iteration statement The term pretest means that the loop completion occurs before the loop body is executed The term posttest means that the loop completion occurs after the loop body is executed . The iteration statement and the associated loop body together form an iteration statement CMPS401 Class Notes (Chap08) Page 7 / 17 Dr. Kuo-pao Yang 8.3.1 Counter-Controlled Loops A counting iterative control statement has a variable, called the loop variable, in which the count value is maintained It also includes means of specifying the intial and terminal values of the loop variable, and the difference between sequential loop variable values, called the stepsize. The intial, terminal and stepsize are called the loop parameters. Design issues: – What are the type and scope of the loop variable? – 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? – Fortran 90’s DO syntax: [name:] DO label variable = initial, terminal [, stepsize] . END DO [name] – The label is that of the last statement in the loop body, and the stepsize, when absent, defaults to 1. – Loop variable must be an INTEGER and may be either negative or positive. – The loop parameters are allowed to be expressions and can have negative or positive values. – They are evaluated at the beginning of the execution of the DO statement, and the value is used to compute an iteration count, which then has the number of times the loop is to be executed. – The loop is controlled by the iteration count, not the loop param, so even if the params are changed in the loop, which is legal, those changes cannot affect loop control. – The iteration count is an internal var that is inaccessible to the user code. – The DO statement is a single-entry structure CMPS401 Class Notes (Chap08) Page 8 / 17 Dr. Kuo-pao Yang The for statement of the C-based languages for ([expr_1] ; [expr_2] ; [expr_3]) loop body – The loop body can be a single statement, a compound statement, or a null statement for (count = 1; count <= 10; count++) . – All of the expressions of C’s for are optional – If the second expression is absent, it is an infinite loop – If the first and third expressions are absent, no assumptions are made – The C-based languages for design choices are: . There