c-plus-plus
  1. c-plus-plus-factorial

C++ Program to Calculate Factorial

A factorial of a number is the product of all the numbers from 1 to that number. For example, the factorial of 5 is 54321 = 120.

Syntax

int factorial(int n) {
    if (n == 1) return 1;
    return n * factorial(n-1);
}

Example

#include <iostream>
using namespace std;

int factorial(int n) {
    if (n == 1) return 1;
    return n * factorial(n-1);
}

int main() {
    int num;
    cout << "Enter a positive integer: ";
    cin >> num;

    cout << "Factorial of " << num << " is " << factorial(num) << endl;
    return 0;
}

Output

Enter a positive integer: 5
Factorial of 5 is 120

Explanation

In the above example, we have defined a function called factorial which takes an integer argument and returns the factorial of that integer. The function uses recursion to calculate the factorial.

In the main function, we get an integer input from the user and then call the factorial function to compute the factorial. Finally, we print the result to the console.

Use

Factorials are useful in combinatorial problems that involve selecting objects from a set. They are also used in probability theory and statistics to calculate permutations and combinations.

Important Points

  • The factorial of 0 is defined to be 1.
  • Factorials increase very rapidly as the input number increases, so be careful not to overflow the integer data type.
  • Recursive functions can be used to calculate factorials.

Summary

In summary, calculating the factorial of a number is a common problem in mathematics and computer science. It can be easily calculated using a recursive function. Factorials are important in combinatorial problems and can be used to calculate permutations and combinations.

Published on: