Table of contents
1.
Introduction
2.
Factorial Program Using a Loop in C++
2.1.
C++
3.
Factorial Program Using a While Loop in C++
3.1.
Example Code
3.2.
C++
4.
Factorial Program Using Recursion in C++
4.1.
C++
5.
Factorial Program Using Ternary Operator
5.1.
Example Code
5.2.
C++
6.
Factorial Program Using Call By Reference
6.1.
C++
7.
Frequently Asked Questions
7.1.
What is the largest number I can calculate the factorial for using these methods in C++?
7.2.
Can these factorial functions handle negative input?
7.3.
What is the symbol for factorial in C++?
7.4.
Does C++ have a built-in factorial function?
7.5.
What is the formula of factorial in C++?
8.
Conclusion
Last Updated: Jan 7, 2025
Medium

Factorial Program in C++

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Factorial is a mathematical operation that calculates the product of all positive integers less than or equal to a given number. A factorial of a non-negative integer, n, is the product of all positive integers less than or equal to n. For example, the factorial of 5 is 120. This basic but powerful concept is crucial in areas such as permutations & combinations, algorithms, & statistical calculations. 

Factorial Program in C++

In programming, factorial programs are commonly used to find the factorial value of a number. In this article, we will learn how to implement a factorial program in C++ using both loops & recursion. 

Factorial Program Using a Loop in C++

To compute the factorial of a number using a loop in C++, we utilize a simple for loop that multiplies numbers successively. This approach is straightforward & effective for calculating factorials of smaller numbers. Here’s how you can do it:

First, you need to include the standard input-output library in your C++ program, which is done by adding #include <iostream> at the beginning of your code. This allows you to use input & output operations in your program.

Here's a basic example of calculating the factorial of a number using a loop:

  • C++

C++

#include <iostream>
using namespace std;

