1 Joe Meehean.  call themselves directly  or indirectly void f(){... f();... } void g(){... h();... } void h(){... g();... }

Slides:



Advertisements
Similar presentations
Types of Recursive Methods
Advertisements

Computer Science II Recursion Professor: Evan Korth New York University.
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)
More on Recursive Methods KFUPM- ICS Data Structures.
Recursion. Binary search example postponed to end of lecture.
Proof Techniques and Recursion. Proof Techniques Proof by induction –Step 1: Prove the base case –Step 2: Inductive hypothesis, assume theorem is true.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
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 Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
1 Chapter 1 RECURSION. 2 Chapter 1  Subprogram implementation  Recursion  Designing Recursive Algorithms  Towers of Hanoi  Backtracking  Eight Queens.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 19 Recursion.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
CS 1704 Introduction to Data Structures and Software Engineering.
Chapter 7 Recursion Recursive methods Recursion in two- dimensional grids Recursive helper method Analysis of recursive algorithms.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
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.
ICS220 – Data Structures and Algorithms Dr. Ken Cosh Week 5.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 13 Recursion Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
Recursion A function is said to be recursive if it calls itself, either directly or indirectly. void repeat( int n ) { cout
Recursion. Recursive Methods  A recursive method is a method that calls itself.  General Form of Simple Recursive Methods  Every recursive method has.
C++ Programming Lecture 12 Functions – Part IV
1 Chapter 8 Recursion. 2 Recursive Function Call a recursion function is a function that either directly or indirectly makes a call to itself. but we.
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! =
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
Program Development and Design Using C++, Third Edition
Function Recursion to understand recursion you must understand recursion.
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.
Recursion ITFN The Stack. A data structure maintained by each program at runtime. Push Pop.
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.
Programming with Recursion
Recursion.
CS212: Data Structures and Algorithms
CS314 – Section 5 Recitation 9
Identify the Appropriate Method for Handling Repetition
Chapter 8: Recursion Data Structures in Java: From Abstract Data Types to the Java Collections Framework by Simon Gray.
Chapter 19: Recursion.
Introduction to Recursion
Recursion Lakshmish Ramaswamy.
Recursion DRILL: Please take out your notes on Recursion
5.13 Recursion Recursive functions Functions that call themselves
Data Structures and Algorithms
Computer Science 4 Mr. Gerb
More on Recursive Methods
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Cs212: DataStructures Computer Science Department Lab 3 : Recursion.
Stack Frames and Functions
RECURSION Annie Calpe
Module 1-10: Recursion.
Recursion Taken from notes by Dr. Neil Moore
Java Programming: Chapter 9: Recursion Second Edition
CSC 143 Recursion.
The structure of programming
Dr. Sampath Jayarathna Cal Poly Pomona
CSE 206 Course Review.
Recursion © Dave Bockus.
Presentation transcript:

1 Joe Meehean

 call themselves directly  or indirectly void f(){... f();... } void g(){... h();... } void h(){... g();... }

int factorial(int x){ int handback; if( x <= 1 ){ handback = 1; }else{ handback = x * factorial(x-1); } return handback; } factorial(4) = 4 * factorial(4 – 1) factorial(3) = 3 * factorial(3 – 1) … factorial(1) = 1

 When a recursive call is made: marks current place in code clones itself  copy of code  new parameters  new set of uninitialized local variables clone executes starting at beginning  When clone returns clone is cleaned up previous version starts at just after recursive method call

CLASS ACTIVITY void doClap(int k){ if(k == 0 ) return; clap k times; doClap(k – 1); return; } 1 st person: doClap(3)

 doClap(3) 3, 4, 5, 6, … memory access error stack overflow need code to stop recursion eventually void doClap(int k){ clap k times; doClap(k + 1); return; }

 Must have a base case Condition under which no recursive call is made Helps prevent infinite recursion void doClap(int k){ if( k == 0 ) return; clap k times; doClap(k + 1); return; } Still has infinite recursion?

 Must make progress towards base case void doClap(int k){ if( k == 0 ) return; clap k times; doClap(k - 1); return; } Does doClap follow rules 1 & 2? Infinite recursion? If so, how should we change the code

 Must make progress towards base case void doClap(int k){ if( k <= 0 ) return; clap k times; doClap(k - 1); return; } Does doClap follow rules 1 & 2? Infinite recursion? If so, how should we change the code

 printStr(“hello”, 0) => “hello”  printStr(“hello”, 2) => “llo” void printStr(string s, int k){ if( k >= s.length() ) return; cout << s[k]; printStr(s, k+1); }

Design rule assume that all recursive calls work even if you haven’t finished writing it yet void printStr(string s, int k){ if( k >= s.length() ) return; cout << s[k]; printStr(s, k+1); }

void printStr(string s, int k){ if( k >= s.length() ) return; cout << s[k] << endl; printStr(s, k+1); } cloneoutput printStr(“hello”, 0) printStr(“hello”, 1) printStr(“hello”, 2) printStr(“hello”, 3) printStr(“hello”, 4) printStr(“hello”, 5) h e l l o

void printStr(string s, int k){ if( k >= s.length() ) return; printStr(s, k+1); cout << s[k] << endl; } cloneoutput printStr(“hello”, 0) printStr(“hello”, 1) printStr(“hello”, 2) printStr(“hello”, 3) printStr(“hello”, 4) printStr(“hello”, 5) h e l l o

 A method may have statements before recursive call after recursive both  After statements are done only when the recursive call is finished and all the recursive calls recursive calls have finished

 Whats printed for printStr(“STOP”, 0)? void printStr(string s, int k){ if( k >= s.length() ) return; cout << s[k] << endl; printStr(s, k+1); cout << s[k] << endl; }

 Whats printed for printStr(“STOP”, 0)? STOPPOTS  How can we change it to print STOP POTS void printStr(string s, int k){ if( k >= s.length() ) return; cout << s[k] << endl; printStr(s, k+1); cout << s[k] << endl; }

 How can we change it to print STOP POTS void printStr(string s, int k){ if( k >= s.length() ){ cout ” << endl; return; } cout << s[k] << endl; printStr(s, k+1); cout << s[k] << endl; }

18

CallValue of k mystery(3)6 mystery(2)4 mystery(1)2 mystery(0) void mystery(int j){ if( j <= 0 ) return; int k = j * 2; mystery(j – 1); cout << k << “ “; } Each clone gets own local variables Outputs => 2 4 6

// sums #s from 1 to max // Iterative version int doSum(int max){ int sum = 0; for(int i = 1; i <= max; i++){ sum += i; } return sum; }

// sums #s from 1 to max // Iterative version int doSum(int max){ int sum = 0; for(int i = 1; i <= max; i++){ sum += i; } return sum; } // Recursive version int doSum(int max){ if( max <= 0 ) return 0; return max + doSum(max – 1); }

doSum(3) doSum(2) doSum(1) doSum(0)

 Can do recursion with int parameters count up or down to base case  Or, with recursive data structures a linked list is either empty or a node followed by a linked list

 Prints list in order void printList(Node * node){ if( node == NULL ) return; cout data_ << endl; printList(node->next_); }

 How can we change this code to print list backwards? void printList(Node * node){ if( node == NULL ) return; cout data_ << endl; printList(node->next_); }

void printList(Node * node){ if( node == NULL ) return; printList(node->next_); cout data_ << endl; }  Prints list backwards  Rare case where recursion makes code faster as well as simpler

 Activation records (ARs) stack of ARs maintained at runtime 1 AR for each active method active methods have been called, but not returned yet  Each AR includes: function parameters local variables return address

 Activation Record Stack when method is called, its AR is pushed when method returns, its AR is popped return address in popped AR tells program where to return control flow

 Auxiliary recursion wrapper method to do something ONCE before or after recursion OR pass more parameters recursion in auxiliary method wrapper sometimes called a driver  Multiple recursive calls per method need to recurse down a few different paths more on this when we talks about trees

// prints a header and the endline // calls aux to print the list void printList(Node * node){ cout << “The list contains: “; printAux(node); cout << endl; } // prints a single string containing // each element in brackets void printAux(Node * node){ if( node == NULL ) return; cout data_ << “]”; printAux(node->next_); }

// public method calls private method // with member variable int List::numNodes(){ return numAux(phead_); } // actually counts the nodes int List::numAux(Node * node){ if( node == NULL ){ return 0; } return 1 + numAux(node->next_); }

 Sum all elements in a vector but the first value int weirdSum(vector & intVect){ return sumVector(intVect, 1); } // actually sums the entries int sumVector( vector & intVect, int pos){ if( pos >= intVect.size() ) return 0; return intVect[pos] + sumAux(intVect, pos + 1); }

 Fibonacci fib(1) = 1, fib(2) = 1 fib(N) for N > 2 = fib(N-1) + fib(N-2) fib(3) = fib(2) + fib(1) = = 2 int fib(int n){ if( n <= 2) return 1; return fib(n – 2) + fib(n – 1); }

fib(4) fib(3) fib(2) fib(1)  Note: fib(2) is called twice  Redoing work

 Compound interest rule  Never duplicate work don’t solve the same recursive instance in separate recursive calls repeats work you’ve already done more on how to prevent this in CS242

36

 Recursion DOES NOT make your code faster  Recursion DOES NOT use less memory  Recursion DOES make your code simpler sometimes

 When you don’t get anything from it?  Tail recursion the only recursive call is the last line local variables stored just to be thrown away  Tail recursion can be replaced with a while loop

void printStr(string s, int k){ if( k >= s.length() ) return; cout << s[k] << endl; printStr(s, k+1); } void printStrin(string s, int k){ while( true ){ if( k >= s.length() ) return; cout << s[k] << endl; k = k + 1; }

void printString(string s, int k){ while( k < s.length() ){ cout << s[k] << endl; k = k + 1; }

1. Base case 2. Make progress 3. Design rule 4. Compound interest rule

42