Download presentation
Presentation is loading. Please wait.
Published byFelix Hood Modified over 9 years ago
1
Recursion
2
A recursive function contains a call to itself Example: the factorial n!=n*(n-1)! for n>1 n!=1 for n=1 int factorial (int n) { if (n == 0) { return 1; } else { return (n * factorial (n-1)); }
3
Stacks and The Recursive Call Computers use a structure called a stack to keep track of recursion A stack is a memory structure analogous to a stack of paper: Last In First Out Whenever a function is called, the computer uses a "clean sheet of paper“ called active frame The function definition is copied to the paper The arguments are plugged in for the parameters The computer starts to execute the function body
4
Recursion Key elements of a recursive function The function calls itself There must be some terminal condition that ends the recursion Otherwise you will call yourself infinitely and the program will blow up The recursion should be getting simpler on each call
5
Examples power function: int power(int base, int exponent); power (2,4)=2*2*2*2 power(2,4)=2*power(2,3) power(x,n)=x*power(x,n-1) (for n>0) =1 (for n=0) int power (int base, int exponent) { fill in the space };
6
power function int power(int base, int exponent) { If (exponet==0) return 1; else If (exponet>0) return (base*power(base, exponent-1)); else { cout<<“we only take care of positive exponent”<<endl ; exit(1) }
7
Fibonacci sequence Fibonacci sequence
8
Fibonacci sequence function int fibonacci(int n) { if (n == 1) { return 1; } else if (n == 2) { return 1; } else { return fibonacci(n-1) + fibonacci(n-2); }
9
Recursion and iteration Any task that can be accomplished using recursion can also be done without recursion A nonrecursive version of a function typically contains a loop or loops A non-recursive version of a function is usually called an iterative-version A recursive version of a function Usually runs slower Uses more storage May use code that is easier to write and understand
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.