Recursion.

Slides:



Advertisements
Similar presentations
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
Advertisements

Recursive Functions The Fibonacci function shown previously is recursive, that is, it calls itself Each call to a recursive method results in a separate.
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.
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. Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn about recursive algorithms Lecture.
Recursion CS-240/CS341. What is recursion? a function calls itself –direct recursion a function calls its invoker –indirect recursion f f1 f2.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 – Recursive Funtions From Deitel’s “C” Book 5.13Recursion 5.14Example Using Recursion: The Fibonacci.
Chapter 14: Recursion Starting Out with C++ Early Objects
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
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.
Comp 245 Data Structures Recursion. What is Recursion? A problem solving concept which can be used with languages that support the dynamic allocation.
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.
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
Chapter 14 Recursion. Chapter Objectives Learn about recursive definitions Explore the base case and the general case of a recursive definition Learn.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Functions (Recursion) Outline 5.13Recursion 5.14Example.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Recursion Part 3 CS221 – 2/27/09. Recursion A function calls itself directly: Test() { … Test(); … }
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Functions-Recall 1. 2 Parameter passing & return void main() { int x=10, y=5; printf (“M1: x = %d, y = %d\n”, x, y); interchange (x, y); printf (“M2:
Sudeshna Sarkar, IIT Kharagpur 1 Functions : Recursion Lecture
1 Recursion. 2 A process by which a function calls itself repeatedly  Either directly. X calls X  Or cyclically in a chain. X calls Y, and Y calls X.
A Brief Introduction to Recursion. Recursion Recursive methods … –methods that call themselves! –They can only solve a base case –So, you divide a problem.
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.
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.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
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
Recursion.
Programming and Data Structures
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion CENG 707.
Chapter 15 Recursion.
Introduction to Recursion
Chapter 10 Recursion Instructor: Yuksel / Demirer.
5.13 Recursion Recursive functions Functions that call themselves
Data Structures and Algorithms
Chapter 17 Recursion.
Chapter 15 Recursion.
CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)
Functions.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Algorithm Analysis (for Divide-and-Conquer problems)
Chapter 17 Recursion.
Recursion Chapter 11.
CS201: Data Structures and Discrete Mathematics I
Recursion Data Structures.
Functions Recursion CSCI 230
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
Stack Frames and Functions
Chapter 17 Recursion.
Module 1-10: Recursion.
Recursion When performing a repetitive task either: a loop recursion
Java Programming: Chapter 9: Recursion Second Edition
CSC 143 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
ICS103 Programming in C Lecture 11: Recursive Functions
Presentation transcript:

Recursion

Recursion A process by which a function calls itself repeatedly Either directly. X calls X Or cyclically in a chain. X calls Y, and Y calls X Used for repetitive computations in which each action is stated in terms of a previous result fact(n) = n * fact (n-1)

Contd. For a problem to be written in recursive form, two conditions are to be satisfied: It should be possible to express the problem in recursive form Solution of the problem in terms of solution of the same problem on smaller sized data The problem statement must include a stopping condition fact(n) = 1, if n = 0 = n * fact(n-1), if n > 0 Stopping condition Recursive definition

Examples: Factorial: fact(0) = 1 fact(n) = n * fact(n-1), if n > 0 GCD: gcd (m, m) = m gcd (m, n) = gcd (m%n, n), if m > n gcd (m, n) = gcd (n, n%m), if m < n Fibonacci series (1,1,2,3,5,8,13,21,….) fib (0) = 1 fib (1) = 1 fib (n) = fib (n-1) + fib (n-2), if n > 1

Factorial long int fact (int n) { if (n == 1) return (1); else return (n * fact(n-1)); }

Factorial Execution long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); }

Factorial Execution long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); }

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); }

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); if (3 = = 1) return (1); else return (3 * fact(2)); long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); }

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); if (3 = = 1) return (1); else return (3 * fact(2)); if (2 = = 1) return (1); else return (2 * fact(1)); long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); }

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); if (3 = = 1) return (1); else return (3 * fact(2)); if (2 = = 1) return (1); else return (2 * fact(1)); long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); } if (1 = = 1) return (1);

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); if (3 = = 1) return (1); else return (3 * fact(2)); if (2 = = 1) return (1); else return (2 * fact(1)); 1 long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); } if (1 = = 1) return (1);

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); if (3 = = 1) return (1); else return (3 * fact(2)); 2 if (2 = = 1) return (1); else return (2 * fact(1)); 1 long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); } if (1 = = 1) return (1);

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); if (3 = = 1) return (1); else return (3 * fact(2)); 2 if (2 = = 1) return (1); else return (2 * fact(1)); 1 long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); } if (1 = = 1) return (1);

