34.1k views
0 votes
Write both an iterative and recursive solution for the factorial
problem.

1 Answer

3 votes

Answer:

Step-by-step explanation:

Recursive:

C++ program to find factorial of given number

#include <iostream>

using namespace std;

unsigned int factorial(unsigned int n)

{

if (n == 0)

return 1;

return n * factorial(n - 1);

}

// Driver code

int main()

{

int num = 5;

cout << "Factorial of "

<< num << " is " << factorial(num) << endl;

return 0;

Iterative:

// C++ program for factorial of a number

#include <iostream>

using namespace std;

unsigned int factorial(unsigned int n)

{

int res = 1, i;

for (i = 2; i <= n; i++)

res *= i;

return res;

}

// Driver code

int main()

{

int num = 5;

cout << "Factorial of "

<< num << " is "

<< factorial(num) << endl;

return 0;

}

User Godice
by
5.9k points