int main() {
int n, factorial = 1;
cout << "Enter a positive integer: ";
cin >> n;

for(int i = 1; i <= n; ++i) {
factorial *= i; // Multiply factorial by i each iteration
}

cout << "Factorial of " << n << " = " << factorial << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Enter a positive integer: 5
Factorial of 5 = 120


In this code:

  • We start by declaring an integer n that will store the number for which we want to find the factorial.
     
  • We also declare factorial & initialize it to 1. This variable will store the result of the factorial.
     
  • The program then prompts the user to enter a positive integer.
     
  • It uses a for loop where i starts from 1 & increments by 1 until it reaches n. In each iteration of the loop, factorial is multiplied by i.
     
  • After the loop completes, the factorial of the number is printed.

 

This loop-based method is simple & efficient for inputs that are not excessively large, as the value of factorial grows very quickly & can exceed the storage capacity of standard data types for large inputs.

Factorial Program Using a While Loop in C++

The factorial of a number is the product of all positive integers from 1 to that number. For example, the factorial of 5 (written as 5!) is 1 * 2 * 3 * 4 * 5 = 120.

Below is an explanation of how to calculate the factorial using a while loop in Java:

  • Initialize Variables
    You start by defining two variables: one to hold the number whose factorial is being calculated, and the other to store the result (which begins as 1 because multiplying by 0 would invalidate the calculation).
     
  • While Loop Condition
    The loop runs as long as the number is greater than 0. With each iteration, the loop multiplies the current result by the number and then decreases the number by 1.
     
  • Decrement Operation
    After each iteration, the number is decremented by 1 so that eventually, it becomes 0 and the loop terminates.
     
  • Result Output
    After the loop finishes, the result variable contains the factorial of the original number, and it is printed to the console.

Example Code

  • C++

C++

public class FactorialWhile {
public static void main(String[] args) {
int number = 5; // The number whose factorial we want to calculate
int factorial = 1; // Initialize the result to 1

while (number > 0) {
factorial *= number; // Multiply result by the current number
number--; // Decrease the number by 1 in each iteration
}

System.out.println("Factorial: " + factorial); // Output the result
}
}
You can also try this code with Online C++ Compiler
Run Code


Output

Factorial: 120

Factorial Program Using Recursion in C++

Recursion is a programming technique where a function calls itself to solve a problem. In C++, we can use recursion to calculate the factorial of a number in a clean & elegant way. This method is especially useful because it simplifies the code and makes it easy to understand, although it can be less efficient for very large numbers due to the deeper call stack.

Here’s how you can create a factorial program using recursion in C++:

First, as with any C++ program, we start by including the input-output stream header that allows us to use input & output functions in our program:

#include <iostream>
using namespace std;


Next, we define a recursive function that will compute the factorial:

int factorial(int n) {
    if (n == 0)  // Base case: factorial of 0 is 1
        return 1;
    else
        return n * factorial(n - 1);  // Recursive call
}


In this function:

  • We start by checking if n is 0. If so, the function returns 1 because the factorial of 0 is defined as 1.
     
  • If n is not 0, the function calls itself with n-1, multiplying the result by n. This continues until n reaches 0.
     

Here's how you can use this function in your main program to calculate the factorial of a given number:

  • C++

C++

#include <iostream>
using namespace std;

int main() {

   int n;

   cout << "Enter a positive integer: ";

   cin >> n;

   cout << "Factorial of " << n << " = " << factorial(n) << endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Enter a positive integer: 5
Factorial of 5 = 120


In the main function:

  • The program prompts the user to enter a positive integer.
     
  • It then calls the factorial function using the entered number & displays the result.
     
  • This recursive method is quite intuitive because each function call makes a smaller problem until it reaches the simplest problem, which is calculating the factorial of 0.
     

Recursion can be more informative & easier to write, especially for mathematical functions like factorials, but it's important to understand that it uses more memory due to function calls. For very large numbers, it might lead to a stack overflow error if the recursion goes too deep.

Factorial Program Using Ternary Operator

A ternary operator is a shorthand form of the if-else statement in Java. You can use it to calculate the factorial of a number recursively.

The ternary operator simplifies the recursion logic. The factorial of a number n is calculated as n * factorial(n-1) until n becomes 1, where the recursion stops. The ternary operator checks whether n is greater than 1, and if so, multiplies n by the factorial of n-1. If n is 1, the factorial is 1, which is the base case for the recursion.

Example Code

  • C++

C++

public class FactorialTernary {
public static void main(String[] args) {
int number = 5;
int result = factorial(number);
System.out.println("Factorial: " + result);
}

static int factorial(int n) {
// Ternary operator for factorial
return (n == 1) ? 1 : n * factorial(n - 1);
}
}
You can also try this code with Online C++ Compiler
Run Code


Output

Factorial: 120

Factorial Program Using Call By Reference

In call by reference, a method receives the reference to the actual memory address of the argument, allowing changes made in the called method to affect the original variable. However, Java does not support direct call-by-reference. Instead, it uses call-by-value, but when using objects, the value passed is the reference to the object. So we can simulate call-by-reference by using an object.

By wrapping the integer in an object (like an array or a class), we can pass this object to a method that calculates the factorial. The method modifies the object’s value, effectively simulating call-by-reference.

  • C++

C++

public class FactorialCallByReference {
public static void main(String[] args) {
int[] number = {5}; // Wrapping number in an array
factorial(number); // Call by reference-like behavior using array
System.out.println("Factorial: " + number[0]);
}

static void factorial(int[] num) {
int result = 1;
for (int i = 1; i <= num[0]; i++) {
result *= i;
}
num[0] = result; // Modify the original array value
}
}
You can also try this code with Online C++ Compiler
Run Code


Output

Factorial: 120

Frequently Asked Questions

What is the largest number I can calculate the factorial for using these methods in C++?

The largest number you can reliably calculate the factorial for depends on the data type used to store the result. For data types like int or long, you can typically go up to 12 or 20, respectively, before encountering overflow. Using unsigned long long extends this range slightly further.

Can these factorial functions handle negative input?

No, factorials are only defined for non-negative integers. Both programs assume positive input. If negative input handling is needed, you should modify the program to return an error message or handle the input differently.

What is the symbol for factorial in C++?

In C++, there is no specific symbol for factorial like in mathematics. Instead, you typically implement factorial using a function that multiplies a series of descending positive integers or by using recursion.

Does C++ have a built-in factorial function?

No, C++ does not have a built-in factorial function. To calculate factorials, you need to either write your own function using loops or recursion, or use a library like <boost> that provides advanced mathematical functions.

What is the formula of factorial in C++?

The formula for calculating a factorial in C++ is typically written as a function that multiplies numbers in descending order. For example, n! (factorial of n) is calculated as n * (n-1) * (n-2) * ... * 1.

Conclusion

In this article, we have learned how to calculate the factorial of a number using two different methods in C++: loops & recursion. The loop method is straightforward & efficient for smaller numbers, while recursion offers a clear & elegant approach, though it can be less efficient for very large numbers due to deeper call stacks. 

Live masterclass