C++ Program To Find Factorial Of A Number Using Iteration

A mathematical procedure known as a factorial that determines the product of all positive integers from 1 to a specified number "n" . In this article, you will see how to find factorial of a number using iteration in C++.

Understanding Factorial:

The product of all positive numbers less than or equal to a non-negative integer 'n' is its factorial, represented as 'n! '. It is frequently utilized in many combinatorial and mathematical computations. The base case for the factorial function is the factorial of 0, which has a definition of 1.

The following simple method can be used to iteratively compute the factorial of a given number:

  • Set the initial value of a variable, usually called "factorial" , to 1 to store the outcome.
  • Make an iteration loop that goes from 1 to 'n' , where 'n' is the number you wish to get the factorial for.
  • Multiply the current value of "factorial" by the loop counter for each iteration of the loop.
  • The factorial of 'n' will be in the 'factorial' variable once the loop has finished.
  • Example:

Let us take a C++ program to Find factorial of a Number using Iteration:

Example

#include <iostream>
using namespace std;
// Function to calculate factorial using iteration
unsigned long long calculateFactorial(int n) {
 if (n < 0) {
 // Factorial is not defined for negative numbers
 return 0;
 }
 unsigned long long factorial = 1;
 for (int i = 1; i <= n; ++i) {
 factorial *= i;
 }
 return factorial;
}
int main() {
 int n;
 // Input
 cout << "Enter a non-negative integer to calculate its factorial: ";
 cin >> n;
 // Check for negative input
 if (n < 0) 
 {
 cout << "Factorial is not defined for negative numbers." << endl;
 } else {
 // Calculate the factorial and display the result
 unsigned long long result = calculateFactorial(n);
 cout << "The factorial of " << n << " is " << result << endl;
 }
 return 0;
}

Output:

Input Required

This code uses input(). Please provide values below: