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++
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++
#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++
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++
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.