Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Factorial using Recursion in C++

Recursive factorial in C++ with a dry run of factorial(5): the base case, the call stack unwinding, why negatives never stop, and where int overflows.

BeginnerRecursion ProgramsExample 1 of 5
factorial-using-recursion.cpp
1#include <iostream>
2using namespace std;
3
4// Recursive function to calculate factorial
5int factorial(int n) {
6 // Base case
7 if (n == 0 || n == 1) {
8 return 1;
9 }
10
11 // Recursive case
12 return n * factorial(n - 1);
13}
14
15int main() {
16 int num;
17 cout << "Enter a number: ";
18 cin >> num;
19
20 if (num < 0) {
21 cout << "Factorial is not defined for negative numbers." << endl;
22 } else {
23 int result = factorial(num);
24 cout << "Factorial of " << num << " = " << result << endl;
25 }
26
27 // Display factorial of first 10 numbers
28 cout << "\nFactorials of 0-10:" << endl;
29 for (int i = 0; i <= 10; i++) {
30 cout << i << "! = " << factorial(i) << endl;
31 }
32
33 return 0;
34}

Sample Output

Factorial of 5 = 120

5 × 4 × 3 × 2 × 1.

0! = 1

Handled by the base case.

In this one

  • The two parts of every recursive function
  • How calls wait on the stack and then return
  • Why negative input needs a guard
  • Where int overflows for factorial

How it works

  1. 1

    Read num and reject negatives.

  2. 2

    factorial(n) returns 1 for 0 or 1.

  3. 3

    Otherwise it returns n * factorial(n - 1).

  4. 4

    Print the result and then 0! to 10!.

Dry run: Factorial using Recursion

factorial(5)

  1. 1.= 5 * factorial(4)
  2. 2.= 5 * 4 * factorial(3)
  3. 3.= 5 * 4 * 3 * factorial(2)
  4. 4.= 5 * 4 * 3 * 2 * factorial(1)
  5. 5.= 5 * 4 * 3 * 2 * 1 = 120
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1 = 120

Edge cases

13 or more

Enter 13.

13! is larger than int can hold, so the result overflows and prints a wrong value. Switch to long long.

Negative input

Enter -3.

main prints the "not defined" message, so factorial is never called with a negative number.

Very deep recursion

Call factorial(100000) with a long long version.

Each call uses stack space, so 100,000 frames can overflow the stack and crash. The loop version has no such limit.

What's going on

A recursive function calls itself on a smaller version of the same problem. Factorial fits perfectly: n! = n × (n − 1)!, and the chain stops at 1.

Every recursive function needs two parts. The base case answers the smallest problem directly; here, if (n == 0 || n == 1) return 1;. The recursive case shrinks the problem and calls itself: return n * factorial(n - 1);.

For factorial(5), nothing is multiplied on the way down. Each call waits for the one below it: factorial(5) waits for factorial(4), which waits for factorial(3), and so on to factorial(1), which returns 1. Then the answers come back up: 2 × 1 = 2, 3 × 2 = 6, 4 × 6 = 24, 5 × 24 = 120. Each waiting call is a frame on the call stack, holding its own copy of n.

main rejects negative input, because the base case would never be reached: factorial(−1) would call factorial(−2) forever until the stack runs out and the program crashes.

The loop then prints 0! to 10!. 0! = 1 by definition, which the base case handles.

The return type is int, which holds at most 2,147,483,647. 12! = 479,001,600 fits, but 13! = 6,227,020,800 does not. The multiplication overflows, which is undefined behavior for signed ints, and in practice prints a wrong number such as 1932053504. Use long long (good to 20!) or unsigned long long for bigger values.

The loop version in loop-programs does the same work without stack frames. Recursion here is for learning the pattern, which you will need for trees, divide-and-conquer sorts, and backtracking.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. Leave one out and the compiler stops at the first name it does not recognize.

Understanding Recursion

Recursion Concept:

Function calls itself
Breaks problem into subproblems
Base case stops recursion
Recursive case reduces problem

Key Components:

Base case: stops recursion
Recursive case: calls itself
Problem reduction: smaller subproblem
Stack: stores function calls

Factorial Definition

Mathematical Definition:

n! = n × (n-1) × (n-2) × ... × 2 × 1
0! = 1 (by definition)
1! = 1

Recursive Definition:

n! = n × (n-1)!
Base case: 0! = 1, 1! = 1
Recursive case: n! = n × (n-1)!

Base Case

Stopping Condition:

if (n == 0 || n == 1) {

return 1;

}

What happens here:

Stops recursion
Returns known value
Prevents infinite recursion
Essential for recursion

Recursive Case

Function Calls Itself:

return n * factorial(n - 1);

What happens here:

Calls factorial with smaller value
Reduces problem size
Multiplies result
Builds solution from subproblems

Recursion Flow

Example: factorial(5):

1.factorial(5) calls factorial(4)
2.factorial(4) calls factorial(3)
3.factorial(3) calls factorial(2)
4.factorial(2) calls factorial(1)
5.factorial(1) returns 1 (base case)
6.Each level multiplies and returns
7.Result: 5 × 4 × 3 × 2 × 1 = 120

When to Use Recursion

Good fits:

Problems with recursive structure
Tree/graph traversals
Divide and conquer
Mathematical definitions
Natural recursive problems

Example Scenarios:

Factorial, Fibonacci
Tree traversals
Sorting algorithms
Backtracking
Dynamic programming

Important Considerations

Base Case:

Must be reachable
Stops recursion
Prevents infinite loops
Essential component

Stack Overflow:

Deep recursion uses stack
Limited stack size
May cause overflow
Consider iterative for large n

Performance:

Recursion has overhead
Function call cost
Stack frame creation
Iterative may be faster

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What happens without the base case?

Pick an answer to check it.

Question 2

When is the multiplication 5 * 24 actually done?

Pick an answer to check it.

Questions people ask

Is recursion slower than a loop?

Slightly, because each call costs a stack frame. For factorial the loop is the better choice in real code.

What is a stack overflow?

Running out of call-stack memory because calls nest too deeply, usually from a missing or unreachable base case.

What is tail recursion?

A call that is the very last thing a function does. factorial(n - 1) is not, because the multiplication happens after it returns.