Recursion Essentials:
There are some points one must know to implement good and successful recursive programs, without these points one can’t be able to write error-free code for a recursive problem. These points are as follows:
1. There must be a terminating condition for the problem, which we want to solve with recursion.
2. There must be an if condition in the recursive routine, this if clause specifies the terminating condition for the recursion.
3. Each time a new recursive call is made, new memory space is allocated to each automatic and register variables used in the program.
Disadvantages of recursion:
1. It consumes more memory space because recursive calls along with automatic variables are stored in the stack and each time the call is made a new memory is allocated.
2. The computer may run out of memory (an error is generated) if the recursive call is not checked.
3. It is not efficient in terms of speed and execution time.
4. If proper precautions are not taken , recursion may result in non terminating iterations.
5. Recursion is not advocated when the problem can be solved through iterations.
6. Recursion may be treated as a software tool to be applied carefully and selectively. Cannot be and should not be used for normal programs.
Difference between Iteration and Recursion
Iteration | Recursion |
It is a process of executing a statement or a set of statements repeatedly until some specified condition is true. | Recursion is the technique of defining anything in terms of itself. |
Iteration involves four(4) clear-cut steps initialization, condition, execution, and updation. | There must be an exclusive if statement inside the recursive function, specifying the stopping condition. |
Any recursive problem can be solved iteratively. | Not all problems have a recursive solution. |
The iterative counterpart of a problem is more efficient in terms of memory utilization and execution speed. | Recursion is generally a worse option to go for a simple problems, or problems not recursive in nature. |