24

What is the difference between iteration and recursion and why/when is one better:

while (true) {
    // Iterating
}

And

private void recursion() {
    if (true)
        recursion(); // Recursing

    return;
}

I see a lot of recursive implementation while it could be easily done in a simple loop.

  • 1
    Functional languages tend to encourage recursion. It's less common in C but still very useful and powerful and needed for some problems. Iteration is *generally* faster, some compilers will actually convert certain recursion code into iteration. Recursion is often more elegant than iteration. – Charlie Burns Nov 05 '13 at 17:15
  • possible duplicate of [Recursion or Iteration?](http://stackoverflow.com/questions/72209/recursion-or-iteration) – Alexander Shukaev Nov 05 '13 at 17:16
  • Author, please learn to Google and use search here at SO. This question has to be closed and deleted as 101 duplicate. I can already see the flood of copy/paste answers. – Alexander Shukaev Nov 05 '13 at 17:29
  • @Haroogan I did search it before I asked my question but those answers just didn't do it for me, I just couldn't get it until now. –  Nov 05 '13 at 17:31

8 Answers8

38

There are two main differences between Recursion and an Iterative Version of the same algorithm.

First of all, some times it is almost better to understand a recursive algorithm than an iterative one (At least if you are experienced programmer) So it does increase expressivity and in some cases readability (It might also lead to the exact opposite in other cases)

Expresivity is a huge deal on programming languages and be able to write the same code in 5 lines instead of 20 is a huge deal.

On the downside, it decreases the performance of your code. Recursive functions have to keep the function records in memory and jump from one memory address to another to be invoked to pass parameters and return values. That makes them very bad performance wise.

Sum Up:

Iterative Algorithms = Fast Performance but hard to write (sometimes hard to read too)

Recursive Algorithms = Fast to write but Bad performance wise (Sometimes easier to understand too)

Take this example:

public static long fib(long n) {
    if (n <= 1) return n;
    else return fib(n-1) + fib(n-2);
}

vs

    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;
    }

Source:

http://www.csd.uwo.ca/Courses/CS1027a/code/FibonacciDemo.java

iordanis
  • 1,284
  • 2
  • 15
  • 28
  • Interesting, your example did it for me, it cleared my foggy thoughts about them. –  Nov 05 '13 at 17:26
  • but the iteration can be shoreter... `{ int cur=1,prev=0; while (--n){ int next = cur+prev; prev = cur; cur = next; } return cur; }` – SHR Nov 05 '13 at 17:28
  • 3
    @SHR Somewhat true, if nobody is going to maintain that code. But the recursive version is still shorter. – iordanis Nov 05 '13 at 17:31
  • Nice explanation, one thing to add so is that depending on the language and compiler the performance can be close or equal on an optimized recursive algorithm, while largely maintaining readability. For example calculating ```fib(n-1) + fib(n-2)``` would be very expensive but could be implemented via a tail call helper function accepting the 2 previous values as inputs. – Sideshowcoder Sep 26 '16 at 13:54
4

The main difference between recursion and iteration is memory usage.

For every recursive call needs space on the stack frame resulting in memory overhead.

Let me give you an example. Imagine in one case you forgot to write the base case for your recursive function resulting in endless recursive calls and in other case you wrote an infinite loop.

Since every recursive function assigns new memory space, in first case your code will give a stack overflow exception but in second case it will keep running forever.

So it better to make your iterative code more understandable than using Recursion.

mohit verma
  • 41
  • 1
  • 3
  • 1
    Very true, never thought about that, +1 ! –  Oct 08 '14 at 19:28
  • 1
    The memory usage isn't that simple as tail call optimisation is fairly standard now. Many recursive algorithms naturally contain a line like `return recurse(arg)`, others can be easily rewritten to use this form. When done like this the return path is just climbing up the stack returning each time. You can optimise this by not using a stack for all but the first function call - returning instantly and not using any additional memory for each recursion. – lod Aug 26 '15 at 07:48
1

They are different ways to do the same thing. All recursive implementations can be done with a (or multiple) loop(s) and vise versa. It is more about the logic behind it, a way to think about it. Factorial, although not the best example, is n * (n-1)! so it makes sense to use it recursively.

clcto
  • 9,530
  • 20
  • 42
0

Recursion and iteration are different ways to think about a solution. It would be dificult to explain in depth the difference in full scope. In your sample code, you aleady showed the difference. Recursive function is the one that calls itself, while iterative is the one that loops through some block of code. Here are some articles to help you understand them better: Recursion wiki

Iteration wiki

CodeProject SO #1

SO #2

Community
  • 1
  • 1
Roman
  • 1,727
  • 1
  • 20
  • 28
0

They can be used interchangeable to solve different problems. In essence you can write recursive functions iteratively and vise versa.

Iteration may increase the performance of your program. Whereas recursion may give a more intuitive and elegant result. You can choose either which to your preference!

Montaldo
  • 863
  • 8
  • 16
0

Recursive functions work through the process of calling themselves until a condition is met whereas iteration uses a looping control structure (for example while, do while, for) in order to repeat a section of code until a certain condition is met.

Recursive example:

int rec_func(int u, int k) {
  if (k == 0)
    return u;
  return rec_func(u * k, k - 1);
}

Iteration example:

int ite_func(int u, int k) {
  while (k != 0) {
    u = u * k;
    k = k - 1;
  }
  return u;
} 

The only real difference IMO between them is compilation differences.

  • no, not true. In the code sample above, one would loop infinitely and one would cause an error when the stack is full. – clcto Nov 05 '13 at 17:23
0

In theory, you can always swap between iteration and recursion. However, at least in case of C/C++/C#/Java, the compiler offers you some support which might make the solution more elegant, especially when you don't know the number of loops before.

The best example is listing all the files inside a folder and it's descendants. If there are several subfolders containg subfolders, normaly in iteration mode you need a stack to save all folders you need to analyze. In case of recursive approach, the stack is already provided by the compiler, and the solution is more elegant.

AndreiM
  • 815
  • 9
  • 17
-3

Differences between recursion and iteration

Recursion

  1. Recursive function – is a function that is partially defined by itself
  2. Recursion uses selection structure
  3. Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on some condition (base case)
  4. Recursion terminates when a base case is recognized
  5. Recursion is usually slower than iteration due to overhead of maintaining stack
  6. Recursion uses more memory than iteration
  7. Infinite recursion can crash the system
  8. Recursion makes code smaller

Iteration

  1. Iterative Instructions – are loop based repetitions of a process
  2. Iteration uses repetition structure
  3. An infinite loop occurs with iteration if the loop condition test never becomes false
  4. Iteration terminates when the loop condition fails
  5. Iteration does not use the stack so it's faster than recursion
  6. Iteration consumes less memory
  7. Infinite looping uses CPU cycles repeatedly
  8. Iteration makes code longer

Data taken from here.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Yasir
  • 1