Recursion vs Iteration
Learn how to calculate the factorial of a number iteratively.
We'll cover the following...
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 functionint factorial(int n) {int fact = 1;if (n == 0) {fact = 1;}for (int counter = 1; counter <= n; counter++) {fact = fact * counter;}return fact;}// main functionint main() {int n = 5;int result;// Call factorial function in main and store the returned value in resultresult = factorial(n);// Prints value of resultcout << "Factorial of " << n << " = " << result;return 0;}
Differences
The following are the differences between recursion and iteration:
-
In the computer language, iteration ...