Re: Is this recursion?



In addition to the other two responses, which are fine. If you need to
format your recursive function call according to the form it's normally
expressed in, then you can do so by making a small modification to your
code. (Incidentally, this also makes empty strings work.)

Just think of your existing example as "inlining" the base case. Then
undo the inlining. You'll end up with:

public static void reversal(String aWord,int position)
{
if (position < 0)
{
return; // base case
}
else
{
// inductive case
System.out.print(aWord.charAt(position));
reversal(aWord,position-1);
}
}

I made this modification mechanically, just by noting that instead of
only calling reversal on (position != 0), one could always call it
anyway, and then just have it do nothing if (position < 0). You get the
empty string for free.

By comparison, here was your original code (modifications for formatting
and to make the non-structural stuff clearer:

public static void reversal(String aWord,int position)
{
System.out.print(aWord.charAt(position);

if (position != 0)
{
reversal(aWord,position-1);
}
}

I have a feeling the professor is probably not going to like this
because it doesn't fit the 'model' recursion defintion...

Note that I point this out only because it might help you understand
what's going on in terms of this model definition. It may also help you
out if your professor is him/herself shaky on the subject and is likely
to grade formulaically. As much as I'd like to think that's impossible,
experience teaches otherwise.

Your previous answer (except for the empty string case, as Patricia
pointed out) is just fine as a recursive definition.

--
Chris Smith
.



Relevant Pages

  • Re: [RFC] Recursive printk
    ... Here is a set of two patches + a demo patch to enable recursive processing ... of a printf format string in vsnprintf, ... With recursion all the formatting is done into the same buffer ...
    (Linux-Kernel)
  • Re: Empty string
    ... Which creates a new empty string object. ... | poor form in object orientation where I should be able to create a new ... | collector once the recursion is complete. ... | String.Copyis also not an lvalue. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Sun studio CC __attribute__(format) ??
    ... What the format attribute does. ... type-checked against a format string. ... int my_printf ... In order to understand recursion you must first understand recursion. ...
    (comp.unix.solaris)