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
.