C - Recursion - Displaying a string

In this tutorial we will see how to display a string with the recursive method.

Let's see this example of the recursive and the iterative method with the functions below:

// recursion.c

#include        <string.h>
#include        <stdio.h>
#include        <unistd.h>

void    displayString_iterative(char *str)
{
  int   i;

  i = 0;
  while (str[i])
    write(1, &str[i++], 1);
}

void    displayString_recursive(char *str)
{
  if (strlen(str) <= 0)
    return;
  write(1, &str[0], 1);
  displayString_recursive(str + 1);
}


int     main()
{
  displayString_recursive("Hello BadproG.com!\n");
  displayString_iterative("Hello BadproG.com!\n");
  return (0);
}

Let's compile and execute it:

$ cc recursion.c && ./a.out

Result:

Hello BadproG.com!
Hello BadproG.com!

So we get exactly the same result with iterative and recursive method.

Interesting, isn't it?

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.