0

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);
  }
}
vandench
  • 1,973
  • 3
  • 19
  • 28
  • 1
    the classic maze problem is an example of where to use it. but anywhere you can use it you can use a non-recursion solution as well. asking about "better" is a relative term in the eyes of the beholder. one persons noise is another persons signal. so there is no such thing as better or worse. only better or worse for you and one particular problem being solved. – old_timer Feb 08 '16 at 18:21

2 Answers2

3

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).

Community
  • 1
  • 1
Parthian Shot
  • 1,390
  • 1
  • 13
  • 24
2

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).

Parthian Shot
  • 1,390
  • 1
  • 13
  • 24
Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49