Presentation is loading. Please wait.

Presentation is loading. Please wait.

RECURSIONL27-L28. To learn and the following concepts To design a recursive algorithm To solve problems using recursion To understand the relationship.

Similar presentations


Presentation on theme: "RECURSIONL27-L28. To learn and the following concepts To design a recursive algorithm To solve problems using recursion To understand the relationship."— Presentation transcript:

1 RECURSIONL27-L28

2 To learn and the following concepts To design a recursive algorithm To solve problems using recursion To understand the relationship and difference between recursion and iteration Objectives

3 A recursive function is a function that invokes/calls itself directly or indirectly. Useful programming technique Enables you to develop a natural, straightforward, simple solution to a problem that would otherwise be difficult to solve.  Useful for many tasks, like sorting and mathematical functions like factorial, fibonacci, exponentiation, GCD, Tower of Hanoi, etc. Recursion - Introduction

4 Recursive Thinking Recursion Process A child couldn't sleep, so her mother told a story about a little frog, who couldn't sleep, so the frog's mother told a story about a little bear, who couldn't sleep, so bear's mother told a story about a little weasel...who fell asleep....and the little bear fell asleep;...and the little frog fell asleep;...and the child fell asleep. 4

5 Steps to Design a Recursive Algorithm  Base case:  for a small value of n, it can be solved directly  Recursive case(s):  Smaller versions of the same problem  Algorithmic steps:  Identify the base case and provide a solution to it  Reduce the problem to smaller versions of itself  Move towards the base case using smaller versions

6 Let us consider the Iterative code … void main() { int i, n, sum=0; cout<<"Enter the limit"; cin>>n; cout<<"\nThe sum is"<<fnSum(n); } int fnSum(int n) { int sum=0; for(i=1;i<=n;i++) //Iteration sum=sum+i; return (sum); }

7 Let us consider the Recursive code … void main() { int i, n, sum=0; cout<<"Enter the limit"; cin>>n; cout<<"\nThe sum is"<<fnSum(n); } int fnSum(int x) { if (x == 1) //base case return 1; else return fnSum(x-1) + x; //recursive case }

8 So factorial(5) = 5* factorial(4) = 4* factorial(3) = 3*factorial(2) = 2* factorial(1) = 1*factorial(0) = 1 Factorial of a natural number– a classical recursive example

9 Factorial- recursive procedure #include long factorial (long n) { if (n ==0) //base case return (1); return (n * factorial (n-1)); } void main () { long number; cout << "Please type a number: "; cin >> number; cout << number << "! = " << factorial (number); }

10 Recursion - How is it doing! factorial(0) = 1 factorial(n) = n * factorial(n-1) [for n>0] long rFact (long a) { if (a ==0) return (1); return (a * rFact (a-1)); } rFact(5) rFact(4) x Notice that the recursion isn’t finished at the bottom -- It must unwind all the way back to the top in order to be done. 5 rFact(3) x 4 rFact(2) x 3 rFact(1) x 2 rFact(0) x 1 =1 =2 =6 =24 120 =1 =2 = 6 = 24 = 120

11 int rfibo(int n) { if (n <= 1) return n; else return (rfibo(n-1) + rfibo(n-2)); } Fibonacci Numbers: Recursion Output: n = 4 fib = 3 Fibonacci series is 0,1, 1, 2, 3, 5, 8 …

12 Fibonacci Numbers: Recursion fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) [for n>1] So fibonacci(4) = fibonacci(3) + fibonacci(2) (fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0)) ((fibonacci(1) + fibonacci(0)) + 1) + (1 + 0) ( 1 + 0 ) + 1) + (1 + 0) = 3

13 Recursive Calls initiated by Fib(4)

14 Fibonacci Series using Recursion int rfibo(int); void main(void) { int n,i, a[20], fibo; cout<<"enter any num to n\n"; cin>>n; cout<<“Fibonacci series “; for (i=1; i<=n; i++) { fibo = rfib(i); cout<<"\n"<<fibo; } int rfibo(int n) { if (n <= 1) return n; else return (rfibo(n-1) + rfibo(n-2)); }

15 15 Static Variable The value of static variable persists until the end of the program. Static variables can be declared as static int x;

16 16 void fnStat( ); void main() { int i; for( i= 1; i<=3; i++) fnStat( ); } void fnStat( ) { static int x = 0; x = x + 1; cout<<\nx= “<<x; } Output: x = 1 x = 2 x = 3 Output: x = 1 static int x = 0; Static Variable

17 int rev(int num) { static int n = 0; if(num > 0) n = (n* 10) + (num%10) ; else return n; return rev(num/10); } Extra problem: Reversing a Number: Recursion Output: num = 234 rev = 432

18 int gcd(int x, int y) { if (x == 0) return (y); if (y==0) return (x); return gcd(y, x % y); } GCD: Recursion Output: x= 24, y = 9 gcd = 3 gcd(24,9)  Control In gcd fn on call gcd(9,24%9) gcd(9, 6) gcd(6,9%6) gcd(6, 3) gcd(3,6%3) gcd(3, 0) return values return 3 return 3

19 Extra problem: Sorting: Recursion - Sort(list,n) Base Case: if length of the list (n) = 1 No sorting, return Recursive Call: 1. Find the smallest element in the list and place it in the 0th position 2. Sort the unsorted array from 1.. n-1 sort(&list[1], n-1) For eg: list [ ] = {33,-2,0,2,4} n=5

20 Sorting: Recursion sort(list, n); // call of fn & display of sorted array in main() int sort(int list[], int ln){ int i, tmp, min; if (ln == 1) return 0; /* find index of smallest no */ min = 0; for(i = 1; i < ln; i++) if (list[i] < list[min]) min = i; Output: Orign. array-: 33 -2 0 2 4 Sorted array -: -2 0 2 4 33 /* move smallest element to 0-th element */ tmp = list[0]; list[0] = list[min]; list[min] = tmp; /* recursion */ return sort(&list[1], ln-1); }

21 list[]function calls {33,-2,0,2,4} sort(list,5) Main() {-2,33,0,2,4} sort(&list[1],4) {-2,0,33,2,4} sort(&list[1],3) {-2,0,2,33,4}sort(&list[1],2) {-2,0,2,4,33} sort(&list[1],1) Base case reached.... Return Sorting using recursion - Example

22 Recursion - Should I or Shouldn’t I? Pros –Recursion is a natural fit for some types of problems Cons –Recursive programs typically use a large amount of computer memory and the greater the recursion, the more memory used –Recursive programs can be confusing to develop and extremely complicated to debug

23 RECURSIONIteration Uses more storage space requirement Less storage space requirement Overhead during runtimeLess Overhead during runtime Runs slowerRuns faster a better choice, a more elegant solution for recursive problems Less elegant solution for recursive problems Recursion Vs Iteration

24 Recursion – Do’s You must include a termination condition or Base Condition in recursive function; Otherwise your recursive function will run “forever” or infinite. Each successive call to the recursive function must be nearer to the base condition


Download ppt "RECURSIONL27-L28. To learn and the following concepts To design a recursive algorithm To solve problems using recursion To understand the relationship."

Similar presentations


Ads by Google