Cs212: DataStructures
Download
Report
Transcript Cs212: DataStructures
1
CS212: DATASTRUCTURES
Computer Science Department
Lab 3 : Recursion
Overview
2
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
Rules
3
1.
Every recursive function must have a base case.
2.
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.
21-Jul-15
Computer Science Department
Example1: Calculating Factorial
4
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;
}
21-Jul-15
public static int factorial (int n)
{
int result = 1;
for (int i=1; i<= n; i++)
{ result = result * i;}
return result;
}
Computer Science Department
Calculating Factorial ( cont.)
5
Recursive version of factorial
Base case
(JAVA)
(C++)
Public static int factorial (int n)
{
if (N == 0)
return 1;
else
return N * factorial(N-1);
int factorial (int N)
{
if (N == 0)
return 1;
else
return N * factorial(N-1);
Recursive
calls
}
}
21-Jul-15
Computer Science Department
Example 2: Printing integers
6
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) ;
}
21-Jul-15
Computer Science Department
Printing integers (cont.)
7
Recursive version:
In Java
In C++
void printInt( int N )
{
if (N == 0) return;
printInt( N - 1 );
cout << N << endl;
Base case
Public static void printInt(
int N )
{
if (N == 0) return;
printInt( N - 1 );
System.out.println( N );
Recursive
calls
}
}
21-Jul-15
Computer Science Department