Program Development and Design Using C++, Third Edition

Slides:



Advertisements
Similar presentations
EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Advertisements

Starting Out with Java: From Control Structures through Objects
 2003 Prentice Hall, Inc. All rights reserved. 1 Recursion Recursive functions –Functions that call themselves –Can only solve a base case If not base.
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)
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
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 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.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
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.
Recursion In general there are two approaches to writing repetitive algorithms. One uses loops(while, do while and for): the other uses recursion. Recursion.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
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.
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.
Recursive. 2 Recursive Definitions In a recursive definition, an object is defined in terms of itself. We can recursively define sequences, functions.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
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.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 17: Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 16: Recursion.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Starting Out with C++, 3 rd Edition Chapter 19 Recursion.
C++ Programming Lecture 12 Functions – Part IV
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
Chapter 15: Recursion. Recursive Definitions Recursion: solving a problem by reducing it to smaller versions of itself – Provides a powerful way to solve.
Chapter 15: Recursion. Objectives In this chapter, you will: – Learn about recursive definitions – Explore the base case and the general case of a recursive.
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! =
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
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 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.
CS212: Data Structures and Algorithms
Chapter Topics Chapter 16 discusses the following main topics:
Topic 6 Recursion.
Chapter 15 Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion DRILL: Please take out your notes on Recursion
Recursion Chapter 12.
Chapter 15 Recursion.
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 14: Recursion Starting Out with C++ Early Objects
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Chapter 11.
Chapter 14: Recursion Starting Out with C++ Early Objects
CS148 Introduction to Programming II
Dr. Sampath Jayarathna Cal Poly Pomona
Recursive Algorithms 1 Building a Ruler: drawRuler()
Presentation transcript:

Program Development and Design Using C++, Third Edition Chapter 8 Recursion Program Development and Design Using C++, Third Edition

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)=2f(x-1) + x2 int fun(int x) { if (x==0) return 0; else return 2*fun(x-1)+x*x; } 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

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); } 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 <= 10; 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.h> 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 passes to the function as argument. For example: when n=8, the function should return the eighth number in the sequence, which is 13. 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; } 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

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 innefficient (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