Recursvie to Iterative function

Recursive to Iterative function

The program below outputs the factorial of 5 by using a recursive function.

Change the factorial function to use a for loop instead.

#include <iostream>

unsigned long long factorial(int N)
{
    if (N == 1) 
        return 1; 
 
    return N * factorial(N-1);
}

int main()
{
    std::cout << "Factorial of 5: " << factorial(5) << "\n";
}

Answer

#include <iostream>

unsigned long long factorial(int N)
{
    unsigned long long result = 1;
    for (int i = 1; i <= N; i++)
    {
        result *= i;
    }
    return result;
}

int main()
{
    std::cout << "Factorial of 15: " << factorial(15) << "\n";
}
Questions