In this tutorial, you will learn how to write C++ programs to find the factorial of a non-negative integer using a while loop, a for loop, recursion, and a recursive ternary expression.

C++ Factorial Program

The factorial of a non-negative integer n, written as n!, is the product of all positive integers from 1 through n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. By definition, 0! = 1.

Following picture has the formula to calculate the factorial of a number. And also factorial examples for numbers 5 and 7.

C++ Factorial Programs

Factorial formula and valid input in C++

For an integer n > 0, factorial can be written as n! = n × (n - 1) × ... × 2 × 1. The special case is 0! = 1. The examples on this page assume that n is a non-negative integer. Factorial is not defined for negative integers in the usual integer factorial function.

</>
Copy
n! = n × (n - 1) × (n - 2) × ... × 2 × 1
0! = 1

1. C++ factorial using While loop

In this example, we shall make use of C++ While Loop, to find the factorial of a given number.

Factorial algorithm using a while loop

We shall implement the following factorial algorithm with while loop.

  1. Start.
  2. Read number to a variable n. [We have to find factorial for this number.]
  3. Initialize variable factorial with 1.
  4. Initialize loop control variable i with 1.
  5. Check if i is less than or equal to n. If the condition is false, go to step 8.
  6. Multiply factorial with i.
  7. Increment i. Go to step 5.
  8. Print factorial.
  9. Stop.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int n = 5;
   int factorial = 1;

   int i = 1;
   while (i <= n) {
      factorial *= i;
      i++;
   }

   cout << factorial;
}

Run the above C++ program, and you shall get the following output.

120

The variable factorial starts at 1. Each pass through the loop multiplies it by the next integer. For n = 5, the values become 1, 2, 6, 24, and finally 120.

2. C++ factorial program using For loop

In this example, we shall use C++ For Loop to find the factorial of a given number. The algorithm would be same as that of the one used in above example using while loop.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int main() {
   int n = 5;
   int factorial = 1;

   for (int i = 1; i <= n; i++)
      factorial *= i;

   cout << factorial;
}

Run the above program, and you shall get the following output for n=5.

5! = 120

The multiplication performed by the loop gives 120 for 5!. Note that the program shown above prints only the numeric value with cout << factorial;; to print the label 5! = as well, the cout statement would need to include that text.

3. C++ factorial using Recursion

Finding Factorial of a number is a classic example for recursion technique in any programming language.

In this example, we shall write a recursion function that helps us to find the factorial of a number.

The recursive rule is factorial(n) = n × factorial(n - 1). A base case is required to stop the recursive calls. Here, factorial(0) returns 1.

</>
Copy
factorial(0) = 1
factorial(n) = n × factorial(n - 1), for n > 0

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int factorial(int n);

int main() {
   cout << factorial(4) << endl;
   cout << factorial(6) << endl;
   cout << factorial(5) << endl;
   cout << factorial(0) << endl;
}

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

Following is the output to the above C++ program.

Output

24
720
120
1

For example, factorial(4) evaluates as 4 × factorial(3), then 4 × 3 × factorial(2), and continues until the call reaches the base case factorial(0).

4. C++ recursive factorial using Ternary Operator

When using recursion technique, instead of if else as in above example, you can also use C++ Ternary Operator.

In this example, we shall use recursion technique with ternary operator to make the code concise.

C++ Program

</>
Copy
#include <iostream>
using namespace std;

int factorial(int n);

int main() {
   cout << factorial(4) << endl;
}

int factorial(int n) {
   return (n==0)? 1: n * factorial(n - 1);
}

The program calls factorial(4). The ternary expression returns 1 when n == 0; otherwise, it returns n * factorial(n - 1).

Output

24

C++ factorial with user input and negative-number validation

The earlier programs use fixed values for n. In a program that reads input from the user, check for a negative value before starting the factorial calculation.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    int n;
    unsigned long long factorial = 1;

    cout << "Enter a non-negative integer: ";
    cin >> n;

    if (n < 0) {
        cout << "Factorial is not defined for negative integers.";
        return 0;
    }

    for (int i = 2; i <= n; ++i) {
        factorial *= i;
    }

    cout << n << "! = " << factorial;
    return 0;
}

For an input of 5, the program prints the following result.

Enter a non-negative integer: 5
5! = 120

Integer overflow when calculating factorial in C++

Factorial values grow very quickly. An int can overflow even for relatively small inputs, so it is unsuitable for larger factorials. Using unsigned long long extends the range, but it is still finite. On a system where unsigned long long is 64 bits, 20! fits in the type while 21! does not.

If your program must handle inputs beyond the built-in integer range, use an arbitrary-precision integer library or implement a big-integer representation instead of relying on a wider built-in type.

Is there a built-in factorial function in C++?

The C++ standard library does not provide a general integer factorial() function. For integer factorials, a loop or recursive function is the usual direct approach. The <cmath> function std::tgamma is related through the identity n! = tgamma(n + 1) for suitable values, but it returns a floating-point result and is not a replacement for exact integer factorial calculations.

For loop or recursion for factorial in C++?

Both approaches express the same factorial definition. A loop is usually simpler for an integer factorial because it uses constant call-stack space. Recursion can be useful when learning recursive functions, but each recursive call adds a stack frame until the base case is reached.

C++ factorial summary

In this C++ Tutorial, we learned how to calculate factorial for non-negative integers using while and for loops, recursion, and a ternary expression. We also covered the 0! = 1 base case, input validation for negative integers, the lack of a standard integer factorial function, and integer-overflow limits.

C++ factorial editorial QA checklist

  • Verify that every factorial example treats 0! as 1.
  • Verify that negative integers are not presented as valid inputs to the integer factorial function.
  • Check that the stated output matches the actual cout expression in each newly added program.
  • Check that recursive examples include a reachable base case before the recursive call continues.
  • Check the integer type used before adding examples with factorial values larger than the type can represent.