Topic 1

Recursion

What is Recursion?

A function that calls itself to solve smaller sub-problems. Every recursive function needs:

  1. Base Case โ€” stops the recursion
  2. Recursive Case โ€” function calls itself with simpler input

Each call is pushed onto the call stack. When base case is hit, calls return one by one (unwinding).

โšก
LIFO in call stack โ€” Last called function returns first. Print AFTER recursive call = ascending.
๐ŸŽฏ
Base case is mandatory โ€” Without it โ†’ infinite recursion โ†’ stack overflow.
๐Ÿ”ฌ
Print before call = descending. Print after call = ascending.
๐Ÿ“Š
Time: O(n) for linear recursion. Space: O(n) due to call stack.
#include <iostream>
using namespace std;

void f(int x) {
    if (x > 0) {
        cout << x;
        f(x - 2);
        cout << x;
    }
}

int main() {
    f(5);    // Output: 5 3 1 1 3 5
    return 0;
}

Exam Tip โ€” Tracing Output

For f(5) where print is before AND after call: 5 3 1 1 3 5

Going IN: prints 5, 3, 1 โ€” Coming BACK: prints 1, 3, 5

Pattern: n % 10 = last digit, n / 10 = remove last digit