Recursion. Circular Definition (not useful) E.g., E.g., Projenitor: one who produces an offspring Projenitor: one who produces an offspring Offspring:

Slides:



Advertisements
Similar presentations
Recursion.
Advertisements

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.
Recursion. Idea: Some problems can be broken down into smaller versions of the same problem Example: n! 1*2*3*…*(n-1)*n n*factorial of (n-1)
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Searching Arrays. COMP104 Lecture 22 / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and return its index if the.
Recursion Gordon College CPS212
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part 5. Recursive Algorithms.
COMPSCI 105 S Principles of Computer Science Recursion 3.
CSC 212 Recursion By Dr. Waleed Alsalih. Definition A recursive function (method) is one that calls itself. A recursive method must have a basis part.
CENG 7071 Recursion. CENG 7072 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive function.
Recursion.  Identify recursive algorithms  Write simple recursive algorithms  Understand recursive function calling  With reference to the call stack.
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
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.
Recursion.
 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++
Recursion.
CS-2852 Data Structures LECTURE 12B Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Recursion. Definition Recursion is a function calling on itself over and over until reaching an end state. One such example is factorial. 10! = 10 * 9.
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
Recursion in C++. Recursion Recursive tasks: A task that is defined in terms of itself. A function that calls itself. With each invocation, the problem.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Recursion. Circular Definition Circular definition Circular definition Dialectic materialism is materialism that is dialectic. Dialectic materialism is.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Recursion. Hanoi Tower Legend: Inside a Vietnamese temple there are three rods (labeled as r 1, r 2, and r 3 ), surrounded by n golden disks of different.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
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.
ISOM MIS 215 Module 4 – Recursion. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Chapter 8 Recursion. 2 Objectives  To know what is a recursive function and the benefits of using recursive functions (§8.1).  To determine the base.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Recursion. What is Recursion? Method of solving problems Alternative to iteration All recursive solutions can be implemented iteratively Characteristic...
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
Program Development and Design Using C++, Third Edition
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 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Recursion.
CS212: Data Structures and Algorithms
Recursion.
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion CENG 707.
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
Recursion Chapter 12.
Chapter 15 Recursion.
Andy Wang Object Oriented Programming in C++ COP 3330
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
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion.
Chapter 19: Recursion.
Recursive Algorithms 1 Building a Ruler: drawRuler()
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Recursion

Circular Definition (not useful) E.g., E.g., Projenitor: one who produces an offspring Projenitor: one who produces an offspring Offspring: one who is produced by a projenitor Offspring: one who is produced by a projenitor E.g., E.g., Oak: a tree that produces acorn Oak: a tree that produces acorn Acorn: a nut produced by oak tree Acorn: a nut produced by oak tree

Recursive Definition Recursive Definition Recursive Definition Uses the term being defined as part of the definition Uses the term being defined as part of the definition Is not a circular definition Is not a circular definition Must have base case(s) Must have base case(s) Factorial of n: n! n! = 1, when n = 0 // base case n! = n (n – 1)!, when n > 0 // recursive case Factorial of n: n! n! = 1, when n = 0 // base case n! = n (n – 1)!, when n > 0 // recursive case

