Topic 6 Recursion.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Recursion Recursive functions –Functions that call themselves –Can only solve a base case If not base.
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.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Chapter 19 Recursion.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.12Recursion 3.13Example Using Recursion: The Fibonacci Series 3.14Recursion.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
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.
 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++
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 17: Recursion.
Recursion. Basic problem solving technique is to divide a problem into smaller sub problems These sub problems may also be divided into smaller sub problems.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
RECURSION.
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.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
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.
Sequential & Object oriented Programming
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
C++ Programming Lecture 12 Functions – Part IV
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
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! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Program Development and Design Using C++, Third Edition
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
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 Dr. Chow-Sing LinRecursion - CH 10 Problem Solving and Program Design in C Chapter 9 Recursion Chow-Sing Lin.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion Powerful Tool
CS212: Data Structures and Algorithms
Chapter Topics Chapter 16 discusses the following main topics:
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
Chapter 10 Recursion Instructor: Yuksel / Demirer.
OBJECT ORIENTED PROGRAMMING II LECTURE 23 GEORGE KOUTSOGIANNAKIS
Recursion Chapter 12.
Chapter 15 Recursion.
Chapter 19 Recursion.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 14: Recursion Starting Out with C++ Early Objects
CSC113: Computer Programming (Theory = 03, Lab = 01)
Formatted and Unformatted Input/Output Functions
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
MSIS 655 Advanced Business Applications Programming
Applied Algorithms (Lecture 17) Recursion Fall-23
Recursion Chapter 11.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Chapter 18.
Yan Shi CS/SE 2630 Lecture Notes
CS148 Introduction to Programming II
Dr. Sampath Jayarathna Cal Poly Pomona
Recursive Algorithms 1 Building a Ruler: drawRuler()
ICS103 Programming in C Lecture 11: Recursive Functions
Recursion.
Recursive Thinking.
Presentation transcript:

Topic 6 Recursion

Program Development and Design Using C++, Third Edition Objectives You should be able to: Mentally execute recursive functions Write and understand programs which contain recursive functions Convert a while loop into a call to a recursive function Program Development and Design Using C++, Third Edition

Recursion (Chapter 6 in textbook-section 6.6) A function that is defined in terms of itself is called recursive e.g. f(x)= 0 if x=0 2f(x-1) + x2 if x>0 Program Development and Design Using C++, Third Edition

Program Development and Design Using C++, Third Edition Example of fun() 2*fun(2)+3*3 int fun(int x) { if (x==0) return 0; else return 2*fun(x-1)+x*x; } 2*(2*fun(1)+2*2)+3*3 2*(2*(2*fun(0)+1*1)+2*2)+3*3 Recursive call for fun(3): =2*(2*(2*0+1)+4)+9 Returned value of fun(3): 21 Program Development and Design Using C++, Third Edition

Program Development and Design Using C++, Third Edition Recursion Recursive functions Functions that call themselves Can only solve a base case If not base case Break problem into smaller problem(s) Launch new copy of function to work on the smaller problem (recursive call/recursive step) Slowly converges towards base case Function makes call to itself inside the return statement Eventually base case gets solved Answer works way back up, solves entire problem Program Development and Design Using C++, Third Edition

Recursion: How the Computation Is Performed C++ allocates new memory locations for function parameters and local variables as each function is called Allocation made dynamically in memory stack Memory stack: Area of memory used for rapidly storing and retrieving data Last-in/first-out Program Development and Design Using C++, Third Edition

Program Development and Design Using C++, Third Edition Rules of Recursion Two fundamental rules of recursion: Base cases. You must always have some base cases which can be solved without recursion. Making Progress. For the cases that are to be solved recursively, the recursive call must always be to a case that makes progress toward a base case. Program Development and Design Using C++, Third Edition

An incorrect recursive function int sum(int n) { return n+sum(n-1); } This function does not have a base case Program Development and Design Using C++, Third Edition

A correct recursive function int sum(int n) { if (n==0) return 0; else return n+sum(n-1); } void main() cout<<sum(3); Program Development and Design Using C++, Third Edition

How the computation is performed: The stack int sum(int n) { if (n==0) return 0; else return n+sum(n-1); } void main() cout<<sum(3); sum(0) n=0 sum(1) n=1 1+0=1 sum(2) n=2 2+1=3 sum(3) n=3 3+3=6 main() Output: 6 Program Development and Design Using C++, Third Edition

A non-terminating recursive program int Bad(int n) { if (n==0) return 0; else return Bad(n/3+1)+n-1; } Program Development and Design Using C++, Third Edition

Program Development and Design Using C++, Third Edition Factorial example factorial n! = n * ( n – 1 ) * ( n – 2 ) * … * 1 Recursive relationship ( n! = n * ( n – 1 )! ) 5! = 5 * 4! 4! = 4 * 3!… Base case (1! = 0! = 1) Program Development and Design Using C++, Third Edition

Recursive factorial function int factorial(int n) { if ( n==0 ) // base case return 1; else // recursive step return n*factorial(n - 1); } Program Development and Design Using C++, Third Edition

Testing the factorial function void main() { int i; // Loop 5 times. During each iteration, calculate // factorial( i ) and display result. for ( i = 0; i <= 5; i++ ) cout << i << "! = "<< factorial( i ) << endl; } Output: 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 Program Development and Design Using C++, Third Edition

Drawing a triangle recursively void Triangle(int n) { //draws a right-angled triangle if (n!=0) line(n,'*'); //function Line from previous chapter cout<<endl; Triangle(n-1); } Program Development and Design Using C++, Third Edition

Testing the function Triangle #include <iostream> using namespace std; void line(int x, char ch) ; //function prototypes void Triangle(int n); void line(int x, char ch) //function definitions { int i; for(i=1; i<=x; i++) cout << ch ; } void Triangle(int n) if (n!=0) line(n, '*'); cout<<endl; Triangle(n-1); Program Development and Design Using C++, Third Edition

Testing the function Triangle(ctd) void main() { int x; cout<<"Please enter the height of the triangle:"; cin>>x; while (x<=0) cout<<"Please enter a positive height of the triangle:"; } Triangle(x); Program Development and Design Using C++, Third Edition

The connection between recursion and looping We can always re-write a while loop as a recursive function: while (<expression>) <statement> //This is any sequence of statements in curly brackets This while loop can be replaced by a call to the recursive function f: void f() { if (<expression>) <statement>; f(); } Program Development and Design Using C++, Third Edition

A non-recursive Triangle function void Triangle(int n) { while (n!=0) line(n,'*'); cout<<endl; n--; } Program Development and Design Using C++, Third Edition

Program Development and Design Using C++, Third Edition Example Using Recursion: Fibonacci Sequence (exercises 6.6, pg. 355, ex. 1) Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8... Each number sum of two previous ones (except for the first two numbers). Write a recursive function that returns the nth number in the Fibonacci sequence, when n is passed to the function as argument. For example: when n=8, the function should return the eighth number in the sequence, which is 21 (starting from 0). Program Development and Design Using C++, Third Edition

The recursive Fibonacci function long fibonacci( long n ) { if ( n == 0 || n == 1 ) // base case return n; else return fibonacci( n - 1 ) + fibonacci( n – 2 ); } Program Development and Design Using C++, Third Edition

The recursive Fibonacci function return 1 return 0 return + Program Development and Design Using C++, Third Edition

What does this function do? void Rev() { int i; cin>>i; if (i!=-1) Rev(); cout<<i<<endl; } Program Development and Design Using C++, Third Edition

Program Development and Design Using C++, Third Edition Answer: Reads a sequence of integers, terminated by -1 and outputs them in reverse order (excluding the -1). Example run: User enters: 2 5 7 8 -1 Output: 8 2 Program Development and Design Using C++, Third Edition

How to think recursively? Recursive functions are implemented using an if-else (or switch) statement that leads to different cases. Break the problem into subproblems. Every recursive call reduces the original problem by bringing it closer and closer to the base case until it becomes that case. Identify the base case. This is the simplest case (could be more than one base cases) that will be used to stop recursion. Program Development and Design Using C++, Third Edition

Example of thinking recursively: Palindrome problem Considering writing a recursive palindrome function. A string is a palindrome if it reads the same from the left and from the right. This problem can be divided into two subproblems: Check whether the first and last characters of the string are equal. Ignore these two characters and check whether the rest of the substring is a palindrome. (The second problem is the same as the original problem with a smaller size). There are two base cases: The two end characters are not the same, in which case the string not a palindrome The string size is 0 or 1, in which case the string is a palindrome Program Development and Design Using C++, Third Edition

Recursive palindrome function Classroom/lab exercise…. Program Development and Design Using C++, Third Edition

Program Development and Design Using C++, Third Edition Exercises: The recursive solution to the problem of finding the Fibonacci number we gave earlier, is very inefficient (why?). Write a non-recursive Fibonacci function. Program Development and Design Using C++, Third Edition

Exercises (continued): The greatest common divisor (gcd) of two integers p and q is the largest integer that divides both (e.g. gcd of 18 and 12 is 6). An algorithm to compute the greatest common divisor of two integers p and q is the following: Let r be the remainder of p divided by q. If r is 0, then q is the greatest common divisor. Otherwise, set p equal to q, then q equal to r, and repeat the process. Write a recursive function that implements the above algorithm. Program Development and Design Using C++, Third Edition

Exercises (continued): Write a recursive function called locate that takes a string str, a character ch and an integer i and returns the index position of the first occurrence of character ch in string str. (The function assumes that there is an occurrence of the character at or after the index i in the string str). Example: cout<<locate("hello", 'l',0); should print 2. Program Development and Design Using C++, Third Edition