0

My function:

int num(int x) 
{ 
   if(x>0) 
     num(x-1); 
   else 
     return 0; 
   printf("%d",x); 
}

This function takes a input x and prints the numbers from 1 upto x.I can't seem to understand how this works, can someone please elaborate. Thanks in advance!

2 Answers2

4

To solve this type of thing, it's often best to take a pen and paper and "pretend to be the computer running the code".

So, if we have a call of num(4), it will lead to:

if (4 > 0)    // Yupp, 4 > 0 
  num(3);     // x - 1 = 3
  if (3 > 0)  // Yupp
    num(2)
    if (2 > 0)
      num(1)
      if (1 > 0)
        num(0)
        if (0 > 0) // Nope
        goto else-part:
        return 0;
      skip else-part
      print(1);
    skip else-part
    print(2);
  skip else-part
  print(3)
  skip else-part
print(4)
Mats Petersson
  • 444
  • 2
  • 7
3

in my opinion, the easiest way of wrapping your head around recursion is starting from the end.

In every recursive function, there's a stopping condition. In your case it's else return 0; so the method will return 0 if the argument is zero or lower. That's simple. Now let's go backwards.

We know that num(0) returns 0 without doing anything else. So now we can now figure out what num(1) is. num(1) will call num(0) (which will return 0 and do nothing else), and then print x which is 1. Now we can backtrack and look at num(2). num(2) will call num(1), which we already covered, and then prints 2, so we can look at num(3) etc.

So for every number x, num(x) will simply print all numbers from 1 to x.

Malt
  • 164
  • 5