Homework Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25 Copyright c 2002 2017 UMaine Computer Science Department 1 / 33 1
COS 140: Foundations of Computer Science Control Constructs: Conditionals and Loops Fall 2017 Introduction 3 Language constructs........................................................ 3 Why study them?.......................................................... 4 Example 1............................................................... 5 Example 2............................................................... 7 Conditionals 8 If then else.............................................................. 8 Example................................................................ 9 Syntax.................................................................. 10 Blocks.................................................................. 12 Other conditionals.......................................................... 13 Loops 15 Loops.................................................................. 15 Example................................................................ 16 For Loops............................................................... 17 While Loops.............................................................. 20 Repeat until Loops......................................................... 22 Recursion 23 Example................................................................ 24 Why use it?.............................................................. 26 Languages............................................................... 27 Cost................................................................... 28 A warning............................................................... 30 2
Introduction 3 / 33 Programmimg Language Control Constructs In a program, often need to do one thing or another based on some condition do some statement or sets of statements multiple times Programming languages have constructs for controlling the execution of programs in these ways: conditionals and loops Copyright c 2002 2017 UMaine Computer Science Department 3 / 33 3
Why Study Conditionals and Loops? Practical: need to use them Two important constructs that reflect how people solve problems Many ways these could be implemented in a programming language which is best? Copyright c 2002 2017 UMaine Computer Science Department 4 / 33 Example: Counting Cards How would you program the computer to count cards of different colors? Assume that you can read information about a single card and find out its value and suit What variables are needed, and of what type? What instructions would you give? You can only use simple instructions; and You must specify everything that needs to be done. Copyright c 2002 2017 UMaine Computer Science Department 5 / 33 4
A Solution Variables: Value, Suit: the value and suit as the information is read Red: number of red cards (integer) Black: number of black cards (integer) Instructions in pseudocode: Start: Open file containing information about the cards; Red = 0; Black = 0; Read information about a card into Value and Suit; Repeat until no more cards: If Suit is "clubs" or "spades" then Black = Black + 1; else Red = Red + 1; end if; Read info about a card into Value and Suit; end repeat; Print values of Red, Black; end program; Copyright c 2002 2017 UMaine Computer Science Department 6 / 33 Example: Booth s Algorithm Conditionals needed: look for 0 1 or 1 0 in the last bit of Q and in Q-1, do something special in these cases Loops needed: repeat most of the steps in the algorithm for the number of bits in the register Copyright c 2002 2017 UMaine Computer Science Department 7 / 33 5
Conditionals 8 / 33 If Then Else Construct The most widely-used construct for conditionals Example syntax: if condition then statement 1 else statement 2 The else part is usually optional Semantics: If condition is true, then do statement 1. Otherwise, do statement 2 (if the else is specified otherwise, do nothing) Then go to statement after the if then else. Note: statement 1 and statement 2 can be compound statements or blocks (later) Copyright c 2002 2017 UMaine Computer Science Department 8 / 33 Example: If Then Else for Booth s Algorithm if (Q(last) = 1 & Q1 = 0) then A := A - M else if (Q(last) = 0 & Q1 = 1) then A := A + M; shiftright(q); Copyright c 2002 2017 UMaine Computer Science Department 9 / 33 6
If Then Else Syntax Actual syntax will vary from language to language Examples: Pascal: if (Q(last) = 1 & Q1 = 0) then A := A - M else if (Q(last) = 0 & Q1 = 1) then A := A + M; shiftright(q); C: if (Q[last] == 1 && Q1 == 0) A = A - M; else if (Q[last] == 0 && Q1 == 1) A = A + M; shiftright(q); Copyright c 2002 2017 UMaine Computer Science Department 10 / 33 If Then Else Syntax Lisp: Python: (if (= (car (last Q)) 1) (if (= Q1 0) (decf A M)) (if (= Q1 1) (incf A M))) (shiftright Q) if Q[last] == 1 and Q1 == 0: A = A - M else: if Q[last] == 0 and Q1 == 1: A = A + M shiftright(q) Copyright c 2002 2017 UMaine Computer Science Department 11 / 33 7
Blocks Sometimes need to do several statements instead of just one for then or else Problem: How can the language tell how many statements go with those parts and where they end? Blocks group together statements make it clear where they begin and end Also called compound statements Possible delimiters for blocks: begin stmt stmt... stmt end {stmt stmt... stmt} if stmt stmt... stmt else stmt stmt... stmt endif if stmt stmt... stmt else stmt stmt... stmt fi do stmt stmt... stmt od spacing Copyright c 2002 2017 UMaine Computer Science Department 12 / 33 Some Other Conditionals Case or switch statement (many languages) Have a variable with many possible values, each of which corresponds to a case of what should be done Each enumerated case has statements to be carried out in that case Example: case dayofweek of 0: write( Sunday ); 1: write( Monday );... end; Copyright c 2002 2017 UMaine Computer Science Department 13 / 33 8
Some Other Conditionals Cond statement (Lisp) Can have an arbitrary number of conditions associated with actions to be taken Do the actions associated with the first true condition Example: (cond ((member name (alice bob carol)) (print "CS professor")) ((member name (david elizabeth frank)) (print "IS professor")) (t (print "Unknown"))) Copyright c 2002 2017 UMaine Computer Science Department 14 / 33 Loops 15 / 33 Loops Loop construct supports iteration allows same statement(s) to be executed repeatedly Several types of loops reflects that the number of iterations can be determined in different ways for different situations Copyright c 2002 2017 UMaine Computer Science Department 15 / 33 9
Example: Booth s Algorithm Need to do the core of the algorithm ( <core> ) the same number of times as the number of bits in the multiplier for bit=1 to C do <core> Particularly nice if need to use bit for some reason in program while c>0 do <core> C:=C-1; end Here, programmer must change the value of C Copyright c 2002 2017 UMaine Computer Science Department 16 / 33 For Loops Syntax: for iterationvariable = lowerbound to upperbound do statementorblock Iteration variable gets set to the lower bound first time through the loop Each time the statement(s) in the loop is (are) executed, iteration variable incremented by one (Some languages: can decrement or specify amount of increment/decrement.) When the iteration variable exceeds upper bound, stop executing loop Control then goes to the following statement Copyright c 2002 2017 UMaine Computer Science Department 17 / 33 10
For Loops Syntax varies from language to language Pascal: C: for assignment := 1 to 20 do sum := sum + grades[assignment]; average := sum / 20; for (assignment=1;assignment<=20;assignment++) sum = sum + grades[assignment]; average = sum/20; Copyright c 2002 2017 UMaine Computer Science Department 18 / 33 For Loops Python: for i in range(20): sum = sum + grades[i] average = sum / 20 Lisp: (dotimes (assignment 20) (setf sum (+ sum (aref grades (1- assignment))))) (setf average (/ sum 20.0)) OR (setf average (/ (loop for assignment from 0 to 19 sum (aref grades assignment)) 20.0)) OR (setq average (/ (reduce # + assignment) 20.0)) Copyright c 2002 2017 UMaine Computer Science Department 19 / 33 11
While Loops Syntax: while condition do statementorblock As long as condition is true, execute the statement(s) in loop Programmer is responsible for ensuring that something changes so that the condition will eventually be false otherwise, have an infinite loop Copyright c 2002 2017 UMaine Computer Science Department 20 / 33 While loop examples Pascal numgrades := 0; write( Enter grade (-1 to quit): ); readln(grade); while grade >= 0 do begin sum := sum + grade; numgrades := numgrades + 1; write( Enter grade: ); readln(grade) end; average := sum / numgrades; Python C printf("enter grade (-1 to quit): "); grade = scanf("%f"); while (grade >= 0) { sum = sum + grade; numgrades++; printf("enter grade: "); grade = scanf("%f"); } average = sum/numgrades; Lisp grade = input("enter grade (-1 to quit): ") (loop with grade while grade >=0: with num-grades = 0 sum = sum + grade with sum = 0 numgrades = numgrades + 1; do (princ "Enter grade (-1 to quit): ") grade = input("enter grade (-1 to quit): ") while (>= (setq grade (read)) 0) average = sum / numgrades do (incf sum grade) (incf num-grades) finally (return (/ sum num-grades))) Copyright c 2002 2017 UMaine Computer Science Department 21 / 33 12
Repeat until Loops Syntax varies, but often: repeat statementorblock until condition As long as condition is false, execute the statement(s) in loop Unlike while loop, body will be executed 1 times Like while loop, programmer is responsible for ensuring that something changes so that the condition will eventually be false otherwise, have an infinite loop Copyright c 2002 2017 UMaine Computer Science Department 22 / 33 Recursion 23 / 33 Recursion Loops are iteration constructs Iteration isn t only way to repeat things Sometimes more natural to use recursion: Cast problem as some operation + simpler version of the problem Copyright c 2002 2017 UMaine Computer Science Department 23 / 33 13
Example Common, simple example: factorial n! = 1 2 3... (n 1) n (1) = n (n 1) (n 2)... 2 1 (2) = n [(n 1) (n 2)... 2 1] (3) = n (n 1)! (4) This is a very natural way to think of the problem, and to program Copyright c 2002 2017 UMaine Computer Science Department 24 / 33 Recursion Need to specify a base case: when the recursion stops: e.g., 1! = 1 Need to specify a recursive step here, n (n 1)! Pseudocode: subroutine factorial(n): if n = 1 then return 1; else return n * factorial(n-1); fi; end factorial; Copyright c 2002 2017 UMaine Computer Science Department 25 / 33 14
Why use it? Sometimes more natural than loops Examples: Search for a value in a sorted list Search a tree Play a game of chess Create a plan to go from here to Kapa a, Hawaii Copyright c 2002 2017 UMaine Computer Science Department 26 / 33 Languages Most languages support recursion (exceptions include the original FORTRAN) Functional languages: basic construct for repeating E.g., Lisp family of languages: (defun factorial (n) (cond ((<= n 1) 1) (t (* n (factorial (1- n)))))) Copyright c 2002 2017 UMaine Computer Science Department 27 / 33 15
Cost of Recursion Some think recursion is slow: Loops: require only a jump instruction to do next iteration Recursion: each recursive call requires a function call, which can be expensive However, it is as fast as loops for tail recursion: A function is tail-recursive if the last thing the function does before returning is the recursive call Languages are optimized for this: they don t do a subroutine call, just do body of function again without creating new stack frame Almost everything can be made tail-recursive using dynamic programming Copyright c 2002 2017 UMaine Computer Science Department 28 / 33 Tail Recursion Tail-recursive factorial: (defun factorial (n &optional (so-far 1)) (cond ((<= n 1) so-far) (t (factorial (1- n) (* n so-far))))) Faster even for this simple case: run 1,000,000 times in Lisp: Non-tail-recursive: 4.47 seconds Tail-recursive: 4.40 seconds Speed up of 1.6% Copyright c 2002 2017 UMaine Computer Science Department 29 / 33 16
When not to use recursion Consider the case of the Fibonacci sequence: F(n) = F(n 1)+F(n 2) This is a straightforward recursive definition Pseudocode: Subroutine Fib(n): if n < 2 then return 1; else return Fib(n-1) + Fib(n-2); fi; end; Difficult to make tail-recursive; but not the worst problem Recursive calls form a tree, branching factor 2: exponential Copyright c 2002 2017 UMaine Computer Science Department 30 / 33 n calls When not to use recursion 1 1 2 1 3 3 4 5 5 9 6 15 7 25 8 41 9 67 10 109 11 177 12 287 13 465 14 753 15 1219 20 13,529 25 150,049 30 1,664,079 40 204,668,309 Copyright c 2002 2017 UMaine Computer Science Department 31 / 33 17
What to do instead? Dynamic programming or use a loop Non-tail recursive Fibonacci of n = 50 in Lisp: 21 minutes Tail-recursive or iterative Fibonacci of n = 10, 000: about 180 milliseconds Copyright c 2002 2017 UMaine Computer Science Department 32 / 33 Fibonacci By the way, in case anyone asks, Fibonacci(10,000) = 3364476487643178326662161200510754331030214846068006390656476997468008144216666236815559551363373402-5582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652- 7313000888302692356736131351175792974378544137521305205043477016022647583189065278908551543661595829-8727968298751063120057542878345321551510387081829896979161312785626503319548714021428753269818796204- 6936097879900350962302291026368131493195275630227837628441540360584402572114334961180023091208287046-0889239623288354615057765832712525460935911282039252853934346209042452489294039017062338889910858410- 6518317336043747073790855263176432573399371287193758774689747992630583706574283016163740896917842637-8624212835258112820516370298089332099905707920064367426202389783111470054074998459250360633560933883- 8319233867830561364353518921332797329081337326426526339897639227234078829281779535805709936910491754-7080893184105614632233821746563732124822638309210329770164805472624384237486241145309381220656491403- 2751086643394517512161526545361333111314042436854805106765843493523836959653428071768775328348234345-5573667197313927462736291082106792807847180353291311767789246590899386354593278945237776744061922403- 3763867400402133034329749690202832814593341882681768389307200363479562311710310129195316979460763273-7589253530772552375943788434504067715555779056450443016640119462580972216729758615026968443146952034- 6149322911059706762432685159928347098912847067408620085871350162603120719031720860940812983215810772-8207635318662461127824553720853236530577595643007251774431505153960090516860322034916322264088524885- 2433158051534849622434848299380905070483482449327453732624567755879089187190803662058009594743150052-4025327097469953187707243768259074199396322659841474981936092852239450397071654431564213281576889080- 5878318340491743455627052022356484649519611246026831397097506938264870661326450766507461151267752274-8621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133- 252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875 Copyright c 2002 2017 UMaine Computer Science Department 33 / 33 18