The Wayback Machine - https://web.archive.org/web/20240717180319/https://www.geeksforgeeks.org/difference-between-recursion-and-iteration/
Open In App

Difference between Recursion and Iteration

Last Updated : 22 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A program is called recursive when an entity calls itself. A program is called iterative when there is a loop (or repetition).

Example: Program to find the factorial of a number 

C




// C program to find factorial of given number
#include <stdio.h>
 
// ----- Recursion -----
// method to find factorial of given number
int factorialUsingRecursion(int n)
{
    if (n == 0)
        return 1;
 
    // recursion call
    return n * factorialUsingRecursion(n - 1);
}
 
// ----- Iteration -----
// Method to find the factorial of a given number
int factorialUsingIteration(int n)
{
    int res = 1, i;
 
    // using iteration
    for (i = 2; i <= n; i++)
        res *= i;
 
    return res;
}
 
// Driver method
int main()
{
    int num = 5;
    printf("Factorial of %d using Recursion is: %d\n", num,
           factorialUsingRecursion(5));
 
    printf("Factorial of %d using Iteration is: %d", num,
           factorialUsingIteration(5));
 
    return 0;
}
 
// This code is contributed by mits


C++




// C++ program to find factorial of given number
#include<bits/stdc++.h>
using namespace std;
 
// ----- Recursion -----
// method to find factorial of given number
int factorialUsingRecursion(int n)
{
    if (n == 0)
        return 1;
 
    // recursion call
    return n * factorialUsingRecursion(n - 1);
}
 
// ----- Iteration -----
// Method to find the factorial of a given number
int factorialUsingIteration(int n)
{
    int res = 1, i;
 
    // using iteration
    for (i = 2; i <= n; i++)
        res *= i;
 
    return res;
}
 
// Driver method
int main()
{
    int num = 5;
    cout << "Factorial of " << num <<
            " using Recursion is: " <<
            factorialUsingRecursion(5) << endl;
 
    cout << "Factorial of " << num <<
            " using Iteration is: " <<
            factorialUsingIteration(5);
 
    return 0;
}
 
// This code is contributed by mits


Java




// Java program to find factorial of given number
class GFG {
 
    // ----- Recursion -----
    // method to find factorial of given number
    static int factorialUsingRecursion(int n)
    {
        if (n == 0)
            return 1;
 
        // recursion call
        return n * factorialUsingRecursion(n - 1);
    }
 
    // ----- Iteration -----
    // Method to find the factorial of a given number
    static int factorialUsingIteration(int n)
    {
        int res = 1, i;
 
        // using iteration
        for (i = 2; i <= n; i++)
            res *= i;
 
        return res;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        int num = 5;
        System.out.println("Factorial of " + num
                           + " using Recursion is: "
                           + factorialUsingRecursion(5));
 
        System.out.println("Factorial of " + num
                           + " using Iteration is: "
                           + factorialUsingIteration(5));
    }
}


Python3




# Python3 program to find factorial of given number
 
# ----- Recursion -----
# method to find factorial of given number
def factorialUsingRecursion(n):
    if (n == 0):
        return 1;
 
    # recursion call
    return n * factorialUsingRecursion(n - 1);
 
# ----- Iteration -----
# Method to find the factorial of a given number
def factorialUsingIteration(n):
    res = 1;
 
    # using iteration
    for i in range(2, n + 1):
        res *= i;
 
    return res;
 
# Driver method
num = 5;
print("Factorial of",num,"using Recursion is:",
                    factorialUsingRecursion(5));
 
print("Factorial of",num,"using Iteration is:",
                    factorialUsingIteration(5));
     
# This code is contributed by mits


C#




// C# program to find factorial of
// given number
using System;
 
class GFG
{
 
    // ----- Recursion -----
    // method to find factorial of
    // given number
    static int factorialUsingRecursion(int n)
    {
        if (n == 0)
            return 1;
 
        // recursion call
        return n * factorialUsingRecursion(n - 1);
    }
 
    // ----- Iteration -----
    // Method to find the factorial of
    // a given number
    static int factorialUsingIteration(int n)
    {
        int res = 1, i;
 
        // using iteration
        for (i = 2; i <= n; i++)
            res *= i;
 
        return res;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int num = 5;
        Console.WriteLine("Factorial of " + num +
                          " using Recursion is: " +
                          factorialUsingRecursion(5));
 
        Console.WriteLine("Factorial of " + num +
                          " using Iteration is: " +
                          factorialUsingIteration(5));
    }
}
 
