Find Factorial of a Number Using Recursion

0
Output

Calculation & Dry Run

This section explains the mathematical calculation and a step-by-step dry run (call stack) for the recursive factorial function. Example input used: 5.

Mathematical Calculation

Factorial definition:

n! = n × (n-1) × (n-2) × … × 1

So for n = 5:

5! = 5 × 4 × 3 × 2 × 1

= 120

Dry Run (Function Call Stack)

Assume the program calls fact(5). The recursion expands until the base case (n <= 1) is reached. Each step waits for the inner call to return.

Step

Function Call Action / Return Value Stack Status
1 fact(5) Needs 5 × fact(4) fact(5) waiting for fact(4)
2 fact(4) Needs 4 × fact(3) fact(5) → fact(4)
3 fact(3) Needs 3 × fact(2) fact(5) → fact(4) → fact(3)
4 fact(2) Needs 2 × fact(1) fact(5) → fact(4) → fact(3) → fact(2)
5 fact(1) Base case reached, returns 1 Inner-most call returns
6 fact(2) resumes Returns 2 × 1 = 2 fact(5) → fact(4) → fact(3)
7 fact(3) resumes Returns 3 × 2 = 6 fact(5) → fact(4)
8 fact(4) resumes Returns 4 × 6 = 24 fact(5)
9 fact(5) resumes Returns 5 × 24 = 120 Stack empty

Final Output

The factorial is 120

Code (C) — For Reference

Tags

Post a Comment

0Comments

Post a Comment (0)