























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
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