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 School of Computing and Information S 1 / 33
COS 140: Foundations of C S Control Constructs: and Fall 2017 Copyright c 2002 2017 UMaine School of Computing and Information S 2 / 33
Programmimg Language Control Constructs Language constructs Why study them? 1 2 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 School of Computing and Information S 3 / 33
Why Study and? Language constructs Why study them? 1 2 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 School of Computing and Information S 4 / 33
Example: Counting Cards Language constructs Why study them? 1 2 How would you program the c 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 School of Computing and Information S 5 / 33
A Solution Language constructs Why study them? 1 2 Variables: Copyright c 2002 2017 UMaine School of Computing and Information S 6 / 33
A Solution Language constructs Why study them? 1 2 Variables: Value,Suit: the value and suit as the information is read Red: number of red cards (integer) Black: number of black cards (integer) Copyright c 2002 2017 UMaine School of Computing and Information S 6 / 33
A Solution Language constructs Why study them? 1 2 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: Copyright c 2002 2017 UMaine School of Computing and Information S 6 / 33
A Solution Language constructs Why study them? 1 2 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 School of Computing and Information S 6 / 33
Example: Booth s Algorithm Language constructs Why study them? 1 2 needed: look for 0 1 or 1 0 in the last bit of Q and in Q-1, do something special in these cases needed: repeat most of the steps in the algorithm for the number of bits in the register Copyright c 2002 2017 UMaine School of Computing and Information S 7 / 33
If Then Else Construct If then else Syntax Blocks Other conditionals The most widely-used construct for conditionals 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 School of Computing and Information S 8 / 33
Example: If Then Else for Booth s Algorithm If then else Syntax Blocks Other conditionals 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 School of Computing and Information S 9 / 33
If Then Else Syntax If then else Syntax Blocks Other conditionals Actual syntax will vary from language to language s: Copyright c 2002 2017 UMaine School of Computing and Information S 10 / 33
If Then Else Syntax If then else Syntax Blocks Other conditionals Actual syntax will vary from language to language s: Pascal: 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 School of Computing and Information S 10 / 33
If Then Else Syntax If then else Syntax Blocks Other conditionals Actual syntax will vary from language to language s: 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 School of Computing and Information S 10 / 33
If Then Else Syntax If then else Syntax Blocks Other conditionals Lisp: (if (= (car (last Q)) 1) (if (= Q1 0) (decf A M)) (if (= Q1 1) (incf A M))) (shiftright Q) Copyright c 2002 2017 UMaine School of Computing and Information S 11 / 33
If Then Else Syntax If then else Syntax Blocks Other conditionals Lisp: (if (= (car (last Q)) 1) (if (= Q1 0) (decf A M)) (if (= Q1 1) (incf A M))) (shiftright Q) Python: 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 School of Computing and Information S 11 / 33
Blocks If then else Syntax Blocks Other conditionals 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 School of Computing and Information S 12 / 33
Some Other If then else Syntax Blocks 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 Copyright c 2002 2017 UMaine School of Computing and Information S 13 / 33
Some Other If then else Syntax Blocks 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 School of Computing and Information S 13 / 33
Some Other If then else Syntax Blocks 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 Copyright c 2002 2017 UMaine School of Computing and Information S 14 / 33
Some Other If then else Syntax Blocks 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 School of Computing and Information S 14 / 33
For While Repeat until 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 School of Computing and Information S 15 / 33
Example: Booth s Algorithm For While Repeat until 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 usebit 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 School of Computing and Information S 16 / 33
For For While Repeat until 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 School of Computing and Information S 17 / 33
For Syntax varies from language to language For While Repeat until Copyright c 2002 2017 UMaine School of Computing and Information S 18 / 33
For For While Repeat until Syntax varies from language to language Pascal: for assignment := 1 to 20 do sum := sum + grades[assignment]; average := sum / 20; Copyright c 2002 2017 UMaine School of Computing and Information S 18 / 33
For For While Repeat until Syntax varies from language to language Pascal: for assignment := 1 to 20 do sum := sum + grades[assignment]; average := sum / 20; C: for (assignment=1;assignment<=20;assignment++) sum = sum + grades[assignment]; average = sum/20; Copyright c 2002 2017 UMaine School of Computing and Information S 18 / 33
For For While Repeat until Python: for i in range(20): sum = sum + grades[i] average = sum / 20 Copyright c 2002 2017 UMaine School of Computing and Information S 19 / 33
For For While Repeat until 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 School of Computing and Information S 19 / 33
While For While Repeat until 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 School of Computing and Information S 20 / 33
While loop examples For While Repeat until 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; 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; Python 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 School of Computing and Information S 21 / 33
Repeat until For While Repeat until Syntax varies, but often: repeat statementorblock until condition As long as condition is false, execute the statement(s) in loop Unlikewhile loop, body will be executed 1 times Likewhile 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 School of Computing and Information S 22 / 33
Why use it? Languages Cost A warning 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 School of Computing and Information S 23 / 33
Example Common, simple example: factorial Why use it? Languages Cost A warning Copyright c 2002 2017 UMaine School of Computing and Information S 24 / 33
Example Why use it? Languages Cost A warning Common, simple example: factorial n! = 1 2 3... (n 1) n (1) Copyright c 2002 2017 UMaine School of Computing and Information S 24 / 33
Example Why use it? Languages Cost A warning Common, simple example: factorial n! = 1 2 3... (n 1) n (1) = n (n 1) (n 2)... 2 1 (2) Copyright c 2002 2017 UMaine School of Computing and Information S 24 / 33
Example Why use it? Languages Cost A warning 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) Copyright c 2002 2017 UMaine School of Computing and Information S 24 / 33
Example Why use it? Languages Cost A warning 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 School of Computing and Information S 24 / 33
Example Why use it? Languages Cost A warning 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 School of Computing and Information S 24 / 33
Need to specify a base case: when the recursion stops Why use it? Languages Cost A warning Copyright c 2002 2017 UMaine School of Computing and Information S 25 / 33
Why use it? Languages Cost A warning Need to specify a base case: when the recursion stops: e.g., 1! = 1 Need to specify a recursive step Copyright c 2002 2017 UMaine School of Computing and Information S 25 / 33
Why use it? Languages Cost A warning Need to specify a base case: when the recursion stops: e.g., 1! = 1 Need to specify a recursive step here,n (n 1)! Copyright c 2002 2017 UMaine School of Computing and Information S 25 / 33
Why use it? Languages Cost A warning 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 School of Computing and Information S 25 / 33
Why use it? Why use it? Languages Cost A warning Sometimes more natural than loops s: 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 School of Computing and Information S 26 / 33
Languages Why use it? Languages Cost A warning 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 School of Computing and Information S 27 / 33
Cost of Why use it? Languages Cost A warning Some think recursion is slow: : require only a jump instruction to do next iteration : 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 School of Computing and Information S 28 / 33
Tail Why use it? Languages Cost A warning 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 School of Computing and Information S 29 / 33
When not to use recursion Consider the case of the Fibonacci sequence: F(n) = F(n 1)+F(n 2) Why use it? Languages Cost A warning Copyright c 2002 2017 UMaine School of Computing and Information S 30 / 33
When not to use recursion Why use it? Languages Cost A warning Consider the case of the Fibonacci sequence: F(n) = F(n 1)+F(n 2) This is a straightforward recursive definition Copyright c 2002 2017 UMaine School of Computing and Information S 30 / 33
When not to use recursion Why use it? Languages Cost A warning 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; Copyright c 2002 2017 UMaine School of Computing and Information S 30 / 33
When not to use recursion Why use it? Languages Cost A warning 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 Copyright c 2002 2017 UMaine School of Computing and Information S 30 / 33
When not to use recursion Why use it? Languages Cost A warning 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 School of Computing and Information S 30 / 33
Why use it? Languages Cost A warning When not to use recursion n calls 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 School of Computing and Information S 31 / 33
What to do instead? Dynamic programming or use a loop Why use it? Languages Cost A warning Copyright c 2002 2017 UMaine School of Computing and Information S 32 / 33
What to do instead? Dynamic programming or use a loop Non-tail recursive Fibonacci ofn = 50 in Lisp Why use it? Languages Cost A warning Copyright c 2002 2017 UMaine School of Computing and Information S 32 / 33
What to do instead? Dynamic programming or use a loop Non-tail recursive Fibonacci ofn = 50 in Lisp: 21 minutes Why use it? Languages Cost A warning Copyright c 2002 2017 UMaine School of Computing and Information S 32 / 33
What to do instead? Why use it? Languages Cost A warning Dynamic programming or use a loop Non-tail recursive Fibonacci ofn = 50 in Lisp: 21 minutes Tail-recursive or iterative Fibonacci ofn = 10,000: Copyright c 2002 2017 UMaine School of Computing and Information S 32 / 33
What to do instead? Why use it? Languages Cost A warning Dynamic programming or use a loop Non-tail recursive Fibonacci ofn = 50 in Lisp: 21 minutes Tail-recursive or iterative Fibonacci ofn = 10,000: about 180 milliseconds Copyright c 2002 2017 UMaine School of Computing and Information S 32 / 33
Fibonacci By the way, in case anyone asks, Fibonacci(10,000) = Why use it? Languages Cost A warning Copyright c 2002 2017 UMaine School of Computing and Information S 33 / 33
Fibonacci Why use it? Languages Cost A warning 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 School of Computing and Information S 33 / 33