Factorial Execution long int fact (int n) { if (n = = 1) return (1); if (4 = = 1) return (1); else return (4 * fact(3)); 6 if (3 = = 1) return (1); else return (3 * fact(2)); 2 if (2 = = 1) return (1); else return (2 * fact(1)); 1 long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); } if (1 = = 1) return (1);

Factorial Execution long int fact (int n) { if (n = = 1) return (1); 24 if (4 = = 1) return (1); else return (4 * fact(3)); 6 if (3 = = 1) return (1); else return (3 * fact(2)); 2 if (2 = = 1) return (1); else return (2 * fact(1)); 1 long int fact (int n) { if (n = = 1) return (1); else return (n * fact(n-1)); } if (1 = = 1) return (1);

Look at the variable addresses (a slightly different program) ! void main() { int x,y; scanf("%d",&x); y = fact(x); printf ("M: x= %d, y = %d\n", x,y); } int fact(int data) { int val = 1; printf("F: data = %d, &data = %u \n &val = %u\n", data, &data, &val); if (data>1) val = data*fact(data-1); return val; Output 4 F: data = 4, &data = 3221224528 &val = 3221224516 F: data = 3, &data = 3221224480 &val = 3221224468 F: data = 2, &data = 3221224432 &val = 3221224420 F: data = 1, &data = 3221224384 &val = 3221224372 M: x= 4, y = 24

Fibonacci Numbers int fib (int n) { if (n == 0 or n == 1) Fibonacci recurrence: fib(n) = 1 if n = 0 or 1; = fib(n – 2) + fib(n – 1) otherwise; int fib (int n) { if (n == 0 or n == 1) return 1; [BASE] return fib(n-2) + fib(n-1) ; [Recursive] }

Fibonacci recurrence: fib(n) = 1 if n = 0 or 1; int fib (int n) { if (n == 0 || n == 1) return 1; return fib(n-2) + fib(n-1) ; } Fibonacci recurrence: fib(n) = 1 if n = 0 or 1; = fib(n – 2) + fib(n – 1) otherwise; fib (5) fib (3) fib (4) fib (1) fib (2) fib (2) fib (3) fib (0) fib (1) fib (1) fib (2) fib (0) fib (1) fib (1) fib (0)

Fibonacci recurrence: fib(n) = 1 if n = 0 or 1; int fib (int n) { if (n == 0 || n == 1) return 1; return fib(n-2) + fib(n-1) ; } Fibonacci recurrence: fib(n) = 1 if n = 0 or 1; = fib(n – 2) + fib(n – 1) otherwise; fib (5) fib (3) fib (4) fib (1) fib (2) fib (2) fib (3) 1 fib (0) fib (1) fib (1) fib (2) fib (0) fib (1) 1 1 1 1 1 fib (1) fib (0) 1 1 fib.c

Fibonacci recurrence: fib(n) = 1 if n = 0 or 1; int fib (int n) { if (n==0 || n==1) return 1; return fib(n-2) + fib(n-1) ; } Fibonacci recurrence: fib(n) = 1 if n = 0 or 1; = fib(n – 2) + fib(n – 1) otherwise; 8 fib (5) 3 5 fib (3) fib (4) 2 3 1 2 fib (1) fib (2) fib (2) fib (3) 1 2 1 1 1 1 1 fib (0) fib (1) fib (1) fib (2) fib (0) fib (1) 1 1 1 1 1 1 1 fib (1) fib (0) 1 1

Sum of Squares int sumSquares (int m, int n) { int middle ; if (m == n) return m*m; else middle = (m+n)/2; return sumSquares(m,middle) + sumSquares(middle+1,n); }

Annotated Call Tree 355 sumSquares(5,10) sumSquares(5,10) 245 110 61 49 145 100 sumSquares(5,6) sumSquares(7,7) sumSquares(8,9) sumSquares(10,10) 25 36 81 64 sumSquares(5,5) sumSquares(6,6) sumSquares(8,8) sumSquares(9,9) 25 36 49 81 100 64

Towers of Hanoi Problem 5 4 3 2 1 LEFT CENTER RIGHT

Initially all the disks are stacked on the LEFT pole Required to transfer all the disks to the RIGHT pole Only one disk can be moved at a time. A larger disk cannot be placed on a smaller disk CENTER pole is used for temporary storage of disks

Recursive statement of the general problem of n disks Step 1: Step 2: Move the top (n-1) disks from LEFT to CENTER Step 2: Move the largest disk from LEFT to RIGHT Step 3: Move the (n-1) disks from CENTER to RIGHT

Tower of Hanoi A B C

Tower of Hanoi A B C

Tower of Hanoi A B C

Tower of Hanoi A B C

Towers of Hanoi function void towers (int n, char from, char to, char aux) { /* Base Condition */ if (n==1) { printf (“Disk 1 : %c  &c \n”, from, to) ; return ; } /* Recursive Condition */ towers (n-1, from, aux, to) ; …………………….

Towers of Hanoi function void towers (int n, char from, char to, char aux) { /* Base Condition */ if (n==1) { printf (“Disk 1 : %c  &c \n”, from, to) ; return ; } /* Recursive Condition */ towers (n-1, from, aux, to) ; printf (“Disk %d : %c  %c\n”, n, from, to) ; …………………….

Towers of Hanoi function void towers (int n, char from, char to, char aux) { /* Base Condition */ if (n==1) { printf (“Disk 1 : %c  %c \n”, from, to) ; return ; } /* Recursive Condition */ towers (n-1, from, aux, to) ; printf (“Disk %d : %c  %c\n”, n, from, to) ; towers (n-1, aux, to, from) ;

TOH runs Output void towers(int n, char from, char to, char aux) { if (n==1) { printf ("Disk 1 : %c -> %c \n", from, to) ; return ; } towers (n-1, from, aux, to) ; printf ("Disk %d : %c -> %c\n", n, from, to) ; towers (n-1, aux, to, from) ; void main() { int n; scanf("%d", &n); towers(n,'A',‘C',‘B'); Output 3 Disk 1 : A -> C Disk 2 : A -> B Disk 1 : C -> B Disk 3 : A -> C Disk 1 : B -> A Disk 2 : B -> C

More TOH runs Output 4 Disk 1 : A -> B Disk 2 : A -> C Disk 1 : B -> C Disk 3 : A -> B Disk 1 : C -> A Disk 2 : C -> B Disk 4 : A -> C Disk 2 : B -> A Disk 3 : B -> C void towers(int n, char from, char to, char aux) { if (n==1) { printf ("Disk 1 : %c -> %c \n", from, to) ; return ; } towers (n-1, from, aux, to) ; printf ("Disk %d : %c -> %c\n", n, from, to) ; towers (n-1, aux, to, from) ; void main() { int n; scanf("%d", &n); towers(n,'A',‘C',‘B');

Relook at recursive Fibonacci: Not efficient !! Same sub-problem solved many times. int fib (int n) { if (n==0 || n==1) return 1; return fib(n-2) + fib(n-1) ;} fib (5) fib (3) fib (4) fib (1) fib (2) fib (2) fib (3) fib (0) fib (1) fib (1) fib (2) fib (0) fib (1) How many calls? How many additions? fib (1) fib (0)

Much Less Computation here! Iterative Fib int fib( int n) { int i=2, res=1, m1=1, m2=1; if (n ==0 || n ==1) return res; for ( ; i<=n; i++) { res = m1 + m2; m2 = m1; m1 = res; } return res; void main() { int n; scanf("%d", &n); printf(" Fib(%d) = %d \n", n, fib(n)); Much Less Computation here! (How many additions?)

An efficient recursive Fib int Fib(int m1, int m2, int n, int i) { int res; if (n == i) res = m1+ m2; else res = Fib(m1+m2, m1, n, i+1); return res; } int Fib ( int, int, int, int); void main() { int n; scanf("%d", &n); if (n == 0 || n ==1) printf("F(%d) = %d \n", n, 1); else printf("F(%d) = %d \n", n, Fib(1,1,n,2)); } Much Less Computation here! (How many calls/additions?)

Run Output $ ./a.out 3 F: m1=1, m2=1, n=3, i=2 F: m1=2, m2=1, n=3, i=3 5 F: m1=1, m2=1, n=5, i=2 F: m1=2, m2=1, n=5, i=3 F: m1=3, m2=2, n=5, i=4 F: m1=5, m2=3, n=5, i=5 F(5) = 8 int Fib ( int, int, int, int); void main() { int n; scanf("%d", &n); if (n == 0 || n ==1) printf("F(%d) = %d \n", n, 1); else printf("F(%d) = %d \n", n, Fib(1,1,n,2)); } int Fib(int m1, int m2, int n, int i) { int res; printf("F: m1=%d, m2=%d, n=%d, i=%d\n", m1,m2,n,i); if (n == i) res = m1+ m2; else res = Fib(m1+m2, m1, n, i+1); return res;

each time a function is activated int Fib(int n, int i) { static int m1, m2; int res, temp; if (i==2) {m1 =1; m2=1;} if (n == i) res = m1+ m2; else { temp = m1; m1 = m1+m2; m2 = temp; res = Fib(n, i+1); } return res; Static Variables int Fib (int, int); void main() { int n; scanf("%d", &n); if (n == 0 || n ==1) printf("F(%d) = %d \n", n, 1); else printf("F(%d) = %d \n", n, Fib(n,2)); } Static variables remain in existence rather than coming and going each time a function is activated

Static Variables: See the addresses! int Fib(int n, int i) { static int m1, m2; int res, temp; if (i==2) {m1 =1; m2=1;} printf("F: m1=%d, m2=%d, n=%d, i=%d\n", m1,m2,n,i); printf("F: &m1=%u, &m2=%u\n", &m1,&m2); printf("F: &res=%u, &temp=%u\n", &res,&temp); if (n == i) res = m1+ m2; else { temp = m1; m1 = m1+m2; m2 = temp; res = Fib(n, i+1); } return res; } Output 5 F: m1=1, m2=1, n=5, i=2 F: &m1=134518656, &m2=134518660 F: &res=3221224516, &temp=3221224512 F: m1=2, m2=1, n=5, i=3 F: &res=3221224468, &temp=3221224464 F: m1=3, m2=2, n=5, i=4 F: &res=3221224420, &temp=3221224416 F: m1=5, m2=3, n=5, i=5 F: &res=3221224372, &temp=3221224368 F(5) = 8

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 Choice between performance (iteration) and good software engineering (recursion).

Every recursive program can also be written without recursion Recursion is used for programming convenience, not for performance enhancement Sometimes, if the function being computed has a nice recurrence form, then a recursive code may be more readable

How are function calls implemented? The following applies in general, with minor variations that are implementation dependent The system maintains a stack in memory Stack is a last-in first-out structure Two operations on stack, push and pop Whenever there is a function call, the activation record gets pushed into the stack Activation record consists of the return address in the calling program, the return value from the function, and the local variables inside the function

STACK Activation record Before call After call After return void main() { …….. x = gcd (a, b); } int gcd (int x, int y) { …….. return (result); } Local Variables Activation record STACK Return Value Return Addr Before call After call After return

Before call Call ncr Call fact fact returns ncr returns void main() { …….. x = ncr (a, b); } int ncr (int n, int r) { return (fact(n)/ fact(r)/fact(n-r)); } int fact (int n) { ……… return (result); } 3 times 3 times LV2, RV2, RA2 LV1, RV1, RA1 LV1, RV1, RA1 LV1, RV1, RA1 Before call Call ncr Call fact fact returns ncr returns

What happens for recursive calls? What we have seen …. Activation record gets pushed into the stack when a function call is made Activation record is popped off the stack when the function returns In recursion, a function calls itself Several function calls going on, with none of the function calls returning back Activation records are pushed onto the stack continuously Large stack space required

We shall illustrate the process by an example of computing factorial Activation records keep popping off, when the termination condition of recursion is reached We shall illustrate the process by an example of computing factorial Activation record looks like: Return Addr Return Value Local Variables

Example:: main() calls fact(3) void main() { int n; n = 3; printf (“%d \n”, fact(n) ); } int fact (n) int n; { if (n = = 0) return (1); else return (n * fact(n-1)); }

TRACE OF THE STACK DURING EXECUTION RA .. main - n = 3 RA .. fact n = 2 n = 1 1 n = 0 1*1 = 1 2*1 = 2 3*2 = 6 main calls fact fact returns to main

Do Yourself Trace the activation records for the following version of Fibonacci sequence int f (int n) { int a, b; if (n < 2) return (n); else { a = f(n-1); b = f(n-2); return (a+b); } void main() { printf(“Fib(4) is: %d \n”, f(4)); Local Variables (n, a, b) X Return Value Return Addr (either main, or X, or Y) Y main