C++ for Beginners: C++ Program to Find Factorial

Hits: 14

(C++ programming Example for Beginners)

C++ Program to Find Factorial

The 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.


For any positive number n, it’s factorial is given by:

factorial = 1*2*3...*n

Factorial of negative number cannot be found and factorial of 0 is 1.

In this program below, user is asked to enter a positive integer. Then the factorial of that number is computed and displayed in the screen.


Example: 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 qualifier is added to it.

Since the factorial a number can be large, it is defined as long long.

 

C++ for Beginners: C++ Program to Find Factorial

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.