Recursive Function Recursive function Recursive function Invokes itself within the function Invokes itself within the function Is an example of divide-and-conquor technique Is an example of divide-and-conquor technique Recursive factorial function int fact(int n){ if (n == 0) // base case return 1; else // recursive case return n * fact(n – 1); } Recursive factorial function int fact(int n){ if (n == 0) // base case return 1; else // recursive case return n * fact(n – 1); } Invocation cout << fact(4);

Recursive Factorial Function fact(4) return 4 * fact(3) fact(3) return 3 * fact(2) fact(2) return 2 * fact(1) fact(1) return 1 * fact(0) fact(0) return 1 fact(1) return 1 * 1 fact(2) return 2 * 1 fact(3) return 3 * 2 fact(4) return 4 * 3

Recursive Functions Recursive Functions Consider a function for solving the count- down problem from some number num down to 0 : Base case: when num == 0 : the problem is solved and we “blast off!” Base case: when num == 0 : the problem is solved and we “blast off!” Otherwise, num > 0 : we count off num and then recursively count down from num-1 Otherwise, num > 0 : we count off num and then recursively count down from num

Recursive Functions Recursive Functions A recursive function for counting down to 0: void countDown(int num) { if (num == 0) // base case if (num == 0) // base case cout << "Blastoff!"; cout << "Blastoff!"; else // recursive else // recursive { // call { // call cout << num << "..."; cout << num << "..."; countDown(num-1); countDown(num-1); }} 14-7

What Happens When Called? 14-8 third call to countDown num is 0 countDown(1); countDown(0); // no // recursive // call second call to countDown num is 1 first call to countDown num is 2 OUTPUT: Blastoff!

Fibonnaci Number fib(n) = 1, when n = 0 fib(n) = 1, when n = 1 fib(n) = fib(n -1) + fib(n – 2), when n > 1 fib(n) = 1, when n = 0 fib(n) = 1, when n = 1 fib(n) = fib(n -1) + fib(n – 2), when n > 1 Fibonacci Function int fib(int n){ if (n == 0 || n == 1) return 1; else return fib(n – 1) + fib(n – 2); } Fibonacci Function int fib(int n){ if (n == 0 || n == 1) return 1; else return fib(n – 1) + fib(n – 2); }

Your Turn Write a recursive function sumOf(int n), which returns the sum of consecutive integers between 1 and n. Write a recursive function sumOf(int n), which returns the sum of consecutive integers between 1 and n. E.g., cout << sumOf(10) prints 55. E.g., cout << sumOf(10) prints 55.

Solution int sumOf(int n) { if (n == 1) { return 1; } else { return n + sumOf(n - 1); }

Your Turn Write a recursive function power(double b, int x), which returns b^x (b raised to the power of x). Write a recursive function power(double b, int x), which returns b^x (b raised to the power of x). E.g., cout << power(2, 8) prints 256 E.g., cout << power(2, 8) prints 256

Solution int power(double b, int x){ double result; if (x == 0){ result = 1; } else if (x == 1){ result = b; } else { result = b * power(b, x – 1); } return result; }

Your Turn Write a recursive function which reads a series of characters from the console and prints them backwords. (A sentinel value of ‘z’ signals the end of input.) Write a recursive function which reads a series of characters from the console and prints them backwords. (A sentinel value of ‘z’ signals the end of input.) E.g., main() can contain the following: int main() { cout << “Enter a series of chars.\n”; printBackwards(); … } E.g., main() can contain the following: int main() { cout << “Enter a series of chars.\n”; printBackwards(); … }

Solution void printBackward() { char ch; cin >> ch; if (ch != 'z') { printBackward(); cout << ch; }

Your Turn Write a recursive function named minimum(int a[], int count) which returns the minimum value of an int array. Write a recursive function named minimum(int a[], int count) which returns the minimum value of an int array. E.g., main() can contain the following: int main() { int a[]; int count; intializeArray(a, count); cout << “Min: “ << minimum(a, count); … } E.g., main() can contain the following: int main() { int a[]; int count; intializeArray(a, count); cout << “Min: “ << minimum(a, count); … }

Solution int minimum(int a[], int count) { int min = a[count - 1]; if (count == 1) { return min; } else { if (min < minimum(a, count - 1)) return min; else return minimum(a, count - 1); }

Your Turn Write a recursive function named greatestCommonFactor(int a, int b) which returns the greatest common facter between positive integers a and b. Write a recursive function named greatestCommonFactor(int a, int b) which returns the greatest common facter between positive integers a and b. GCF can be found from the following rules: if b = 0, then GCF is a; otherwise, it is the GCF of b and (a mod b). GCF can be found from the following rules: if b = 0, then GCF is a; otherwise, it is the GCF of b and (a mod b).

Solution int greatestCommonFactor(int a, int b) { if (b == 0) return a; else return lowestCommonFactor(b, a % b); }

Recursive Binary Search Function Assume an array a that is sorted in ascending order, and an item X Assume an array a that is sorted in ascending order, and an item X We want to write a function that searches for X within the array a, returning the index of X if it is found, and returning -1 if X is not in the array We want to write a function that searches for X within the array a, returning the index of X if it is found, and returning -1 if X is not in the array 14-20

Recursive Binary Search A recursive strategy for searching a portion of the array from index lo to index hi is to set m to index of the middle portion of array: set m to index of the middle portion of array: mlo hi

Recursive Binary Search If a[m] == X, we found X, so return m If a[m] > X, recursively search a[lo..m-1] If a[m] < X, recursively search a[m+1..hi] mlo hi

Recursive Binary Search int bSearch(int a[],int lo,int hi,int X) { int m = (lo + hi) /2; int m = (lo + hi) /2; if(lo > hi) return -1; // base if(lo > hi) return -1; // base if(a[m] == X) return m; // base if(a[m] == X) return m; // base if(a[m] > X) if(a[m] > X) return bsearch(a,lo,m-1,X); return bsearch(a,lo,m-1,X); else else return bsearch(a,m+1,hi,X); return bsearch(a,m+1,hi,X);} 14-23

Tower of Hanoi Stack of 64 golden disks, with the largest at the bottom and progressively smaller ones above. When the stack is completely moved, the world will come to an end. It would take 2 64 −1 (18,446,744,073,709,551,615) moves to finish. At a rate of one move per sec, it would take them roughly 585 billion years to finish.billion

Tower of Hanoi Objective Move the stack of disks from one tower to another with the following rules : Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk.

Solution N disks Tower 2Tower 1 Tower 3 Move N – 1 disks from 1 to 2 Move 1 disk from 1 to 3 Demo

Algorithm (n = 3)

Solution N disks Tower 2Tower 1 Tower 3 Move N – 1 disks from 1 to 2 Move 1 disk from 1 to 3 Demo

Algorithm Move (int n, int from, int to, int aux) If (n = 1) Then cout << “Move disk from “ << from << “ to “ << to << endl Else Move (n – 1, from, aux, to) cout << “Move disk from “ << from << “ to << to << endl; Move (n – 1, aux, to, from) End If Move (int n, int from, int to, int aux) If (n = 1) Then cout << “Move disk from “ << from << “ to “ << to << endl Else Move (n – 1, from, aux, to) cout << “Move disk from “ << from << “ to << to << endl; Move (n – 1, aux, to, from) End If