RECURSION – ITERATION

Recursion refers to a situation where a function calls itself again and again until some base condition is not reached.

A program is called recursive when an entity calls itself.

It is comparatively slower because before each function call the current state of function is stored in stack.

Memory usage is more as stack is used to store the current function state.

Size of code is comparatively smaller in recursion.

int factorialUsingRecursion(int n)

{

if (n == 0)

return 1;

// recursion call

return n * factorialUsingRecursion(n – 1);

}

Iteration refers to a situation where some statements are executed again and again using loops until some condition is true.

A program is call iterative when there is a loop (or repetition).

Its execution is faster because it doesn’t use stack.

Memory usage is less as it doesn’t use stack.

Iteration makes the code size bigger.

int factorialUsingIteration(int n)

{

int res = 1, i;

// using iteration

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

res *= i;

return res;

}

Advantage: Recursion makes the complex programs simpler and easy to understand by making the code reduced than Iteration.
Disadvantage: Recursion occupies more memory and a slow process than iteration

This entry was posted in Basic. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *