290 likes | 320 Views
Chapter 8: Control Structures. Lectures # 15. Chapter 8 Topics. Introduction Compound Statements Selection Statements Iterative Statements Unconditional Branching Conclusions. Chapter 8: Control Structures. 2. Levels of Control Flow. Within expressions
E N D
Chapter 8:Control Structures Lectures # 15
Chapter 8 Topics • Introduction • Compound Statements • Selection Statements • Iterative Statements • Unconditional Branching • Conclusions Chapter 8: Control Structures 2
Levels of Control Flow • Within expressions • (governed by associativity and precedence rules Ch 7.). • Among program units • ( highest level we will see in Ch 9 and Ch 13). • Among program statements • (in this lecture). Chapter 8: Control Structures 3
Control Statements, Control Structures • Control Statements: • Statements that provide capabilities such as: • Selection among several alternative control flow paths. • Repeated execution of collections of statements. • Control Structure: • A control statement and the collection of statements whose execution it controls. • Categories include: • Compound statements. • Selection statements. • Iterative statements. • Unconditional branching. Chapter 8: Control Structures 4
Compound Statements • Allow a collection of statements to be abstracted to a single statement. • A block is a compound statement which includes data declarations. • Some languages have specially delimited compound statements: • begin … end : in Pascal. • { … } : in C, C++, C#. • Some control constructs have built-in delimiters such as: repeat…until Chapter 8: Control Structures 5
Selection Statements • A selection statement provides the means of choosing between two or more paths of execution. • Two general categories: • Two-way selectors. • Multiple-way selectors. Chapter 8: Control Structures 6
Two-Way Selection Statements • General form: if control_expression then clause else clause • ALGOL 60 and some other languages: if (boolean_expr) then statement (then clause) else statement (else clause) • The statements could be single or compound. Chapter 8: Control Structures 7
Nesting Selectors • Java example: if (sum == 0) if (count == 0) result = 0; else result = 1; • Whichifgets theelse ? • Java's static semantics rule:elsematches with the nearestif. Chapter 8: Control Structures 8
Nesting Selectors (cont.) • To force an alternative semantics, compound statements may be used: if (sum == 0) { if (count == 0) result = 0;} else result = 1; • The above solution is used in C, C++, and C#. • Perl requires that all then and else clauses to be compound. Chapter 8: Control Structures 9
Multiple-Way Selection Statements • Allow the selection of one of any number of statements or statement groups. • Modern multiple selectors: • C’sswitchstatement: switch (expression) { case const_expr_1: stmt_1; … case const_expr_n: stmt_n; [default: stmt_n+1] } Chapter 8: Control Structures 10
Multiple-Way Selection: Examples • Early multiple selectors: • FORTRAN arithmetic IF (a three-way selector): IF (arithmetic expression) N1, N2, N3 • Ex:IF (expression) 10, 20, 30 10 …… GO TO 40 20 …… GO TO 40 30 …… 40 • Segments require GOTOs. • The arithmetic IF can be entered through any of its statements from anywhere in the program. Chapter 8: Control Structures 11
Multiple-Way Selection: Examples • The Ada’scasestatement: case expression is when choice list => stmt_sequence; … when choice list => stmt_sequence; [when others => stmt_sequence;] end case; • More reliable than C’sswitch: once a stmt_sequence execution is completed, control is passed to the first statement after the case statement. Chapter 8: Control Structures 12
Multiple-Way Selection Using if • Multiple Selectors can appear as direct extensions to two-way selectors, using else-if clauses, for example in Ada: if ... then ... elsif ... then ... elsif ... then ... else ... end if Chapter 8: Control Structures 13
Iterative Statements • The repeated execution of a statement or compound statement is accomplished either by iteration or recursion. • Iterative statements categories: • Counter-controlled loops. • Logically-controlled loops. • User-located loop control mechanisms. • Data structure based-iteration. Chapter 8: Control Structures 14
Iterative Statements: Counter-Controlled Loops • A counting iterative statement has a loop variable, and a means of specifying the initial and terminal, and stepsize values. Chapter 8: Control Structures 15
Counter-Controlled Loops:Examples • Pascal’sforstatement: for variable := initial (to|downto) final do statement; • Design choices: • Loop variable must be an ordinal (such as int or char) type of usual scope. • After normal termination, loop variable is undefined. • The loop variable cannot be changed in the loop. Chapter 8: Control Structures 16
Counter-Controlled Loops:Examples (cont.) • Ada: for var in [reverse] discrete_range loop ... end loop • A discrete range is a sub-range of an integer or enumeration type. • Scope of the loop variable is the range of the loop. • Loop variable is implicitly undeclared after loop termination. Chapter 8: Control Structures 17
Counter-Controlled Loops:Examples (cont.) • C’sforstatement: for ([expr_1] ; [expr_2] ; [expr_3]) statement; • Everything can be changed in the loop. • The first expression is evaluated once, but the other two are evaluated with each iteration. Chapter 8: Control Structures 18
Counter-Controlled Loops:Examples (cont.) • C++ differs from C in: • The initial expression can include variable definitions (scope is from the definition to the end of the loop body). Chapter 8: Control Structures 19
Summing numbers in C++(Reading) int sum(int start, int finish, int incr){ int total = 0; for (int i = 0; i <= finish; i += incr) { total += i; } return total;} Chapter 8: Control Structures 20
Summing numbers in Scheme(Reading) (define (sum start finish incr) (let ((total 0)) (do ((i start (+ i incr))) ((> i finish) total) (set! total (+ i total))))) Local variable total = 0 Loop increment Initial value for i Return value Test to quit Loop “body” Chapter 8: Control Structures 21
Iterative Statements: Logically-Controlled Loops • Repetition control is based on a Boolean. • General forms: • while (ctrl_expr) do loop body • dO loop body while (ctrl_expr) Chapter 8: Control Structures 22
Logically-Controlled Loops: Examples • Pascal has separate pre-test and post-test logical loop statements (while-do and repeat-until). • C and C++ also have both, but the control expression for the post-test version is treated just like in the pre-test case (while-do and do-while). • Java is like C, except the control expression must be Boolean. • Adahas a pre-test version, but no post-test. • Perlhas two pre-test logical loops, while and until, but no post-test logical loop. Chapter 8: Control Structures 23
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). • Examples: • Ada loop – exit [loop_label] [when condition]. • C loops – break and continue. Chapter 8: Control Structures 24
User-Located Loop Control Mechanisms breakand continue • C, C++, and Java: breakstatement. • Unconditional; for any loop or switch; one level only. • Java and C# have a labeledbreakstatement: control transfers to the label. • An alternative: continuestatement; it skips the remainder of this iteration, but does not exit the loop. Chapter 8: Control Structures 25
Iterative Statements: Iteration Based on Data Structures • C#’s foreach statement iterates on the elements of arrays and other collections: Strings[] = strList = {“Bob”, “Carol”, “Ted”}; foreach (Strings name in strList) Console.WriteLine (“Name: {0}”, name); • The notation {0} indicates the position in the string to be displayed. • Perl has foreach which iterates through lists: @names = {“Bob”, “Carol”, “Ted”, “Alice”};…foreach $name (@names) { print $name} Chapter 8: Control Structures 26
Unconditional Branching • Transfers execution control to a specified place in the program. • Well-known mechanism: goto statement. • Label forms: • <<ADA_LABEL>> • Label: (in other languages). • Major concern: Readability. Chapter 8: Control Structures 27
Unconditional Branching (cont.) • Some languages do not support goto statement (e.g., Module-2 and Java). • C# offers goto statement (can be used in switch statements). • Restrictions on branches: • Into a function from another function? • Into a loop or selection statement? Chapter 8: Control Structures 28
Conclusion • Variety of statement-level structures. • Functional and logic programming languages are quite different control structures. Chapter 8: Control Structures 29