// This code has been contributed by Rajput-Ji


PHP




<?php
// PHP program to find factorial of given number
 
    // ----- Recursion -----
    // method to find factorial of given number
    function factorialUsingRecursion($n)
    {
        if ($n == 0)
            return 1;
 
        // recursion call
        return $n * factorialUsingRecursion($n - 1);
    }
 
    // ----- Iteration -----
    // Method to find the factorial of a given number
    function factorialUsingIteration($n)
    {
        $res = 1;
 
        // using iteration
        for ($i = 2; $i <= $n; $i++)
            $res *= $i;
 
        return $res;
    }
 
    // Driver method
        $num = 5;
        print("Factorial of ".$num." using Recursion is: ".
                            factorialUsingRecursion(5)."\n");
 
        print("Factorial of ".$num." using Iteration is: ".
                            factorialUsingIteration(5)."\n");
     
// This code is contributed by mits
?>


Javascript




<script>
 
// JavaScript program to find factorial of given number
// ----- Recursion -----
// method to find factorial of given number
function factorialUsingRecursion(n)
    {
        if (n == 0)
            return 1;
 
        // recursion call
        return n * factorialUsingRecursion(n - 1);
    }
 
    // ----- Iteration -----
    // Method to find the factorial of a given number
    function factorialUsingIteration(n)
    {
        var res = 1, i;
 
        // using iteration
        for (i = 2; i <= n; i++)
            res *= i;
 
        return res;
    }
 
    // Driver method
        var num = 5;
        document.write("Factorial of " + num
                           + " using Recursion is: "
                           + factorialUsingRecursion(5)+"<br>");
 
        document.write("Factorial of " + num
                           + " using Iteration is: "
                           + factorialUsingIteration(5));
     
// This code is contributed by shivanisinghss2110
</script>


Output

Factorial of 5 using Recursion is: 120
Factorial of 5 using Iteration is: 120

Time and Space Complexity

Time Complexity: O(2n)
Auxiliary Space: O(n)

Below is a detailed explanation to illustrate the difference between the two using the above example. We will study the different aspects of both recursive and iterative approaches.

1. Time Complexity

The time complexity of the method may vary depending on whether the algorithm is implemented using recursion or iteration.

  • Recursion: The time complexity of recursion can be found by finding the value of the nth recursive call in terms of the previous calls. Thus, finding the destination case in terms of the base case, and solving in terms of the base case gives us an idea of the time complexity of recursive equations. Please see Solving Recurrences for more details.
     
  • Iteration: The time complexity of iteration can be found by finding the number of cycles being repeated inside the loop. 

2. Usage

Usage of either of these techniques is a trade-off between time complexity and size of code. If time complexity is the point of focus, and the number of recursive calls would be large, it is better to use iteration. However, if time complexity is not an issue and shortness of code is, recursion would be the way to go.

  • Recursion: Recursion involves calling the same function again, and hence, has a very small length of code. However, as we saw in the analysis, the time complexity of recursion can get to be exponential when there are a considerable number of recursive calls. Hence, usage of recursion is advantageous in shorter code, but higher time complexity.
     
  • Iteration: Iteration is the repetition of a block of code. This involves a larger size of code, but the time complexity is generally lesser than it is for recursion. 

3. Overhead

Recursion has a large amount of Overhead as compared to Iteration. 

  • Recursion: Recursion has the overhead of repeated function calls, that is due to the repetitive calling of the same function, the time complexity of the code increases manyfold.
     
  • Iteration: Iteration does not involve any such overhead. 

4. Infinite Repetition

Infinite Repetition in recursion can lead to a CPU crash but in iteration, it will stop when memory is exhausted. 

  • Recursion: In Recursion, Infinite recursive calls may occur due to some mistake in specifying the base condition, which on never becoming false, keeps calling the function, which may lead to a system CPU crash.
     
  • Iteration: Infinite iteration due to a mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further.

Difference between Iteration and Recursion

The following table lists the major differences between iteration and recursion:

Property

Recursion

Iteration

Definition Function calls itself. A set of instructions repeatedly executed.
Application For functions. For loops.
Termination Through base case, where there will be no function call. When the termination condition for the iterator ceases to be satisfied.
Usage Used when code size needs to be small, and time complexity is not an issue. Used when time complexity needs to be balanced against an expanded code size.
Code Size Smaller code size Larger Code Size.
Time Complexity Very high(generally exponential) time complexity. Relatively lower time complexity(generally polynomial-logarithmic).
Space Complexity The space complexity is higher than iterations. Space complexity is lower.
Stack Here the stack is used to store local variables when the function is called. Stack is not used.
Speed Execution is slow since it has the overhead of maintaining and updating the stack. Normally, it is faster than recursion as it doesn’t utilize the stack.
Memory  Recursion uses more memory as compared to iteration. Iteration uses less memory as compared to recursion.
Overhead Possesses overhead of repeated function calls. No overhead as there are no function calls in iteration.
Infinite Repetition If the recursive function does not meet to a termination condition or the base case is not defined or is never reached then it leads to a stack overflow error and there is a chance that the an system may crash in infinite recursion. If the control condition of the iteration statement never becomes false or the control variable does not reach the termination value, then it will cause infinite loop. On the infinite loop, it uses the CPU cycles again and again.


Previous Article
Next Article

Similar Reads

Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Print and remove leaf nodes of given Binary Tree on each iteration
Given a binary tree, the task is to: Print all the leaf nodes and then delete them all. Repeat this process till the tree becomes empty. Examples: Input: 1 /. \ 2 3 / \ 4 5 Output: Iteration 1: 4 5 3Iteration 2: 2Iteration 3: 1Explanation: The leaf nodes initially were 4, 5 and 3.When those were deleted only node with no child is 2.So the leaf node
7 min read
How to insert a node in Binary Search Tree using Iteration
You are given a binary search tree (BST) and a value to insert into the tree. Print inorder traversal of the BST after the insertion.Example: Input:To the given BST insert 40 Output: Explanation:The new node 40 is a leaf node. Start searching from the root till a leaf node is hit, i.e while searching if a new value is greater than current node move
10 min read
Minimum peak elements from an array by their repeated removal at every iteration of the array
Given an array arr[] consisting of N distinct positive integers, the task is to repeatedly find the minimum peak element from the given array and remove that element until all the array elements are removed. Peak Element: Any element in the array is known as the peak element based on the following conditions: If arr[i - 1] &lt; arr[i] &gt; arr[i +
11 min read
All permutations of a string using iteration
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We have discussed different recursive approaches to prin
4 min read
What is the difference between Backtracking and Recursion?
What is Recursion? The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Properties of Recursion:Performing the same operations multiple times with different inputs.In every step, we try smaller inputs to make the problem smaller.A base condition is nee
2 min read
Difference between Recursion and Dynamic Programming
Recursion and Dynamic programming are two effective methods for solving big problems into smaller, more manageable subproblems. Despite their similarities, they differ in some significant ways. Below is the Difference Between Recursion and Dynamic programming in Tabular format:Features Recursion Dynamic Programming Definition By breaking a difficul
5 min read
Inorder Tree Traversal without recursion and without stack!
Using Morris Traversal, we can traverse the tree without using stack and recursion. The idea of Morris Traversal is based on Threaded Binary Tree. In this traversal, we first create links to Inorder successor and print the data using these links, and finally revert the changes to restore original tree. 1. Initialize current as root 2. While current
9 min read
Practice questions for Linked List and Recursion
Assume the structure of a Linked List node is as follows. C/C++ Code struct Node { int data; struct Node *next; }; // This code is contributed by SHUBHAMSINGH10 C/C++ Code struct Node { int data; struct Node *next; }; Java Code static class Node { int data; Node next; }; // This code is contributed by shubhamsingh10 C/C++ Code class Node: def __ini
11 min read
Print 1 to 100 in C++ Without Loops and Recursion
We can print 1 to 100 without using loops and recursion using three approaches discussed below: 1) Template Metaprogramming: Templates in C++ allow non-datatypes also as parameters. Non-datatype means a value, not a datatype. Example: C/C++ Code // CPP Program to print 1 to 100 // without loops and recursion #include &lt;iostream&gt; using namespac
3 min read
three90RightbarBannerImg