Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.

Slides:



Advertisements
Similar presentations
Tower of Hanoi Tower of Hanoi is a mathematical puzzle invented by a French Mathematician Edouard Lucas in The game starts by having few discs stacked.
Advertisements

The Towers of Hanoi or Apocalypse When?.
More Recursion: Permutations and Towers of Hanoi COP 3502.
Recursive Functions The Fibonacci function shown previously is recursive, that is, it calls itself Each call to a recursive method results in a separate.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Recursion Gordon College CPS212
Review of Recursion. Definition: Recursion - The process of a function calling itself.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Introduction to Programming (in C++) Vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Introduction to Programming (in C++) Introduction Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Reasoning with invariants Jordi Cortadella Department of Computer Science.
The power of logarithmic computations Jordi Cortadella Department of Computer Science.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Recursion Jordi Cortadella Department of Computer Science.
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Basic Mathematics Chapter 1 (1.2 and 1.3) Weiss. Recursion / Slide 2 Logarithms * Definition: if and only if * Theorem 1.1: n Proof: apply the definition.
Upon completion, the world will end…
Introduction to Programming (in C++) Numerical algorithms Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Vectors Jordi Cortadella Department of Computer Science.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Recursion,
Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
COMP 51 Week Fourteen Recursion.
Chapter 15 Recursion.
Reasoning with invariants
Chapter 15 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 14: Recursion Starting Out with C++ Early Objects
Jordi Cortadella Department of Computer Science
Chapter 14: Recursion Starting Out with C++ Early Objects
ECE 103 Engineering Programming
CS201: Data Structures and Discrete Mathematics I
Jordi Cortadella Department of Computer Science
CSC 143 Recursion.
CS148 Introduction to Programming II
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Recursion A subprogram is recursive when it contains a call to itself. Recursion can substitute iteration in program design: – Generally, recursive solutions are simpler than (or as simple as) iterative solutions. – There are some problems in which one solution is much simpler than the other. – Generally, recursive solutions are slightly less efficient than the iterative ones (if the compiler does not try to optimize the recursive calls). – There are natural recursive solutions that can be extremely inefficient. Be careful ! Introduction to Programming© Dept. CS, UPC2

Factorial // Pre: n >= 0 // Returns n! int factorial(int n) { // iterative solution int f = 1; int i = 0; // Invariant: f = i! and i  n while (i < n) { i = i + 1; f = fi; } return f; } Introduction to Programming© Dept. CS, UPC3

Factorial Introduction to Programming© Dept. CS, UPC4

Factorial // Pre: n >= 0 // Returns n! int factorial(int n) { // recursive solution if (n == 0) return 1; else return nfactorial(n - 1); } Introduction to Programming© Dept. CS, UPC5

Recursive design In the design of a recursive program, we usually follow a sequence of steps: 1.Identify the basic cases (those in which the subprogram can solve the problem directly without recurring to recursive calls) and determine how they are solved. For example, in the case of factorial, the only basic case used in the function is n=0. Similarly, we could have considered a more general basic case (e.g., n ≤ 1). In both cases, the function should return 1. Introduction to Programming© Dept. CS, UPC6

Recursive design 2.Determine how to resolve the non-basic cases in terms of the basic cases, which we assume we can already solve. In the case of a factorial, we know that the factorial of a number n greater than zero is n  factorial(n-1). 3.Make sure that the parameters of the call move closer to the basic cases at each recursive call. This should guarantee a finite sequence of recursive calls that always terminates. In the case of a factorial, n-1 is closer to 0 than n. Therefore, we can guarantee that this function terminates. Introduction to Programming© Dept. CS, UPC7

Recursive design For example, it is not clear whether the following function terminates: // Pre: n >= 1 // Returns the number of steps of the Collatz sequence // that starts with n. int Collatz(int n) { // recursive solution if (n == 1) return 0; else if (n%2 == 0) return 1 + Collatz(n/2); else return 1 + Collatz(3n + 1); } The reason is that 3  n+1 is not closer to 1 than n Introduction to Programming© Dept. CS, UPC8

Recursion: behind the scenes Introduction to Programming © Dept. CS, UPC9 int factorial(int n) if (n <= 1) return 1; else return n  factorial(n-1); 4... f = factorial(4); int factorial(int n) if (n <= 1) return 1; else return n  factorial(n-1);

Recursion: behind the scenes Introduction to Programming © Dept. CS, UPC10... f = factorial(4);... int factorial(int n) if (n <= 1) return 1; else return n  factorial(n-1);

Recursion: behind the scenes Each time a function is called, a new instance of the function is created. Each time a function “returns”, its instance is destroyed. The creation of a new instance only requires the allocation of memory space for data (parameters and local variables). The instances of a function are destroyed in reverse order to their creation, i.e. the first instance to be created will be the last to be destroyed. Introduction to Programming© Dept. CS, UPC11

Write the binary representation Design a procedure that, given a number n, writes its binary representation. // Pre: n > 0 // Post: the binary representation of has been written. void base2(int n) { Basic case (n=1)  write “1” General case (n>1)  write n/2 and then write n%2 Introduction to Programming© Dept. CS, UPC12

Write the binary representation // Pre: n > 0 // Post: the binary representation of n has been written. void base2(int n) { if (n == 1) cout << n; else { base2(n/2); cout << n%2; } The procedure always terminates since n/2 is closer to 1 than n. Note that n/2 is never 0 when n > 1. Therefore, the case n = 1 will always be found at the end of the sequence call. Introduction to Programming© Dept. CS, UPC13

Fibonacci numbers Design a function that, given a number n, returns the Fibonacci number of order n. The Fibonacci numbers are: In general, except for n = 0 and n = 1, the Fibonacci number of order n is equal to the sum of the two previous numbers. Introduction to Programming© Dept. CS, UPC order fib

Fibonacci numbers // Pre: n >= 0 // Returns the Fibonacci number of order n. int fib(int n); Basic case: n = 0 ⇒ Return 1. n = 1 ⇒ Return 1. General case: n > 1 ⇒ Return fib(n - 1) + fib(n - 2) Introduction to Programming© Dept. CS, UPC15

Fibonacci numbers // Pre: n >= 0 // Returns the Fibonacci number of order n. int fib(int n) { // Recursive solution if (n <= 1) return 1; else return fib(n - 2) + fib(n - 1); } The function always terminates since the parameters of the recursive call (n-2 and n-1) are closer to 0 and 1 than n. Introduction to Programming© Dept. CS, UPC16

Fibonacci numbers Introduction to Programming© Dept. CS, UPC17 The tree of calls for fib(5) would be: fib(5)fib(4)fib(3) fib(2) fib(1)fib(2)fib(1) fib(0)fib(1)fib(0)fib(1)fib(0)

Fibonacci numbers When fib(5) is calculated: – fib(5) is called once – fib(4) is called once – fib(3) is called twice – fib(2) is called 3 times – fib(1) is called 5 times – fib(0) is called 3 times When fib(n) is calculated, how many times will fib(1) and fib(0) be called? Example: fib(50) calls fib(1) and fib(0) about 2.4·10 10 times Introduction to Programming© Dept. CS, UPC18

Fibonacci numbers // Pre: n >= 0 // Returns the Fibonacci number of order n. int fib(int n) { // iterative solution int i = 1; int f_i = 1; int f_i1 = 1; // Inv: f_i is the Fibonacci number of order i. // f_i1 is the Fibonacci number of order i-1. while (i < n) { int f = f_i + f_i1; f_i1 = f_i; f_i = f; i = i + 1; } return f_i; } Introduction to Programming© Dept. CS, UPC19

Fibonacci numbers With the iterative solution, if we calculate fib(5), we have that: – fib(5) is calculated once – fib(4) is calculated once – fib(3) is calculated once – fib(2) is calculated once – fib(1) is calculated once – fib(0) is calculated once Introduction to Programming© Dept. CS, UPC20

Counting a’s We want to read a text represented as a sequence of characters that ends with ‘.’ We want to calculate the number of occurrences of the letter ‘a’ We can assume that the text always has at least one character (the last ‘.’) Example: the text Programming in C++ is amazingly easy !. has 4 a’s Introduction to Programming© Dept. CS, UPC21

Counting a’s // Input: a sequence of characters that ends with ‘.’ // Returns the number of times ‘a’ appears in the // sequence (and the sequence has been read) Basic case: We have a ‘.’ at the input  return 0 General case: We have something different from ‘.’ at the input  calculate the number of remaining ‘a’ at the input and add 1 if the current char is an ‘a’ Introduction to Programming© Dept. CS, UPC22

Counting a’s // Input: a sequence of characters that ends with ‘.’ // Returns the number of times ‘a’ appears in the // sequence (and the sequence has been read) int count_a() { char c; cin >> c; if (c == '.') return 0; else if (c == 'a') return 1 + count_a(); else return count_a(); } Even though it has no parameters, we can see that the function terminates if we consider that the input is an implicit parameter. At every recursive call, a new char is read. Therefore, each call moves closer to reading the final dot. Introduction to Programming© Dept. CS, UPC23

Tower of Hanoi The puzzle was invented by the French mathematician Édouard Lucas in There is a legend about an Indian temple that contains a large room with three time-worn posts in it, surrounded by 64 golden disks. To fulfil an ancient prophecy, Brahmin priests have been moving these disks, in accordance with the rules of the puzzle, since that time. The puzzle is therefore also known as the Tower of Brahma puzzle. According to the legend, when the last move in the puzzle is completed, the world will end. It is not clear whether Lucas invented this legend or was inspired by it. (from Rules of the puzzle: – A complete tower of disks must be moved from one post to another. – Only one disk can be moved at a time. – No disk can be placed on top of a smaller disk. Introduction to Programming© Dept. CS, UPC24 Not allowed !

Tower of Hanoi Introduction to Programming© Dept. CS, UPC25

Tower of Hanoi Introduction to Programming© Dept. CS, UPC26

Tower of Hanoi What rules determine the next move? How many moves do we need? There is no trivial iterative solution. Introduction to Programming© Dept. CS, UPC27

Tower of Hanoi Introduction to Programming© Dept. CS, UPC28 Inductive reasoning: assume that we know how to solve Hanoi for n-1 disks Hanoi(n-1) from left to middle (safe: the largest disk is always at the bottom) Move the largest disk from the left to the right Hanoi(n-1) from the middle to the right (safe: the largest disk is always at the bottom)

Tower of Hanoi // Pre: n is the number of disks (n≥0). // from, to and aux are the names of the pegs. // Post: Tower of Hanoi solved by moving n disks // from peg from to peg to using peg aux void Hanoi(int n, char from, char to, char aux) { if (n > 0) { Hanoi(n - 1, from, aux, to); cout << “Move disk from “ << from << “ to “ << to << endl; Hanoi(n - 1, aux, to, from); } Introduction to Programming© Dept. CS, UPC29

Tower of Hanoi // Main program to solve the Tower of Hanoi // for any number of disks int main() { int Ndisks; // Read the number of disks cin >> Ndisks; // Solve the puzzle Hanoi(Ndisks, ‘L’, ‘R’, ‘M’); } Introduction to Programming© Dept. CS, UPC30

Tower of Hanoi > Hanoi 5 Move disk from L to R Move disk from L to M Move disk from R to M Move disk from L to R Move disk from M to L Move disk from M to R Move disk from L to R Move disk from L to M Move disk from R to M Move disk from R to L Move disk from M to L Move disk from R to M Move disk from L to R Move disk from L to M Move disk from R to M Introduction to Programming© Dept. CS, UPC31 Move disk from L to R Move disk from M to L Move disk from M to R Move disk from L to R Move disk from M to L Move disk from R to M Move disk from R to L Move disk from M to L Move disk from M to R Move disk from L to R Move disk from L to M Move disk from R to M Move disk from L to R Move disk from M to L Move disk from M to R Move disk from L to R

Tower of Hanoi Introduction to Programming© Dept. CS, UPC32 Hanoi(3,L,R,M)Hanoi(2,L,M,R)Hanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L)LMLMHanoi(1,R,M,L)Hanoi(0,R,L,M)RMRMHanoi(0,L,M,R)LRLRHanoi(2,M,R,L)Hanoi(1,M,L,R)Hanoi(0,M,R,L)MLMLHanoi(0,R,L,M)MRMRHanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L) Hanoi(2,L,M,R) Hanoi(2,M,R,L)

