C - Recursion - Finding a number until a variable reaches another one

The code below display the nb variable until it reaches the number ten.

But the recursion will display the phrase in the printf(), of the main(), at the end of the while inside the r() function.

So the code inside the r() function will be executed before the printf() of the main().

Let's see this easy example:

#include        <stdio.h>

int     r(int nb) {
  while (nb < 10)
    {
      printf("nb = %d\n", nb);
      return r(++nb);
    }
  return 10;
}

int     main() {
  int first = 1;

  printf("Last = %d\n", r(first));
  return 0;
}

And the result:

nb = 1
nb = 2
nb = 3
nb = 4
nb = 5
nb = 6
nb = 7
nb = 8
nb = 9
Last = 10

 

Add new comment

Plain text

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