Recursion vs Iteration

Learn how to calculate the factorial of a number iteratively.

Recursive solution

We can implement a recursive solution iteratively. Let’s write a program to calculate the factorial of a number using a loop. In the iterative solution, we are not calling the same problem with a simpler version; instead, we are using the counter variable and we keep incrementing it until the given condition is true.

Press + to interact
#include <iostream>
using namespace std;
// Iterative factorial function
int factorial(int n) {
int fact = 1;
if (n == 0) {
fact = 1;
}
for (int counter = 1; counter <= n; counter++) {
fact = fact * counter;
}
return fact;
}
// main function
int main() {
int n = 5;
int result;
// Call factorial function in main and store the returned value in result
result = factorial(n);
// Prints value of result
cout << "Factorial of " << n << " = " << result;
return 0;
}

Differences

The following are the differences between recursion and iteration:

  • In the computer language, iteration ...