Horje
C++ Program to Find Factorial of a Number Using Iteration

Factorial of a number n is the product of all integers from 1 to n. In this article, we will learn how to find the factorial of a number using iteration in C++.

Example

Input: 5

Output: Factorial of 5 is 120

Factorial of Number Using Iteration in C++

To find the factorial of a given number we can use loops. First, initialize the factorial variable to 1, and then iterate using a loop from 1 to n, and in each iteration, multiply the iteration number with factorial and update the factorial with the new value.

C++ Program to Find Factorial Using Iteration

The below program shows how we can find the factorial of a given number using the iteration method.

C++

// C++ program to find factorial of a number using iteration
#include <iostream>
using namespace std;
  
int main()
{
    // number n whose factorial needs to be find
    int n = 5;
    // initialize fact variable with 1
    int fact = 1;
  
    // loop calculating factorial
    for (int i = 1; i <= n; i++) {
        fact = fact * i;
    }
    // print the factorial of n
    cout << "Factorial of " << n << " is " << fact << endl;
  
    return 0;
}

Output

Factorial of 5 is 120



Time Complexity: O(N), where N is the given number
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Push All Elements from a Vector to a Queue in C++? How to Push All Elements from a Vector to a Queue in C++?
How to Update Value of a Key in Map in C++? How to Update Value of a Key in Map in C++?
How to Reverse a Vector Using a Stack in C++? How to Reverse a Vector Using a Stack in C++?
How to Insert a Pair in Multimap in C++? How to Insert a Pair in Multimap in C++?
How to Take Operator as Input in C++? How to Take Operator as Input in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14