Factorial in C++

Factorial is a fundamental mathematical concept used to describe the product of all positive integers up to a given number. In C++, calculating factorials can be achieved through iterative or recursive approaches, depending on the problem’s requirements and constraints.

factorial in cpp

Calculating Factorial in C++ using Iteration

The iterative method involves using loops to compute the factorial of a number.

Here’s an example of how to calculate factorial using a for loop in C++:

#include <iostream>

unsigned long long calculateFactorial(int num) {
    unsigned long long factorial = 1;

    for (int i = 1; i <= num; ++i) {
        factorial *= i;
    }

    return factorial;
}

int main() {
    int number;
    std::cout << "Enter the number ";
    std::cin >> number;

    if (number < 0) {
        std::cout << "Invalid Input" << std::endl;
    } else {
        unsigned long long result = calculateFactorial(number);
        std::cout << "Factorial of " << number << " is: " << result << std::endl;
    }

    return 0;
}

Output

factorial in c++

Calculating Factorial in C++ using Recursion

Recursion involves breaking down the problem into smaller sub-problems of the same type. The factorial can be computed recursively in C++ as well:

#include <iostream>

unsigned long long calculateFactorial(int num) {
    if (num == 0 || num == 1) {
        return 1;
    } else {
        return num * calculateFactorial(num - 1);
    }
}

int main() {
    int number;
    std::cout << "Enter the number ";
    std::cin >> number;

    if (number < 0) {
        std::cout << "Inavlid input" << std::endl;
    } else {
        unsigned long long result = calculateFactorial(number);
        std::cout << "Factorial of " << number << " is: " << result << std::endl;
    }

    return 0;
}

Output

factorial program in c++

Both methods for calculating factorial in C++ have their pros and cons. The iterative approach is generally more efficient and consumes less memory, while the recursive approach might be more intuitive but can consume more memory due to function calls.

See Also

3 thoughts on “Factorial in C++”

Leave a Comment