Difference between Recursion and Iteration

In this tutorial you will learn about difference between recursion and iteration with example.

Both recursion and iteration are used for executing some instructions repeatedly until some condition is true. A same problem can be solved with recursion as well as iteration but still there are several differences in their working and performance that I have mentioned below.

Difference between Recursion and Iteration

  Recursion Iteration
Definition Recursion refers to a situation where a function calls itself again and again until some base condition is not reached. Iteration refers to a situation where some statements are executed again and again using loops until some condition is true.
Performance It is comparatively slower because before each function call the current state of function is stored in stack. After the return statement the previous function state is again restored from stack. Its execution is faster because it doesn’t use stack.
Memory Memory usage is more as stack is used to store the current function state. Memory usage is less as it doesn’t use stack.
Code Size Size of code is comparatively smaller in recursion. Iteration makes the code size bigger.

Lets write the implementation of finding factorial of number using recursion as well as iteration.

Recursion Example

Below is the C program to find factorial of a number using recursion.

#include <stdio.h>

int factorial(int n){
    if(n == 0)
        return 1;
    else
        return n * factorial(n-1);
}

int main() {
    printf("Factorial for 5 is %d", factorial(5));

    return 0;
}

Iteration Example

Below is the C program to find factorial of a number using iteration.

#include <stdio.h>

int main() {
    int i, n = 5, fac = 1;

    for(i = 1; i <= n; ++i)
        fac = fac * i;

    printf("Factorial for 5 is %d", fac);

    return 0;
}

Comment below if you have any queries regarding above tutorial for recursion vs iteration.

Leave a Comment

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