Download presentation
Presentation is loading. Please wait.
Published byBrianne Cannon Modified over 6 years ago
1
Cs212: DataStructures Computer Science Department Lab 3 : Recursion
2
Overview Recursion is a function that calls itself
Repeats function (method) block of code until a specified condition is met int factorial() { ... factorial() ... } When a recursive call is made, the function (method) clones itself, making new copies of Code Local variables Parameters 21-Feb-14 Computer Science Department
3
Rules Every recursive function must have a base case.
Every recursive function must make progress towards its base case to prevent infinite recursion. Anything that can be programmed using recursive functions can be programmed without recursion. 8-Dec-18 Computer Science Department
4
Example1: Calculating Factorial
Factorial can be defined as follows Factorial of 0 is 1 Factorial of N (for N>0) is N * N-1 * ... * 3 * 2 * 1 Iterative version of factorial (JAVA) (C++) int factorial (int N) { int result = 1; for (int i=1; i<= N; i++) { result = result * i;} return result; } public static int factorial (int n) { int result = 1; for (int i=1; i<= n; i++) { result = result * i;} return result; } 8-Dec-18 Computer Science Department
5
Calculating Factorial ( cont.)
Recursive version of factorial Base case (JAVA) (C++) int factorial (int N) { if (N == 0) return 1; else return N * factorial(N-1); } Public static int factorial (int n) { if (N == 0) return 1; else return N * factorial(N-1); } Recursive calls 8-Dec-18 Computer Science Department
6
Example 2: Printing integers
Print integers from 1 to N. Iterative version: In C++ In Java void printInt( int N ) { for ( int i = 1 ; i<= N ; i++) cout << i << endl ; } void printInt( int N ) { for ( int i = 1 ; i<= N ; i++) System.out.println(i) ; } 8-Dec-18 Computer Science Department
7
Printing integers (cont.)
Recursive version: In C++ In Java Public static void printInt( int N ) { if (N == 0) return; printInt( N - 1 ); System.out.println( N ); } void printInt( int N ) { if (N == 0) return; printInt( N - 1 ); cout << N << endl; } Base case Recursive calls 8-Dec-18 Computer Science Department
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.