Calculate Factorial in C++


Write a C++ Program to calculate the factorial of the entered number.

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
    unsigned int num;
    unsigned long long fact = 1;
    cout << "Insert any positive number:\n";
    cin >> num;
    for(int x = 1; x <=num; ++x)
        fact *= x;
    cout << "The factorial of " << num << " is " << fact;    
    return 0;

Click Here to View the Output:
Insert any positive number:
The factorial of 5 is 120
Click Here to View the Explanation:
  • User is asked for a number and the program calculates the factorial of that number. For loop is used to calculate factorial in this program. It is calculated by:
  • factorial = 1*2*3…*n
  • If 0 is entered by the user, the screen displays 1. In case a negative number is added, the program is expected to give an error displayed Factorial cannot be found.
  • The input is taken by the user. Please insert any positive number:. For the compiler to ignore any positive or negative signs, unsigned int is used.
  • Another variable fact is declared as unsigned long long. Unsigned qualifier is used so that the entered number is always positive. Moreover, factorial can be very large numbers, so we use long long for it.
  • The program runs and for every time the value of x is less than the entered positive number p, the program increments the value of x by 1 and multiplies the numbers.
  • The display prints: The factorial of 5 is 120

%d bloggers like this: