To Find Factorial of a positive integer n is equal factorial of a positive integer n is equal to 1*2*3*…n. You will learn to calculate the factorial of a number using for loop in this example.
To understand this example i.e C++ Program to Find Factorial, you should have the knowledge of following C++ programming topics:
- C++ for Loop
For any positive number n, it’s factorial is given by:
factorial = 1*2*3...*n
Factorial of a negative number cannot be found and factorial of 0 is 1.
In this program below, the user is asked to enter a positive integer. Then the factorial of that number is computed and displayed on the screen.
Find Factorial of a given number
#include <iostream> using namespace std; int main() { unsigned int n; unsigned long long factorial = 1; cout << "Enter a positive integer: "; cin >> n; for(int i = 1; i <=n; ++i) { factorial *= i; } cout << "Factorial of " << n << " = " << factorial; return 0; }
Output
Enter a positive integer: 12 Factorial of 12 = 479001600
Here variable factorial is of type unsigned long long
.
It is because factorial of a number is always positive, that’s why unsigned
the qualifier is added to it.
Since the factorial a number can be large, it is defined as long long
.
Related Program
- C++ Program to check leap year.
- C++ Program to find factorial.
- C++ Program to display Fibonacci series.
- C++ Program to find GCD using for and while loop.
- C++ Program to find LCM.
- C++ Program to reverse integer or number.
- C++ Program to display factors of a Number.
- C++ Program to check whether a number is a Palindrome or Not.
- C++ Program to display Prime Number Between two intervals.
- C++ Program to Check Whether Number is Even or Odd
- C++ Program to Check Whether a Character is Vowel or Consonant
- C++ Program to Find the Largest Number Of Three Numbers
Ask your questions and clarify your doubts on how to find Factorial in C++ by commenting. Documentation.