Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 Chapter 8 Control Structures. Control Structures  A control structure is a control statement and the statements whose execution it controls.

Similar presentations


Presentation on theme: "Chapter 8 Chapter 8 Control Structures. Control Structures  A control structure is a control statement and the statements whose execution it controls."— Presentation transcript:

1 Chapter 8 Chapter 8 Control Structures

2 Control Structures  A control structure is a control statement and the statements whose execution it controls  Types of control statements:  Selection statements  Iterative statements  Unconditional branching statement  Levels of Control Flow: 1. Within expressions 2. Among program units 3. Among program statements

3 Design Issues  What control statements should a language have?  Can a control structure have multiple entries?  Single entry:  execution of the code segment begins with the first statement in the segment  Multiple entries are possible in languages that include gotos and statement labels  Multiple entries may add flexibility to a control construct  Can a control structure have multiple exits?

4 Selection Statements  Provides the means of choosing between two or more execution paths in a program  Types of Selection Statements:  One-way selection statements  Two-way selection statements  N-way (multiple) selection statements  Nested selection statements?

5 Selection Statements  Single-Way Examples FORTRAN IF: IF (boolean_expr) statement  Problem:  can select only a single statement; to select more, a GOTO must be used, as in the following example IF (.NOT. condition) GOTO 20... 20 CONTINUE

6 Selection Statements  Two-way selection statements if control_expression then clause else clause  Control_expression  arithmetic/Boolean expressions  Clause form  Can be single statements or compound statements (statements in a program block)

7 Selection Statements  Nested Selectors if (sum == 0) if (count == 0) result = 0; else result = 1;  Which if gets the else?  Java's static semantics rule: else goes with the nearest if  To force alternative semantics, use compound statement if (sum == 0) { if (count == 0) result = 0; } else result = 1;

8 Selection Statements  FORTRAN 90 and Ada solution  use special words to resolve semantics of nested selectors  e.g. (Ada) if... then if... then...... else end if... else end if... end if end if  Advantage: flexibility and readability

9 Selection Statements  Multiple Selection Constructs C: switch (expression) { case const_expr_1: statement_1; … case const_expr_k: statement_k; [default:def_statement;] (optional) }

10 Selection Statements  Early Multiple Selectors:  FORTRAN arithmetic IF (a three-way selector) IF (arithmetic expression) N1, N2, N3  Multiple Selection using if: if Expr1 then statement_1 elsif Expr2 then statement_2 … else statement_k end if;

11 Iterative Statements  Repeated execution of a statement or compound statement  accomplished either by iteration or recursion;  here we look at iteration, because recursion is a unit-level control (e.g., using functions)  General design issues for iteration control statements: 1. How is the iteration controlled?  Counter-controlled vs logical-controlled 2. Where should the control mechanism appear in the loop?  pretest (before loop body is executed) vs posttest (after loop body is executed)

12 Iterative Statements  Counter-Controlled Loops for (i = init_value; i < terminal_value; i+=stepsize) { … }  Design Issues: 1.What are the type and scope of the loop variable? 2.What is the value of the loop variable at loop termination? 3.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? 4.Should the loop parameters be evaluated only once, or once for every iteration? Loop parameters Loop variable

13 Counter-Controlled Loops  FORTRAN 95  Syntax: Do label var = initial, terminal [, stepsize]  stepsize can be any value but zero  parameters can be expressions  Design choices: 1. Loop var must be integer; loop parameters can be expressions 2. The loop var cannot be changed in the loop, but loop parameters can because they are evaluated only once, it does not affect loop control 3. Single entry structure – loop can be entered through Do statement

14 Counter-Controlled Loops  Fortran 95: Do label var = init_expression, terminal_expression [, step_expression] Operational Semantics for Fortran 95 Do statement init_value = init_expression terminal_value = terminal_expression step_value = step_expression do_var = init_value iteration_count = max(int((terminal_value–init_value+step_value)/step_value), 0) loop: if iteration_count  0 goto out [loop body] do_var = do_var + step_value iteration_count = interation_count – 1 goto loop out:…

15 Counter-Controlled Loops  Another form of Do statement for FORTRAN 95 [name:] DO variable = initial, terminal [, stepsize] … END DO [name]  Uses a special word for closing: END DO

16 Counter-Controlled Loops  Ada  Syntax: for var in [reverse] discrete_range loop... end loop;  reverse indicates that values of discrete range are assigned in reverse order  Step size is always one (or next element in discrete_range)

17 Counter-Controlled Loops  Ada Design choices: 1. Type of the loop var is that of the discrete range  discrete range is subrange of integer or enumeration type, such as 1..10 or Monday..Friday 2. Scope of loop var is the loop body (it is implicitly declared); loop var does not exist outside the loop Count : Float := 1.35; for Count in 1..10 loop Sum := Sum + Count; end loop; …Count gets the value of 1.35 3. The loop var cannot be changed in the loop, but the discrete range can; it does not affect loop control 4. The discrete range is evaluated just once

18 Counter-Controlled Loops  C-based languages  Syntax: for ([expr_1] ; [expr_2] ; [expr_3]) loop body  Loop body can be single statement, compound statement, or null statement  Expressions can be whole statements, or even statement sequences, with the statements separated by commas  The value of a multiple-statement expression is the value of the last statement in the expression for (i = 0, j = 10; j == i; i++) …  All expressions of C’s for statement are optional  If expr_2 is absent, it is an infinite loop

19 Counter-Controlled Loops for ([expr_1] ; [expr_2] ; [expr_3]) loop body  Operational Semantics: expr_1 loop: if expr_2 = 0 goto out [loop_body] expr_3 goto loop out:…

20 Counter-Controlled Loops  Design choices for C: 1. There is no explicit loop variable or loop parameters  All involved variables can be changed in the loop body 2. It is legal to branch into loop body 3. The first expression is evaluated once, but the other two are evaluated with each iteration

21 Counter-Controlled Loops #include main() { int count, i = 2; count = 2; /* count = 5 */ if (count % 2 == 0) { goto loop; } for (i=0; i<5; i++) { loop: printf("i=%d\n", i); } count = 2: i = 2; i = 3; i = 4; count = 5: i = 0; i = 1; i = 2; i = 3; i = 4;

22 Counter-Controlled Loops  C++  Differs from C in two ways: 1.The control expression can also be Boolean 2.The initial expression can include variable definitions (scope is from the definition to the end of the loop body) for (int i=0; i < len; i++) { … }  Java  Differs from C++ in that the control expression must be Boolean

23 Logically-Controlled Loops  Repetition control is based on a Boolean expression, rather than a counter  More general than counter-controlled loops  Every counting loop can be built with a logical loop, but not vice-versa  Design Issues: 1. Pretest or postest? 2. Should logically controlled loop be a special form of counting loop statement or a separate statement?

24 Logically-Controlled Loops  Pascal has separate pretest and posttest logical loop statements (while-do and repeat-until)  C and C++ also have both while (count > 0) { … } do { … } while (count > 0);  Legal to branch into both while and do loop bodies

25 Logically-Controlled Loops  Ada has a pretest version, but no posttest  FORTRAN 77, 90, and 95 have neither  Perl has two pretest logical loops, while and until, but no posttest logical loop while (count > 0) { … } until (count == 0) { … }

26 User-Located Loop Control  User modify the control flow of program  Design issues: 1.Should the conditional mechanism be an integral part of the exit? 2.Should only one loop body be exited or can enclosing loops also be exited?

27 User-Located Loop Control  Exit statement:  Unconditional unlabeled exit: break (C, C++) for (index=0; index<10; index++) { … if (value < 0) break; }  Unconditional labeled exit: break (Java, C#), last (Perl) C#: outerloop: for (row=0; row<numRows; row++) for (col = 0; col < numCols; col++) { sum += matrix[row][col]; if (sum > 1000) break outerLoop; } Perl: LINE: while ( ) { last LINE if /^$/;... }

28 User-Located Loop Control  Skip the rest of loop body:  C/C++ have unlabeled control statement (continue) while (sum < 1000) { value = getNextValue(); if (value < 0) continue; sum += value; }  Java, Perl, and C# have statements similar to continue, except they can include labels that specify which loop is continued

29 Iteration Based on Data Structures  Loops are controlled by number of elements in a data structure  Perl, Javascript, PHP, and C# have such statements Perl: @values = (1, 2, 3, 4, 5); foreach $value (@values) { print “Value is $value\n”; } C#: String[] strList = {“Bob”, “John”, “Carol” }; foreach (String name in strList) …  More general approach  uses a user-defined data structure and a user-defined function (called an iterator) to go through the structure’s elements  Java has a Collection interface that contains two methods: boolean add(Object obj) - adds elements to collection Iterator iterator() - used to visit the elements in the collection one by one.

30 Unconditional Branching  Transfers execution control to a specified location in the program goto label  Problem: readability  Some languages do not have them: e.g., Java  Loop exit statements are restricted and somewhat camouflaged goto’s  Label forms: 1. Unsigned int constants: Pascal (with colon) FORTRAN (no colon) 2. Identifiers with colons: ALGOL 60, C 3. Variables as labels: PL/I


Download ppt "Chapter 8 Chapter 8 Control Structures. Control Structures  A control structure is a control statement and the statements whose execution it controls."

Similar presentations


Ads by Google