Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25
|
|
- Felicia Chambers
- 6 years ago
- Views:
Transcription
1 Homework Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25 Copyright c UMaine School of Computing and Information S 1 / 33
2 COS 140: Foundations of C S Control Constructs: and Fall 2017 Copyright c UMaine School of Computing and Information S 2 / 33
3 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 UMaine School of Computing and Information S 3 / 33
4 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 UMaine School of Computing and Information S 4 / 33
5 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 UMaine School of Computing and Information S 5 / 33
6 A Solution Language constructs Why study them? 1 2 Variables: Copyright c UMaine School of Computing and Information S 6 / 33
7 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 UMaine School of Computing and Information S 6 / 33
8 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 UMaine School of Computing and Information S 6 / 33
9 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 UMaine School of Computing and Information S 6 / 33
10 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 UMaine School of Computing and Information S 7 / 33
11 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 UMaine School of Computing and Information S 8 / 33
12 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 UMaine School of Computing and Information S 9 / 33
13 If Then Else Syntax If then else Syntax Blocks Other conditionals Actual syntax will vary from language to language s: Copyright c UMaine School of Computing and Information S 10 / 33
14 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 UMaine School of Computing and Information S 10 / 33
15 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 UMaine School of Computing and Information S 10 / 33
16 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 UMaine School of Computing and Information S 11 / 33
17 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 UMaine School of Computing and Information S 11 / 33
18 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 UMaine School of Computing and Information S 12 / 33
19 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 UMaine School of Computing and Information S 13 / 33
20 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 UMaine School of Computing and Information S 13 / 33
21 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 UMaine School of Computing and Information S 14 / 33
22 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 UMaine School of Computing and Information S 14 / 33
23 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 UMaine School of Computing and Information S 15 / 33
24 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 UMaine School of Computing and Information S 16 / 33
25 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 UMaine School of Computing and Information S 17 / 33
26 For Syntax varies from language to language For While Repeat until Copyright c UMaine School of Computing and Information S 18 / 33
27 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 UMaine School of Computing and Information S 18 / 33
28 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 UMaine School of Computing and Information S 18 / 33
29 For For While Repeat until Python: for i in range(20): sum = sum + grades[i] average = sum / 20 Copyright c UMaine School of Computing and Information S 19 / 33
30 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 UMaine School of Computing and Information S 19 / 33
31 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 UMaine School of Computing and Information S 20 / 33
32 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 UMaine School of Computing and Information S 21 / 33
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 UMaine School of Computing and Information S 22 / 33
34 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 UMaine School of Computing and Information S 23 / 33
35 Example Common, simple example: factorial Why use it? Languages Cost A warning Copyright c UMaine School of Computing and Information S 24 / 33
36 Example Why use it? Languages Cost A warning Common, simple example: factorial n! = (n 1) n (1) Copyright c UMaine School of Computing and Information S 24 / 33
37 Example Why use it? Languages Cost A warning Common, simple example: factorial n! = (n 1) n (1) = n (n 1) (n 2) (2) Copyright c UMaine School of Computing and Information S 24 / 33
38 Example Why use it? Languages Cost A warning Common, simple example: factorial n! = (n 1) n (1) = n (n 1) (n 2) (2) = n [(n 1) (n 2) ] (3) Copyright c UMaine School of Computing and Information S 24 / 33
39 Example Why use it? Languages Cost A warning Common, simple example: factorial n! = (n 1) n (1) = n (n 1) (n 2) (2) = n [(n 1) (n 2) ] (3) = n (n 1)! (4) This is a very natural way to think of the problem, and to program Copyright c UMaine School of Computing and Information S 24 / 33
40 Example Why use it? Languages Cost A warning Common, simple example: factorial n! = (n 1) n (1) = n (n 1) (n 2) (2) = n [(n 1) (n 2) ] (3) = n (n 1)! (4) This is a very natural way to think of the problem, and to program Copyright c UMaine School of Computing and Information S 24 / 33
41 Need to specify a base case: when the recursion stops Why use it? Languages Cost A warning Copyright c UMaine School of Computing and Information S 25 / 33
42 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 UMaine School of Computing and Information S 25 / 33
43 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 UMaine School of Computing and Information S 25 / 33
44 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 UMaine School of Computing and Information S 25 / 33
45 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 UMaine School of Computing and Information S 26 / 33
46 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 UMaine School of Computing and Information S 27 / 33
47 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 UMaine School of Computing and Information S 28 / 33
48 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 UMaine School of Computing and Information S 29 / 33
49 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 UMaine School of Computing and Information S 30 / 33
50 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 UMaine School of Computing and Information S 30 / 33
51 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 UMaine School of Computing and Information S 30 / 33
52 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 UMaine School of Computing and Information S 30 / 33
53 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 UMaine School of Computing and Information S 30 / 33
54 Why use it? Languages Cost A warning When not to use recursion n calls , , ,664, ,668,309 Copyright c UMaine School of Computing and Information S 31 / 33
55 What to do instead? Dynamic programming or use a loop Why use it? Languages Cost A warning Copyright c UMaine School of Computing and Information S 32 / 33
56 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 UMaine School of Computing and Information S 32 / 33
57 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 UMaine School of Computing and Information S 32 / 33
58 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 UMaine School of Computing and Information S 32 / 33
59 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 UMaine School of Computing and Information S 32 / 33
60 Fibonacci By the way, in case anyone asks, Fibonacci(10,000) = Why use it? Languages Cost A warning Copyright c UMaine School of Computing and Information S 33 / 33
61 Fibonacci Why use it? Languages Cost A warning By the way, in case anyone asks, Fibonacci(10,000) = Copyright c UMaine School of Computing and Information S 33 / 33
Homework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25
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
Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
Common LISP Tutorial 1 (Basic)
Common LISP Tutorial 1 (Basic) CLISP Download https://sourceforge.net/projects/clisp/ IPPL Course Materials (UST sir only) Download https://silp.iiita.ac.in/wordpress/?page_id=494 Introduction Lisp (1958)
LECTURE 18. Control Flow
LECTURE 18 Control Flow CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear in a program text. Selection (or alternation): a
Modern Programming Languages. Lecture LISP Programming Language An Introduction
Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation
Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
Structure of Programming Languages Lecture 5
Structure of Programming Languages Lecture 5 CSCI 6636 4536 June, 2017 CSCI 6636 4536 Lecture 10... 1/16 June, 2017 1 / 16 Outline 1 Expressions and Evaluation 2 Control Structures Conditionals Repetition
SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012
SCHEME COMPUTER SCIENCE 6A October 29th, 202 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs, we will eventually
REPETITION CONTROL STRUCTURE LOGO
CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of
SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017
SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
RECURSION AND LINKED LISTS 3
RECURSION AND LINKED LISTS 3 COMPUTER SCIENCE 61A July 1, 2014 1 Termination and Warmup A function is recursive if executing a call to the function requires another call to the same function, called a
Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
Introduction to the Analysis of Algorithms. Algorithm
Introduction to the Analysis of Algorithms Based on the notes from David Fernandez-Baca Bryn Mawr College CS206 Intro to Data Structures Algorithm An algorithm is a strategy (well-defined computational
More Complicated Recursion CMPSC 122
More Complicated Recursion CMPSC 122 Now that we've gotten a taste of recursion, we'll look at several more examples of recursion that are special in their own way. I. Example with More Involved Arithmetic
CS1 Recitation. Week 2
CS1 Recitation Week 2 Sum of Squares Write a function that takes an integer n n must be at least 0 Function returns the sum of the square of each value between 0 and n, inclusive Code: (define (square
RECURSION, RECURSION, (TREE) RECURSION! 3
RECURSION, RECURSION, (TREE) RECURSION! 3 COMPUTER SCIENCE 61A September 18, 2013 A function is recursive if it calls itself. Below is recursive factorial function. def factorial(n): if n == 0 or n ==
Chapter 8. Statement-Level Control Structures
Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions 1-2 Levels of Control Flow Within
Chapter 8. Statement-Level Control Structures
Chapter 8 Statement-Level Control Structures Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions Copyright 2009 Addison-Wesley.
Introduction. C provides two styles of flow control:
Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if
CSCI-1200 Data Structures Fall 2017 Lecture 7 Order Notation & Basic Recursion
CSCI-1200 Data Structures Fall 2017 Lecture 7 Order Notation & Basic Recursion Announcements: Test 1 Information Test 1 will be held Monday, Sept 25th, 2017 from 6-7:50pm Students will be randomly assigned
SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015
SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
Algorithmics. Some information. Programming details: Ruby desuka?
Algorithmics Bruno MARTIN, University of Nice - Sophia Antipolis mailto:bruno.martin@unice.fr http://deptinfo.unice.fr/~bmartin/mathmods.html Analysis of algorithms Some classical data structures Sorting
Chapter 8 Algorithms 1
Chapter 8 Algorithms 1 Objectives After studying this chapter, the student should be able to: Define an algorithm and relate it to problem solving. Define three construct and describe their use in algorithms.
Recursion & Iteration
Recursion & Iteration York University Department of Computer Science and Engineering 1 Overview Recursion Examples Iteration Examples Iteration vs. Recursion Example [ref.: Chap 5,6 Wilensky] 2 Recursion
Allegro CL Certification Program
Allegro CL Certification Program Lisp Programming Series Level I Review David Margolies 1 Summary 1 A lisp session contains a large number of objects which is typically increased by user-created lisp objects
Loops / Repetition Statements
Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for
An introduction to Scheme
An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize
Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives
CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme
Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures. Recursive design. Convert loops to recursion
Recursion(int day){return Recursion(day += 1);} Comp Sci 1575 Data Structures Outline 1 2 Solution 2: calls 3 Implementation To create recursion, you must create recursion. How to a recursive algorithm
Repetition Structures
Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements
8 Algorithms 8.1. Foundations of Computer Science Cengage Learning
8 Algorithms 8.1 Foundations of Computer Science Cengage Learning 8.2 Objectives After studying this chapter, the student should be able to: Define an algorithm and relate it to problem solving. Define
APCS-AB: Java. Recursion in Java December 12, week14 1
APCS-AB: Java Recursion in Java December 12, 2005 week14 1 Check point Double Linked List - extra project grade Must turn in today MBCS - Chapter 1 Installation Exercises Analysis Questions week14 2 Scheme
Chapter 6 Control Flow. June 9, 2015
Chapter 6 Control Flow June 9, 2015 Expression evaluation It s common in programming languages to use the idea of an expression, which might be a simple object function invocation over some number of arguments
2.2 (a) Statement, subroutine, procedure, function, parameter, loop
Chapter 2.2: The structure of procedural programs 2.2 (a) Statement, subroutine, procedure, function, parameter, loop Procedural programs are ones in which instructions are executed in the order defined
CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.
CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3
RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012
RECURSION 7 COMPUTER SCIENCE 61A October 15, 2012 1 Recursion We say a procedure is recursive if it calls itself in its body. Below is an example of a recursive procedure to find the factorial of a positive
Chapter 8 Statement-Level Control Structures
Chapter 8 Statement-Level Control Structures In Chapter 7, the flow of control within expressions, which is governed by operator associativity and precedence rules, was discussed. This chapter discusses
Nonvisual Arrays and Recursion. by Chris Brown under Prof. Susan Rodger Duke University June 2012
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012 Nonvisual Arrays This tutorial will display how to create and use nonvisual arrays in Alice. Nonvisual arrays
INF4820. Common Lisp: Closures and Macros
INF4820 Common Lisp: Closures and Macros Erik Velldal University of Oslo Oct. 19, 2010 Erik Velldal INF4820 1 / 22 Topics for Today More Common Lisp A quick reminder: Scope, binding and shadowing Closures
CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion
CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,
CSCI 2212: Intermediate Programming / C Recursion
... 1/40 CSCI 2212: Intermediate Programming / C Recursion Alice E. Fischer November 13 and 16, 2015 ... 2/40 Outline What is Recursion? Recursively Defined Images What is a Recursive Function? How Does
Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms
Recursive Methods and Problem Solving Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Review: Calling Methods int x(int n) { int m = 0; n = n + m + 1; return n; int y(int
CS 415 Midterm Exam Fall 2003
CS 415 Midterm Exam Fall 2003 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Questions will be graded on quality of answer. Please supply the best answer you can to
CS159. Nathan Sprague. November 9, 2015
CS159 Nathan Sprague November 9, 2015 Recursive Definitions Merriam Websters definition of Ancestor: Ancestor One from whom a person is descended [...] Here is a recursive version: Ancestor One s parent.
RECURSION, RECURSION, (TREE) RECURSION! 2
RECURSION, RECURSION, (TREE) RECURSION! 2 COMPUTER SCIENCE 61A February 5, 2015 A function is recursive if it calls itself. Below is a recursive factorial function. def factorial(n): if n == 0 or n ==
6.001 Notes: Section 4.1
6.001 Notes: Section 4.1 Slide 4.1.1 In this lecture, we are going to take a careful look at the kinds of procedures we can build. We will first go back to look very carefully at the substitution model,
Ch. 7: Control Structures
Ch. 7: Control Structures I. Introduction A. Flow of control can be at multiple levels: within expressions, among statements (discussed here), and among units. B. Computation in imperative languages uses
Recall from Last Time: Big-Oh Notation
CSE 326 Lecture 3: Analysis of Algorithms Today, we will review: Big-Oh, Little-Oh, Omega (Ω), and Theta (Θ): (Fraternities of functions ) Examples of time and space efficiency analysis Covered in Chapter
Programming for Electrical and Computer Engineers. Loops
Programming for Electrical and Computer Engineers Loops Dr. D. J. Jackson Lecture 6-1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly
Chapter 5: Recursion
Chapter 5: Recursion Objectives Looking ahead in this chapter, we ll consider Recursive Definitions Function Calls and Recursive Implementation Anatomy of a Recursive Call Tail Recursion Nontail Recursion
Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:
Objectives After studying this chapter, students should be able to: Chapter 8 Algorithms Define an algorithm and relate it to problem solving. Define three construct and describe their use in algorithms.
Handout 9: Imperative Programs and State
06-02552 Princ. of Progr. Languages (and Extended ) The University of Birmingham Spring Semester 2016-17 School of Computer Science c Uday Reddy2016-17 Handout 9: Imperative Programs and State Imperative
Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.
Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes
Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?
Recursion Chapter 8 CS 3358 Summer I 2012 Jill Seaman What is recursion? Generally, when something contains a reference to itself Math: defining a function in terms of itself Computer science: when a function
Fifth Generation CS 4100 LISP. What do we need? Example LISP Program 11/13/13. Chapter 9: List Processing: LISP. Central Idea: Function Application
Fifth Generation CS 4100 LISP From Principles of Programming Languages: Design, Evaluation, and Implementation (Third Edition, by Bruce J. MacLennan, Chapters 9, 10, 11, and based on slides by Istvan Jonyer
Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.
Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also
Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences
Section 5.3 1 Recursion Recursion defining an object (or function, algorithm, etc.) in terms of itself. Recursion can be used to define sequences Previously sequences were defined using a specific formula,
Program Syntax; Operational Semantics
9/5 Solved Program Syntax; Operational Semantics CS 536: Science of Programming, Fall 2018 A. Why Our simple programming language is a model for the kind of constructs seen in actual languages. Step-by-step
Chapter 8. Statement-Level Control Structures ISBN
Chapter 8 Statement-Level Control Structures ISBN 0-321-49362-1 Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions Copyright 2012
Lecture 10: Recursive Functions. Computer System and programming in C 1
Lecture 10: Recursive Functions Computer System and programming in C 1 Outline Introducing Recursive Functions Format of recursive Functions Tracing Recursive Functions Examples Tracing using Recursive
LOOPS. Repetition using the while statement
1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while
SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))
SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if
Decisions, Decisions. Testing, testing C H A P T E R 7
C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little
CMPT 120 Control Structures in Python. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Control Structures in Python Summer 2012 Instructor: Hassan Khosravi The If statement The most common way to make decisions in Python is by using the if statement. The if statement allows you
Symbolic Computation and Common Lisp
Symbolic Computation and Common Lisp Dr. Neil T. Dantam CSCI-56, Colorado School of Mines Fall 28 Dantam (Mines CSCI-56) Lisp Fall 28 / 92 Why? Symbolic Computing: Much of this course deals with processing
CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries
CS 0, LAB 0: ASSERTIONS AND WHILE-LOOPS http://www.cs.cornell.edu/courses/cs0/20sp/labs/lab0.pdf. Preliminaries This lab gives you practice with writing loops using invariant-based reasoning. Invariants
Algorithm Design and Recursion. Search and Sort Algorithms
Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms
Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis
Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Week 02 Module 06 Lecture - 14 Merge Sort: Analysis So, we have seen how to use a divide and conquer strategy, we
Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur
Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself
Iterative Statements. Iterative Statements: Examples. Counter-Controlled Loops. ICOM 4036 Programming Languages Statement-Level Control Structure
ICOM 4036 Programming Languages Statement-Level Control Structure Selection Statement Iterative Statements Unconditional Branching Guarded Commands This lecture covers review questions 8-16 This lecture
CS 842 Ben Cassell University of Waterloo
CS 842 Ben Cassell University of Waterloo Recursive Descent Re-Cap Top-down parser. Works down parse tree using the formal grammar. Built from mutually recursive procedures. Typically these procedures
Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization
Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Module 02 Lecture - 45 Memoization Let us continue our discussion of inductive definitions. (Refer Slide Time: 00:05)
Functional Programming
Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used
RECURSION, RECURSION, (TREE) RECURSION! 3
RECURSION, RECURSION, (TREE) RECURSION! 3 COMPUTER SCIENCE 61A September 18, 2013 A function is recursive if it calls itself. Below is recursive factorial function. def factorial(n): if n == 0 or n ==
Putting the fun in functional programming
CM20167 Topic 4: Map, Lambda, Filter Guy McCusker 1W2.1 Outline 1 Introduction to higher-order functions 2 Map 3 Lambda 4 Filter Guy McCusker (1W2.1 CM20167 Topic 4 2 / 42 Putting the fun in functional
EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution
1. (40 points) Write the following subroutine in x86 assembly: Recall that: int f(int v1, int v2, int v3) { int x = v1 + v2; urn (x + v3) * (x v3); Subroutine arguments are passed on the stack, and can
Chapter Fourteen Bonus Lessons: Algorithms and Efficiency
: Algorithms and Efficiency The following lessons take a deeper look at Chapter 14 topics regarding algorithms, efficiency, and Big O measurements. They can be completed by AP students after Chapter 14.
Writing Functions. Reading: Dawson, Chapter 6. What is a function? Function declaration and parameter passing Return values Objects as parameters
What is a function? Function declaration and parameter passing Return values Objects as parameters Reading: Writing Functions Dawson, Chapter 6 Abstraction Data scoping Encapsulation Modules Recursion
Recursive Definitions
Recursion Objectives Explain the underlying concepts of recursion Examine recursive methods and unravel their processing steps Explain when recursion should and should not be used Demonstrate the use of
/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17
01.433/33 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/2/1.1 Introduction In this lecture we ll talk about a useful abstraction, priority queues, which are
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing More Common Lisp Stephan Oepen & Murhaf Fares Language Technology Group (LTG) September 6, 2017 Agenda 2 Previously Common
CIS 194: Homework 6. Due Monday, February 25. Fibonacci numbers
CIS 194: Homework 6 Due Monday, February 25 Files you should submit: Fibonacci.hs This week we learned about Haskell s lazy evaluation. This homework assignment will focus on one particular consequence
Chapter 8. Statement-Level Control Structures
Chapter 8 Statement-Level Control Structures Levels of Control Flow Within expressions Among program units Among program statements Copyright 2012 Addison-Wesley. All rights reserved. 1-2 Control Structure
Recursive Definitions Structural Induction Recursive Algorithms
Chapter 4 1 4.3-4.4 Recursive Definitions Structural Induction Recursive Algorithms 2 Section 4.1 3 Principle of Mathematical Induction Principle of Mathematical Induction: To prove that P(n) is true for
6.001 Notes: Section 15.1
6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define
1 Lower bound on runtime of comparison sorts
1 Lower bound on runtime of comparison sorts So far we ve looked at several sorting algorithms insertion sort, merge sort, heapsort, and quicksort. Merge sort and heapsort run in worst-case O(n log n)
Lecture 10: Recursion vs Iteration
cs2010: algorithms and data structures Lecture 10: Recursion vs Iteration Vasileios Koutavas School of Computer Science and Statistics Trinity College Dublin how methods execute Call stack: is a stack
Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop
Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00
CSE 341 Lecture 5. efficiency issues; tail recursion; print Ullman ; 4.1. slides created by Marty Stepp
CSE 341 Lecture 5 efficiency issues; tail recursion; print Ullman 3.3-3.4; 4.1 slides created by Marty Stepp http://www.cs.washington.edu/341/ Efficiency exercise Write a function called reverse that accepts
CS450 - Structure of Higher Level Languages
Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.
Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem
Recursion Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem What is Recursion? A problem is decomposed into smaller sub-problems, one or more of which are simpler versions of
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing Common Lisp Fundamentals Stephan Oepen & Murhaf Fares Language Technology Group (LTG) August 30, 2017 Last Week: What is
Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)
Orders of Growth of Processes Today s topics Resources used by a program to solve a problem of size n Time Space Define order of growth Visualizing resources utilization using our model of evaluation Relating
Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.
Chapter 6 Loops 1 Iteration Statements C s iteration statements are used to set up loops. A loop is a statement whose job is to repeatedly execute some other statement (the loop body). In C, every loop
EC 413 Computer Organization
EC 413 Computer Organization C/C++ Language Review Prof. Michel A. Kinsy Programming Languages There are many programming languages available: Pascal, C, C++, Java, Ada, Perl and Python All of these languages
Common LISP-Introduction
Common LISP-Introduction 1. The primary data structure in LISP is called the s-expression (symbolic expression). There are two basic types of s-expressions: atoms and lists. 2. The LISP language is normally
Functional programming with Common Lisp
Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions
More About Recursive Data Types
More About Recursive Data Types CS 5010 Program Design Paradigms Bootcamp Lesson 5.5 Mitchell Wand, 2016-2017 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International
21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie
21-Loops Part 2 text: Chapter 6.4-6.6 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie While Loop Infinite Loops Break and Continue Overview Dr. Henry Louie 2 WHILE Loop Used to
I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub I2204- Imperative Programming Schedule 08h00-09h40