Last Updated on August 25, 2023 by Mayank Dham

At the core of programming lies the ability to break down complex problems into smaller, more manageable pieces. One fundamental concept that illustrates this approach is the calculation of factorials. A factorial represents the product of all positive integers up to a given number. This seemingly simple mathematical operation forms the building block for a multitude of applications across various domains, including combinatorics, probability, and more.

In the realm of programming, understanding how to compute factorials not only demonstrates mastery of basic mathematical operations but also provides insights into recursion, iterative constructs, and problem-solving strategies. By implementing a factorial program in C++, you’ll not only gain a practical tool for solving specific mathematical tasks but also cultivate a deeper appreciation for the elegance of computational thinking.

## What is a Factorial Program in C++?

Calculation of factorial numbers is simple mathematics. The factorial of a number is 1 * 2 * 3 * … * number.

For Example, factorial 6 is

6! = 1 * 2 * 3 * 4 * 5 * 6 = 720.

## Explanation of Program

Let’s create a factorial program using recursive functions. Until the value is not equal to zero, the recursive function will call itself.

Factorial can be calculated using the following recursive formula:

n! = n * (n – 1)!

n! = 1 if n = 0 or n = 1

### Approach 1: Factorial Function in C++ (Using Recursion)

- Build a recursive function factorial which takes an integer n as a parameter and returns an unsigned integer as the output.
- If n ==0 or n==1, then return 1.
- Else return n * factorial(n – 1).

**Code Implementation (Using Recursion)**

#include <iostream> using namespace std; unsigned int factorial(unsigned int n) { if (n == 0 || n == 1) return 1; return n * factorial(n - 1); } int main() { int num = 5; cout << "Factorial of " << num << " is: " << factorial(num) << endl; return 0; }

**Time complexity:** O(n) will be the time complexity for implementing a factorial program in C++ using recursion.

**Auxiliary Space:** O(n) will be the space complexity for implementing a factorial program in C++ using recursion.

### Approach 2: Factorial Function in C++ (Using For loop)

Follow the steps to solve the problem:

- Using a for loop, we will write a program for finding the factorial of a number.
- An integer variable with a value of 1 will be used in the program.
- With each iteration, the value will increase by 1 until it equals the value entered by the user.
- The factorial of the number entered by the user will be the final value in the fact variable.

**Code Implementation (Using For Loop)**

#include <iostream> using namespace std; unsigned int factorial(unsigned int n) { int res = 1, i; for (i = 2; i <= n; i++) res *= i; return res; } int main() { int num = 5; cout << "Factorial of " << num << " is " << factorial(num) << endl; return 0; }

**Time complexity:** O(n) will be the time complexity for implementing a factorial program in C++ using a for loop.

**Auxiliary Space:** O(1) will be the space complexity for implementing a factorial program in C++ using a for loop.

**Approach 3: Factorial Function in C++ (Using While Loop)**

In this approach, we will see how we can use the while loop for implementing the factorial of a number.

**Code Implementation (Using While Loop)**

#include <iostream> using namespace std; unsigned int factorial(unsigned int n) { if(n == 0) return 1; int i = n, fact = 1; while (n / i != n) { fact = fact * i; i--; } return fact; } int main() { int num = 5; cout << "Factorial of " << num << " is " << factorial(num) << endl; return 0; }

**Time complexity:** O(n) will be the time complexity for implementing a factorial program in C++ using a while loop.

**Auxiliary Space:** O(1) will be the space complexity for implementing a factorial program in C++ using a while loop.

**Approach 4: Factorial Function in C++ (Using Ternary Operator)**

A ternary operator can be thought of as a shorthand for an if…else statement. The conditions are provided, along with statements to be executed based on them. Here’s the program for factorial using a ternary operator.

**Code Implementation (Using Ternary Operators)**

#include <iostream> using namespace std; int factorial(int n) { return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } int main() { int num = 5; cout << "Factorial of " << num << " is "<< factorial(num); return 0; }

**Time complexity:** O(n) will be the time complexity for implementing a factorial program in C++ using a ternary operator for the recursive approach.

**Auxiliary Space:** O(n) will be the space complexity for implementing a factorial program in C++ using a ternary operator for the recursive approach.

**Tips**

Various service based companies like TCS, Wipro, Accenture and Capgemini have asked for a factorial program for their technical interviews.

**Conclusion**

Through our exploration of calculating Factorial Program in CPP, we’ve uncovered a fundamental mathematical concept that transcends mere computation. The process of breaking down complex problems into manageable pieces, a skill showcased through factorial calculations, embodies the essence of programming itself. By mastering the techniques to compute factorials, you’ve not only acquired a powerful tool for solving mathematical challenges but also developed a mindset for tackling broader programming tasks.

From iterative loops to recursive functions, the diverse methods we’ve discussed the factorial function in C++ offer insights into different programming paradigms. Whether you’re striving for efficient code or exploring the elegance of recursive solutions, the world of factorials serves as an excellent training ground for honing your programming skills and deepening your understanding of algorithmic thinking.

## FAQ related to factorial function in C++

Here are some FAQs related to factorial program in cpp.

**1. What are some practical applications of factorials in programming?**

Factorials are used in various scenarios, such as calculating permutations, combinations, and probabilities in statistics, generating series in mathematics, and solving certain types of counting problems in computer science and engineering.

**2. Why are factorials important in programming?**

Factorials have applications in combinatorics, probability, permutations, and more. Additionally, calculating factorials can help programmers develop problem-solving skills and explore different programming techniques.

**3. What is the difference between an iterative and a recursive approach to calculating factorials?**

An iterative approach uses loops to repeatedly multiply numbers, while a recursive approach breaks down the problem by calculating the factorial of smaller values and building up to the desired value. Both methods have their advantages and use cases.

**4. Can factorials be negative or non-integer values?**

The factorial operation is defined only for non-negative integers. Negative or non-integer values don’t have factorial definitions in conventional mathematics.

**5. Are there limits to the size of the factorial value that can be calculated?**

Yes, there are limits imposed by the data type used to store the factorial value. Factorials grow rapidly, and for large values of "n," the result may exceed the range of the data type.

**6. Which method is more efficient: iterative or recursive?**

In general, iterative methods tend to be more efficient for calculating factorials due to the overhead of function calls in recursive solutions. However, recursive approaches offer a clearer reflection of the mathematical definition.

**Other C++ Programs**

C++ Program to Add Two Numbers

C++ Program to Reverse a Number

C++ program for heap sort

Bubble Sort in C++ with Program Code and Example

Hello world program in C++

Prime Number Program in C++