Dry Run = Step-by-step tracing of code with values
Debugging = Finding and fixing errors in logic or flow
#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;
}
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
int factorial(int n){
if(n == 1) return 1;
return n * factorial(n - 1);
}
factorial(0) is called?n == 0
int factorial(int n){
if(n == 0 || n == 1) return 1; // ✔️ Base Case Fixed
return n * factorial(n - 1);
}