























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The above uploaded documents covers the following topic in details..these are some verified and important lectures for those studnts or teachers who want to have some knwldge about the following topic along with pratice questions..IT CONTAIN code also for beginners and easy explanation
Typology: Slides
1 / 31
This page cannot be seen from the preview
Don't miss anything!
























- Recursion
- A definition in which something is defined in terms
Example (Recursive Power Function)
int Power ( int x , int n ) { if ( n == 1 ) return x; //Base case else return x * Power (x, n-1); // recursive call }
Recursive function: when we write a function in a simpler form of itself
Example 2 (Recursive Factorial Function)
- Factorial definition
n! = n × n-1 × n-2 × n-3 × … × 3 × 2 × 1 0! = 1
- To calculate factorial of n - Base case - If n = 0, return 1 - Recursive step - Calculate the factorial of n- - Return n × (the factorial of n-1)
To evaluate Factorial(3) evaluate 3 * Factorial(2) To evaluate Factorial(2) evaluate 2 * Factorial(1) To evaluate Factorial(1) evaluate 1 * Factorial(0) Factorial(0) is 1 Return 1 Evaluate 1 * 1 Return 1 Evaluate 2 * 1 Return 2 Evaluate 3 * 2 Return 6
The Runtime Stack during Recursion
int main() { cout << factorial(4); return 0; }
int factorial(int n) { int result; if ((n == 1) || (n == 0)) return 1; else { result = n * factorial(n-1); return result; } {
stack
Fact: return=
stack
Fact: return=
Fact: return=
stack
Fact: return=
Fact: return=
Fact: return=
Fact: return=
()int main } ;cout << factorial(4) ;return 0 {
int factorial(int n) } ;int result if ((n == 1) || (n == 0)) ;return 1 } else ;result = n * factorial(n-1) ;return result