🔹 Dry Run + Debugging in C++ (with Recursion Example)

Dry Run = Step-by-step tracing of code with values

Debugging = Finding and fixing errors in logic or flow


✅ Let's Understand with a Simple Recursive Function:

🔸 Problem: Factorial using Recursion


#include <iostream>
using namespace std;

int factorial(int n) {
    if(n == 0 || n == 1) return 1;      // Base Case
    return n * factorial(n - 1);        // Recursive Call
}

int main() {
    cout << factorial(4);
    return 0;
}


🔁 Dry Run of factorial(4)

We trace every function call and return value:

Call Stack Execution Return Value
factorial(4) 4 * factorial(3) ?
factorial(3) 3 * factorial(2) ?
factorial(2) 2 * factorial(1) ?
factorial(1) Base case → return 1 1
factorial(2) 2 * 1 = 2 2
factorial(3) 3 * 2 = 6 6
factorial(4) 4 * 6 = 24 ✅ Final Answer

🧠 Output: 24


🐞 Now Let's See a Bug Example:


int factorial(int n){
    if(n == 1) return 1;
    return n * factorial(n - 1);
}

🔎 Bug: What if factorial(0) is called?


✅ Debugged Version:


int factorial(int n){
    if(n == 0 || n == 1) return 1;  // ✔️ Base Case Fixed
    return n * factorial(n - 1);
}