Recursion vs. Iteration
In this tutorial, we will understand the difference between a recursive program and an iterative program. So, let’s dive in.
In this tutorial, we will understand the difference between a recursive program and an iterative program. So, let’s dive in.
If you observe closely, the concept of recursion is repeating something multiple times until some condition is true. In a recursive procedure, a function keeps calling itself until the base case is reached which acts as the termination condition. The similar concept is observed in iterative programs too. A piece of code is repeated until some condition is satisfied. Even both the concepts are so interrelated that one can convert any iterative program to its equivalent recursive program, and vice versa.
For example, we already saw the recursive program to find the factorial of a number. The equivalent iterative program is as follows:
#include <stdio.h>
int fact(int n) {
int res = 1;
for (int i=1; i<=n; i++) {
res *= i;
}
return res;
}
int main() {
printf("%d", fact(5));
return 0;
}
But, why do we choose one over the other? Which one is better?
The only person who can answer these questions is YOU. Recursive functions use more stack space compared to their iterative counterpart because there are multiple function calls involved in a recursive procedure. On the other hand, the iterative programs do not consume a lot of memory space because the functions are not called repeatedly. But iterative programs may not feel natural. The most beautiful thing about recursion is its structure. Even a novice can tell what’s going on in the program. For example, the recursive program to find factorial of a number is simple to understand because one can observe that the formula to find factorial is beautifully adopted in the procedure. Same thing can be observed in the Fibonacci program too. But their equivalent interative programs need a little more attention to understand what’s going on.
So, one can make the decision based on what they want. If the requirement is to use less memory space while solving the problem, and if the application you are building is performance critical, then you can go with iteration. If you want your programs to be clear and manageable without worrying about the memory space requirements, then you can go with recursion. It’s just a matter of choice.
One thing to note is that not all problems can naturally be solved through recursion. There are some problems that, if solved recursively, can make the program a bit complicated. So, in these situations, you can choose to write the iterative version of the problem.
Leave a comment