Factorial of a Number

Program to calculate factorial of a number

C++Beginner
C++
#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

Factorial of a Number in C++

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.

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

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

Why Use long long?

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

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