Factorial in C++

Factorial is a fundamental mathematical concept that finds its significance in various algorithms and problem-solving techniques. In this article, we will write a program to calculate factorial in C++.

What is Factorial ?

Factorial, denoted by the exclamation mark ‘!’, is a mathmetical operation that calculates the product of all positive integers from 1 to a given number.

For example factorial of 6 is denoted as 6! and calculated as 6*5*4*3*2*1 = 720.

Factorial in C++

We can calculate factorial in c++, by using various approaches. Here we are going to use Iterative approach to calculate factorial. In Iterative approact we ise a loop to multiply each number from 1 to n.

#include <iostream>

unsigned long long factorialIterative(int n) {
    unsigned long long factorial = 1;
    for (int i = 1; i <= n; i++) {
        factorial *= i;
    }
    return factorial;
}

int main() {
    int num;
    std::cout << "Enter a positive integer: ";
    std::cin >> num;
    std::cout << "Factorial of " << num << " is: " << factorialIterative(num) << std::endl;
    return 0;
}
factorial in c++

You can check this tutorial for calculating factorial using recursion in c++ factorial using recursion in c++

1 thought on “Factorial in C++”

Leave a Comment