Coding Exercise: Calculate Factorial Using Recursion

Write a recursive function to compute n! (factorial) where n! = n × (n-1) × ... × 1.

Test cases: factorial(5) = 120, factorial(0) = 1, factorial(1) = 1.

Problem Statement

Input: Integer n (0 ≤ n ≤ 12)

Output: n! (factorial value)

Base case: factorial(0) = 1, factorial(1) = 1

Recursive case: factorial(n) = n × factorial(n-1)

Approach

1. Check base case: if n ≤ 1, return 1

2. Otherwise: return n × factorial(n-1)

3. Function calls itself until base case reached

Solution Code

C++
Recursive factorial function
#include <iostream>
using namespace std;

// Recursive factorial function
int factorial(int n) {
    // Base case
    if (n <= 1) {
        return 1;
    }
    // Recursive case
    return n * factorial(n - 1);
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    
    cout << "Factorial of " << num << " = " << factorial(num) << endl;
    return 0;
}

Dry Run: factorial(4)

Step-by-step execution:

TEXT
Call stack trace
factorial(4) → 4 * factorial(3)
           ↓
factorial(3) → 3 * factorial(2)
           ↓
factorial(2) → 2 * factorial(1)
           ↓
factorial(1) → 1 (BASE CASE)

Unwind: 2*1=2 → 3*2=6 → 4*6=24

Result: 24 ✓

Test Cases

TEXT
Expected outputs
Input: 0    → Output: 1
Input: 1    → Output: 1
Input: 5    → Output: 120
Input: 6    → Output: 720

Time & Space Complexity

Time: O(n) - n recursive calls

Space: O(n) - call stack depth

Practice Variations

1. Sum of digits recursively (342 → 9)

2. Fibonacci sequence recursively

3. Reverse a string recursively

Conclusion

Mastered recursive factorial! Practice variations to build recursion intuition.

Next: Try Fibonacci or power function recursively.