vandench
vandench

Reputation: 2233

Practical uses for Recursion

Are there any times where it is better to use recursion for a task instead of any other methods? By recursion I am referring to:

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

Upvotes: 0

Views: 206

Answers (2)

Simon Kraemer
Simon Kraemer

Reputation: 5680

First of all your example doesn't make any sense. The way you wrote it would just lead to an endless loop without any result ever.

A "real" function would more look like this:

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

Of course you could accomplish the same thing with a loop (which might even be better, especially if the function call incurs the penalty of a stack frame). Usually, when people use recursion they do so because it's easier to read (for certain problem domains).

Upvotes: 2

Parthian Shot
Parthian Shot

Reputation: 1432

Well, there are a few reasons I can think of.

  • Recursion is often easier to understand than a purely iterative solution. For example, in the case of recursive-descent parsers.

  • In compilers with support for tail call optimization, there's no additional overhead to using recursion over iteration, and it often results in fewer lines of code (and, as a result, fewer bugs).

Upvotes: 3

Related Questions