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.
1#include <iostream>2using namespace std;34// Recursive function to calculate factorial5int factorial(int n) {6 // Base case7 if (n == 0 || n == 1) {8 return 1;9 }1011 // Recursive case12 return n * factorial(n - 1);13}1415int main() {16 int num;17 cout << "Enter a number: ";18 cin >> num;1920 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 }2627 // Display factorial of first 10 numbers28 cout << "\nFactorials of 0-10:" << endl;29 for (int i = 0; i <= 10; i++) {30 cout << i << "! = " << factorial(i) << endl;31 }3233 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
Read num and reject negatives.
- 2
factorial(n) returns 1 for 0 or 1.
- 3
Otherwise it returns n * factorial(n - 1).
- 4
Print the result and then 0! to 10!.
Dry run: Factorial using Recursion
factorial(5)
- 1.= 5 * factorial(4)
- 2.= 5 * 4 * factorial(3)
- 3.= 5 * 4 * 3 * factorial(2)
- 4.= 5 * 4 * 3 * 2 * factorial(1)
- 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:
Key Components:
Factorial Definition
Mathematical Definition:
Recursive Definition:
Base Case
Stopping Condition:
if (n == 0 || n == 1) {
return 1;
}
What happens here:
Recursive Case
Function Calls Itself:
return n * factorial(n - 1);
What happens here:
Recursion Flow
Example: factorial(5):
When to Use Recursion
Good fits:
Example Scenarios:
Important Considerations
Base Case:
Stack Overflow:
Performance:
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.