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

Factorial of n (n!) is the product of all positive integers from 1 to n. We use long long to handle large factorials. The program multiplies numbers from 1 to n iteratively. We also check for negative input as factorial is only defined for non-negative integers.

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.

Table of Contents