Tower of Hanoi Introduction to Programming© Dept. CS, UPC33 Hanoi(3,L,R,M)Hanoi(2,L,M,R)Hanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L)LMLMHanoi(1,R,M,L)Hanoi(0,R,L,M)RMRMHanoi(0,L,M,R)LRLRHanoi(2,M,R,L)Hanoi(1,M,L,R)Hanoi(0,M,R,L)MLMLHanoi(0,R,L,M)MRMRHanoi(1,L,R,M)Hanoi(0,L,M,R)LRLRHanoi(0,M,R,L)

Tower of Hanoi How many moves do we need for n disks? Moves(n) = 1 + 2Moves(n-1) Introduction to Programming© Dept. CS, UPC34 nMoves(n) n2 n -1

Tower of Hanoi Introduction to Programming© Dept. CS, UPC35 ntime 11s 531s 1017m 3s 159h 6m 7s 2012d 3h 16m 15s 251y 23d 8h 40m 31s 30> 34y 40> 34,000y 50> 35,000,000y 60> 36,000,000,000y Let us assume that we can move one disk every second. How long would it take to move n disks?

Digital root The digital root (or the repeated digital sum) of a number is the number obtained by adding all the digits, then adding the digits of that number, and then continuing until a single-digit number is reached. For example, the digital root of is 7, because = 25 and = 7. Introduction to Programming© Dept. CS, UPC36

Digital root Basic case: n can be represented as a single- digit number  return n General case: n has more than one digit – Calculate the sum of the digits – Calculate the digital root of the sum Introduction to Programming© Dept. CS, UPC37

Digital root // Assume we have a function (to be defined) // that calculates the sum of the digits of a number // Pre: n ≥ 0 // Returns the sum of the digits of n // (represented in base 10) int sumdigits(int n); // Pre: n ≥ 0 // Returns the digital root of n int digital_root(int n) { if (n < 10) return n; else return digital_root(sumdigits(n)); } Introduction to Programming© Dept. CS, UPC38

Write a number n in base b Design a program that writes a number n in base b. Examples: 1024 is in base in base in base in base 10 Introduction to Programming© Dept. CS, UPC39

Write a number n in base b Basic case: n = 0  do not write anything (avoid writing numbers with a leading 0). Treat the zero as a special case outside the function. General case: n > 0 – Write the leading digits of the number (n/b) – Write the last digit of the number (n%b) Introduction to Programming© Dept. CS, UPC40

Write a number n in base b // Writes the representation of n in base b (n ≥ 0, 2  b  10) // No digits are written when n = 0. void write_base(int n, int b) { if (n > 0) { write_base(n/b, b); cout << n%b; } } // Input: read two numbers, n and b, with n ≥ 0 and 2  b 10 // Output: write the representation of n in base b. int main() { int n, b; cin >> n >> b; if (n == 0) cout << “0”; else write_base(n, b); cout << endl; } Introduction to Programming© Dept. CS, UPC41