Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Apr 25, 2024
Difficulty: Medium

Factorial Program in C++

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

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

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;
}

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Factorial Program Using Recursion

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;

}

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.

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.

Why does the recursive method use more memory than the loop method?

The recursive method uses more memory because each function call consumes stack space. Each recursive call adds a new layer to the stack, storing variables & return addresses, which does not occur in a loop-based approach.

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.

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. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Topics covered
1.
Introduction
2.
Factorial Program Using a Loop
2.1.
C++
3.
Factorial Program Using Recursion
3.1.
C++
4.
Frequently Asked Questions
4.1.
What is the largest number I can calculate the factorial for using these methods in C++?
4.2.
Why does the recursive method use more memory than the loop method?
4.3.
Can these factorial functions handle negative input?
5.
Conclusion