tags:

views:

105

answers:

4

Hey all, About my question, I'm asking a theoretical question here about Base case or the halting case in a recursive method, what's its standards? I mean, is it standard not to have body in it, just a return statement?

Is it always like the following:

If(input operation value)
return sth;

Do you have different thoughts about it??

+1  A: 

The base case is to terminate the loop (avoid becoming an infinite recursion). There's no standard in the base case, any input that is simple enough to be solved exactly can be chosen as one.

For example, this is perfectly valid:

int factorial (int n) {
  if (n <= 5) {
    // Not just a return statement
    int x = 1;
    while (n > 0) {
      x *= n;
      -- n;
    }
    return x;
  } else {
    return n * factorial(n-1);
  }
}
KennyTM
I said that I'm asking a theoretical question, I mean if I want to teach recursion, I wont use your previous code, I know it's a valid way, but it doesn't make recursion and the Base case concept clear enough, what do you think?
Shaza
A: 

The pattern for recursive functions is that they look something like this:

f( value ) 
   if ( test value )
      return value
   else
      return f( simplify value )

I don't think you can say much more than that about general cases.

anon
A: 

It depends entirely on the particular recursive function. In general, it can't be an empty return; statement, though - for any recursive function that returns a value, the base case should also return a value of that type, since func(base) is also a perfectly valid call. For example, a recursive factorial function would return a 1 as the base value.

tzaman
A recursive method doesn't have to return a value, though.
Ken
True, of course. But then, I could say: for recursive methods that return `void`, the base will also return `void` ... ;)
tzaman
+1  A: 

In some cases, your base case is

return literal

In some cases, you base case is not simply "return a literal".

There cannot be a "standard" -- it depends on your function.

The "Syracuse Function" http://en.wikipedia.org/wiki/Collatz_conjecture for example, doesn't have a trivial base case or a trivial literal value.

"Do you have different thoughts about it??" Isn't really a sensible question.

The recursion has to terminate, that's all. A trivial tail recursion may have a "base case" that returns a literal, or it may be a calculation. A more complex recursion may not have a trivial "base case".

S.Lott