Difference Between Recursion and Iteration

Last updated on September 4th, 2023 at 09:47 pm

Here, We will learn about recursion, iteration, differences between recursion and iteration and their code in java.

Recursion

Recursion is a technique in which function calls itself until a base condition is satisfied. A recursive method solves a problem by calling a copy of itself to work on a smaller problem

Example Recursion Code in Java:
public static long fib (long n)
{
    if (n <= 1)
        return n;
    else
        return fib (n-1) + fib (n-2);Code language: Java (java)
differences between recursion and iteration, recursion, recursive approach
iteration, iterative approach, differences between recursion and iteration

Iteration

Iteration is a technique in which function call repeatedly for a finite number of times. It use constructs like loops and sometime other data structures like stacks and queues to solve the problems.

Example Iteration Code in Java:
public static long fib (long n)
{
    if ((n == 1) || (n == 2)){
        return 1;
    }
    else{
        long prev = 1, current = 1, next = 0;
        for (long i=3; i<=n; i++){
            next = prev + current;
            prev = current;
            current = next;
         }
        return next;
    }
}Code language: PHP (php)

Difference between Recursion and Iteration

RecursionIteration
Recursion uses selection structureIteration uses repetition structure
It is slower than iteration due to overhead of maintaining stackIt is faster than recursion because it does not use the stack
It uses more memoryIt uses less memory.
Infinite recursion can crash the systemInfinite looping uses CPU cycles repeatedly
It makes code smallerIt makes code longer

Recursive Algorithms

Here, We will learn about recursive algorithm, recursion, recursive function, implementation, properties and examples of…

Read More

4Sum LeetCode Solution

Here, We see 4Sum LeetCode Solution. This Leetcode problem is done in many programming languages…

Read More

Want to Contribute:-

If you like “To The Innovation” and want to contribute, you can mail your articles to 📧 [email protected]. See your articles on the main page and help other coders.😎

Leave a Comment

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

Scroll to Top