Factorial of a Number

Program to calculate factorial of a number

BeginnerTopic: Loop Programs
Back

C++ Factorial of a Number Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int n;
    long long factorial = 1;
    
    cout << "Enter a positive integer: ";
    cin >> n;
    
    if (n < 0) {
        cout << "Factorial is not defined for negative numbers" << endl;
    } else {
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        cout << "Factorial of " << n << " = " << factorial << endl;
    }
    
    return 0;
}
Output
Enter a positive integer: 5
Factorial of 5 = 120

Understanding Factorial of a Number

This program calculates the factorial of a number. Factorial is one of the most fundamental concepts in mathematics and programming, used extensively in permutations, combinations, probability, and many algorithms. The program demonstrates iterative multiplication, data type selection for large numbers, and input validation.

---

1. What is Factorial?

Factorial of a non-negative integer n (denoted as n!) is the product of all positive integers from 1 to n.

Mathematical definition:

n! = n × (n-1) × (n-2) × ... × 3 × 2 × 1
0! = 1 (by definition)
Factorial is only defined for non-negative integers

Examples:

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

120

4! = 4 × 3 × 2 × 1 =

24

3! = 3 × 2 × 1 =

6

2! = 2 × 1 =

2

1! =

1

0! =

1

Applications:

Permutations: Number of ways to arrange n items = n!
Combinations: Used in probability and statistics
Series expansions: Taylor series, binomial theorem
Algorithm analysis: Time complexity calculations

---

2. Header File: #include <iostream>

#include <iostream>

Provides:

cout → for displaying output
cin → for reading input

---

3. Declaring Variables

int n;

long long factorial = 1;

Variable `n`:

Stores the number entered by the user
The number for which we'll calculate factorial

Variable `factorial`:

Stores the result (the factorial value)

-

Initialized to 1

This is crucial!

Why initialize to 1?

Factorial is a product (multiplication)
1 is the identity element for multiplication
Starting with 1 ensures: 1 × 2 × 3 × ... = correct result
If initialized to 0: 0 × anything = 0 (wrong!)

Why use `long long` instead of `int`?

Factorials grow very rapidly
int can store values up to ~2.1 billion
13! = 6,227,020,800 (exceeds int range)
long long can store up to ~9.2 × 10^18
Can handle factorials up to 20! safely

---

4. Taking Input From User

`cout << "Enter a positive integer: ";`

cin >> n;

Prompts user to enter a number
Reads and stores it in n

Example:

User enters:

5

n = 5

---

5. Input Validation - Checking for Negative Numbers

if (n < 0)

cout << "Factorial is not defined for negative numbers" << endl;

Why check for negative?

Factorial is only defined for non-negative integers (0, 1, 2, 3, ...)
Negative numbers don't have factorial
We must handle this error case

What happens:

If user enters -5, program prints error message and exits
Prevents invalid calculations

---

6. Calculating Factorial Using For Loop

for (int i = 1; i <= n; i++)

factorial *= i;

How the loop works:

For n = 5:

Iteration 1 (i = 1):

factorial = factorial * ifactorial = 1 * 1 = 1
Now: factorial = 1

Iteration 2 (i = 2):

factorial = 1 * 2 = 2
Now: factorial = 2

Iteration 3 (i = 3):

factorial = 2 * 3 = 6
Now: factorial = 6

Iteration 4 (i = 4):

factorial = 6 * 4 = 24
Now: factorial = 24

Iteration 5 (i = 5):

factorial = 24 * 5 = 120
Now: factorial = 120

After loop:

factorial = 120

---

7. Understanding the Accumulation Pattern

factorial *= i; is shorthand for factorial = factorial * i;

This is the

multiplicative accumulation pattern

:

Start with 1 (identity for multiplication)
Multiply by each number from 1 to n
Result is the product of all numbers

Visual representation:

Initial: factorial = 1
Iteration 1: factorial = 1 × 1 = 1
Iteration 2: factorial = 1 × 2 = 2
Iteration 3: factorial = 2 × 3 = 6
Iteration 4: factorial = 6 × 4 = 24
Iteration 5: factorial = 24 × 5 = 120
Result: 120 ✅

---

8. Special Case: Factorial of 0

What if user enters 0?

Loop condition: i <= 01 <= 0 is

false

Loop doesn't execute
factorial remains 1
Output: "Factorial of 0 = 1" ✅

This is correct because

0! = 1

by mathematical definition.

Why is 0! = 1?

It's defined this way for mathematical consistency
Makes formulas work correctly (permutations, combinations)
Empty product equals 1 (similar to empty sum equals 0)

---

9. Displaying the Result

cout << "Factorial of " << n << " = " << factorial << endl;

This prints:

Text: "Factorial of "
Value of n: 5
Text: " = "
Value of factorial: 120
New line

Output:

Factorial of 5 = 120

---

10. Why Factorials Grow So Fast

Factorials increase extremely rapidly:

5! = 120
10! = 3,628,800
15! = 1,307,674,368,000
20! = 2,432,902,008,176,640,000

This is why we use `long long`:

int can only store up to ~2.1 billion
13! exceeds this limit
long long can handle up to 20! safely

For larger factorials:

Need even larger data types or special libraries
Or use approximation methods (Stirling's formula)

---

11. Alternative: Recursive Approach

Factorial can also be calculated recursively:

int factorial(int n) {

if (n <= 1) return 1;

}

    return n * factorial(n - 1);

Iterative (our approach):

Uses loop
More memory efficient
No function call overhead
Better for large numbers

Recursive:

More elegant code
Uses function calls (stack)
Can cause stack overflow for large n
Good for learning recursion

---

12. Real-World Applications

Permutations:

Number of ways to arrange n items = n!
Example: 5 books can be arranged in 5! = 120 ways

Combinations:

Used in probability: C(n, r) = n! / (r! × (n-r)!)

Series:

e^x = 1 + x/1! + x²/2! + x³/3! + ...
Used in calculus and physics

---

Summary

Factorial (n!) = product of all integers from 1 to n
0! = 1 by definition
Use long long to handle large factorials
Initialize factorial to 1 (identity for multiplication)
Use for loop to multiply numbers from 1 to n
Always validate input (check for negative numbers)
Factorials grow extremely fast

This program teaches:

Multiplicative accumulation pattern
Data type selection for large numbers
Input validation
Understanding mathematical functions in programming

Mastering factorial helps in:

Solving permutation/combination problems
Understanding recursive algorithms
Working with series and sequences
Many competitive programming problems

Factorial is one of the most fundamental concepts in mathematics and programming, and understanding it deeply helps in solving many advanced problems.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Factorial of a Number

This C++ program is part of the "Loop Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents