News

Tuesday, April 19, 2022

Factorial in C++ Iterative Method





Introduction:

Working Principle:

Example:

Code:

The source code of factorial using iterative method is below:




// Factorial of any number = 1*2*3*...*n
#include <iostream>
using namespace std;

int factorial(int num) 
{
    int result = 1;
	if (num== 0) 
	{
        result = 1 ;
    }
	for (int i=1; i<=num; i++) 
	{
        
		result = result * i ;
    }
    return result;
}

int main() 
{
    int num;

    cout << "Enter a non-negative number: ";
    cin >> num;
    cout << "Factorial of " << num << " = " << factorial(num);

}



Output:




No comments:

Post a Comment