 2003 Prentice Hall, Inc. All rights reserved. 1 Recursion Recursive functions –Functions that call themselves –Can only solve a base case If not base.

Slides:



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

 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline some useful problems.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Recursion.
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
File Handling Accessing a data file for input: 1) Include the file stream header file: #include using namespace std; 2) Associate an input file name with.
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.12Recursion 3.13Example Using Recursion: The Fibonacci Series 3.14Recursion.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
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.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
 2003 Prentice Hall, Inc. All rights reserved Linked Lists Upcoming program has two class templates –Create two class templates –ListNode data.
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,
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
 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++
1 Storage Classes, Scope, and Recursion Lecture 6.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
Lecture6 Recursion function © by Pearson Education, Inc. All Rights Reserved. 1.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Computer Science 101 Fast Searching and Sorting. Improving Efficiency We got a better best case by tweaking the selection sort and the bubble sort We.
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
1 CS1120: Recursion. 2 What is Recursion? A method is said to be recursive if the method definition contains a call to itself A recursive method is a.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
1 Lecture 5: Part 1 Searching Arrays Searching Arrays: Linear Search and Binary Search Search array for a key value Linear search  Compare each.
File I/O ifstreams and ofstreams Sections 11.1 &
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
Chapter 5 – Functions II Outline Recursion Examples Using Recursion: The Fibonacci Series.
 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 2 September 3, 2009.
Starting Out with C++, 3 rd Edition Chapter 19 Recursion.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 8 September 24, 2009.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
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! =
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions September.
Program Development and Design Using C++, Third Edition
Section Recursion  Recursion – defining an object (or function, algorithm, etc.) in terms of itself.  Recursion can be used to define sequences.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Topic 6 Recursion.
5.13 Recursion Recursive functions Functions that call themselves
IS Program Design and Software Tools Introduction to C++ Programming
RECURSION.
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Functions.
Chapter 5 - Functions Outline 5.1 Introduction
Quicksort and Mergesort
File Handling Accessing a data file for input: 1) Include the file stream header file: #include using namespace std; 2) Associate an input file.
Recursive Algorithms 1 Building a Ruler: drawRuler()
ADT LIST So far we have seen the following operations on a “list”:
Presentation transcript:

 2003 Prentice Hall, Inc. All rights reserved. 1 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 its way back up to solve the entire problem

 2003 Prentice Hall, Inc. All rights reserved. 2 Recursion 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)

 2003 Prentice Hall, Inc. All rights reserved. Outline // Recursive factorial function. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setw; unsigned long factorial( unsigned long ); // function prototype int main() 15 { 16 // Loop 10 times. During each iteration, calculate 17 // factorial( i ) and display result. 18 for ( int i = 0; i <= 10; i++ ) 19 cout << setw( 2 ) << i << "! = " 20 << factorial( i ) << endl; return 0; // indicates successful termination } // end main Data type unsigned long can hold an integer from 0 to 4 billion.

 2003 Prentice Hall, Inc. All rights reserved. Outline // recursive definition of function factorial 27 unsigned long factorial( unsigned long number ) 28 { 29 // base case 30 if ( number <= 1 ) 31 return 1; // recursive step 34 else 35 return number * factorial( number - 1 ); } // end function factorial 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = ! = ! = ! = The base case occurs when we have 0! or 1!. All other cases must be split up (recursive step).

 2003 Prentice Hall, Inc. All rights reserved. 5 Example Using Recursion: Fibonacci Series Fibonacci series: 0, 1, 1, 2, 3, 5, 8... –Each number sum of two previous ones –Example of a recursive formula: fib(n) = fib(n-1) + fib(n-2) C++ code for Fibonacci function long fibonacci( long n ) { if ( n == 0 || n == 1 ) // base case return n; else return fibonacci( n - 1 ) + fibonacci( n – 2 ); }

 2003 Prentice Hall, Inc. All rights reserved. 6 Example Using Recursion: Fibonacci Series f( 3 ) f( 1 ) f( 2 ) f( 1 )f( 0 )return 1 return 0 return + +

 2003 Prentice Hall, Inc. All rights reserved. Outline // Recursive fibonacci function. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 unsigned long fibonacci( unsigned long ); // function prototype int main() 12 { 13 unsigned long result, number; // obtain integer from user 16 cout << "Enter an integer: "; 17 cin >> number; // calculate fibonacci value for number input by user 20 result = fibonacci( number ); // display result 23 cout << "Fibonacci(" << number << ") = " << result << endl; return 0; // indicates successful termination The Fibonacci numbers get large very quickly, and are all non-negative integers. Thus, we use the unsigned long data type.

 2003 Prentice Hall, Inc. All rights reserved. Outline } // end main // recursive definition of function fibonacci 30 unsigned long fibonacci( unsigned long n ) 31 { 32 // base case 33 if ( n == 0 || n == 1 ) 34 return n; // recursive step 37 else 38 return fibonacci( n - 1 ) + fibonacci( n - 2 ); } // end function fibonacci Enter an integer: 0 Fibonacci(0) = 0 Enter an integer: 1 Fibonacci(1) = 1 Enter an integer: 2 Fibonacci(2) = 1 Enter an integer: 3 Fibonacci(3) = 2

 2003 Prentice Hall, Inc. All rights reserved. Outline 9 Enter an integer: 4 Fibonacci(4) = 3 Enter an integer: 5 Fibonacci(5) = 5 Enter an integer: 6 Fibonacci(6) = 8 Enter an integer: 10 Fibonacci(10) = 55 Enter an integer: 20 Fibonacci(20) = 6765 Enter an integer: 30 Fibonacci(30) = Enter an integer: 35 Fibonacci(35) =

 2003 Prentice Hall, Inc. All rights reserved. 10 Recursion vs. Iteration Repetition –Iteration: explicit loop –Recursion: repeated function calls Termination –Iteration: loop condition fails –Recursion: base case recognized Both can have infinite loops Balance between performance (iteration) and good software engineering (recursion)

 2003 Prentice Hall, Inc. All rights reserved. Quick Sort Divide and conquer, recursive sorting algorithm O(n log n) comparisons to sort n items –O(n 2 ) for the worst case Fast sorting for large array sizes Strategy: 1. Pick a value from the list, called pivot (i.e. median or first) 2. Partition the list according to the following: (values less than pivot) pivot (values larger than pivot) 3. Recursively sort the two sub-lists. Base cases are lists of size zero or one. 11

 2003 Prentice Hall, Inc. All rights reserved. Quick Sort Sample Function void quicksort(int data[],int first, int last) { int pivot; if(last > first) { // list has two or more elements pivot=partition(data, first, last); // find pivot and split list into 2 sub lists quicksort(data, first, pivot - 1); // apply quick sort to the left sub list quicksort(data, pivot + 1, last); // apply quick sort to the right sub list }//IF }//QUICKSORT 12

 2003 Prentice Hall, Inc. All rights reserved. Quick Sort Recursion Tree 13

 2003 Prentice Hall, Inc. All rights reserved. File Handling Accessing a data file for input: 1) Include the file stream header file: #include using namespace std; 2) Associate an input file name with an input file stream for accessing the data file. ifstream fin(“datafile.in”); You may explicitly indicate the mode of file access as input: ifstream fin(“datafile.in”,ios::in); 14

 2003 Prentice Hall, Inc. All rights reserved. File Handling 3) Use the associated file name to access the data: fin>>accountNum>>balance; or while(fin>>accountNum[i]>>balance[i]){ … } to retrieve data until end of file (EOF) is reached 4) Close the file indicating that the data access is terminated. fin.close( ); 15

 2003 Prentice Hall, Inc. All rights reserved. File Handling Accessing a data file for output: 1) Include the file stream header file: #include using namespace std; 2) Associate an output file name with an output file stream: ofstream fout(“datafile.out”,ios::out); 16

 2003 Prentice Hall, Inc. All rights reserved. File Handling 3) Use the associated file name to output the data: fout<<accountNum<< “ ”<<balance<<endl; 4) Close the file indicating that the data access is terminated. fout.close( ); 17

 2003 Prentice Hall, Inc. All rights reserved. Mode of Opening a File Input –ifstream fin(“datafile.in”, ios::in); Output –ofstream fout(“datafile.out”, ios::out); Both input and output –fstream acctFile(“accountfile.txt”, ios::in|ios::out); Append –ofstream fout(“accountfile.txt”, ios::app); 18