Recursion


Let's "unwind" this recursion and look at it in a non-recursive way.

Suppose we had 4 functions, each that prints a string:

void print_string1(const char *string);
void print_string2(const char *string);
void print_string3(const char *string);
void print_string4(const char *string);
Implementations:
void print_string1(const char *string)
{
  if (*string)
  {
    putchar(*string);
    print_string2(string + 1);
  }
}
void print_string2(const char *string)
{
  if (*string)
  {
    putchar(*string);
    print_string3(string + 1);
  }
}
void print_string3(const char *string)
{
  if (*string)
  {
    putchar(*string);
    print_string4(string + 1);
  }
}
void print_string4(const char *string)
{
  if (*string)
    putchar(*string);
}

We can print a string by calling the first function:

char *s = "Digi";
print_string1(s);
This will display the 4 character string: Digi
  1. print_string1 prints D and calls print_string2 with igi, then returns.
  2. print_string2 prints i and calls print_string3 with gi, then returns.
  3. print_string3 prints g and calls print_string4 with i, then returns.
  4. print_string4 prints i and returns.
Problems/Limitations: A solution is to start the process again. We just have print_string4 print the first character and then call print_string1 with the rest of the characters:
void print_string4(const char *string)
{
  if (*string)
  {
    putchar(*string);
    print_string1(string + 1);
  }
}
Now, we can print a string of any length and the process would go like this:
  1. Pass a string to print_string1.
  2. In print_string1, if the first character isn't NULL, print it and pass the rest of the characters to print_string2.
  3. In print_string2, if the first character isn't NULL, print it and pass the rest of the characters to print_string3.
  4. In print_string3, if the first character isn't NULL, print it and pass the rest of the characters to print_string4.
  5. In print_string4, if the first character isn't NULL, print it and pass the rest of the characters to print_string1.
  6. Goto step 2.
This process will continue until the first character in any function is NULL, because the "chain" has been broken.

void print_string1(const char *string)
{
  if (*string)
  {
    putchar(*string);
    print_string1(string + 1);
  }
}
This is the same as our original recursive function, but with a different name.