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!
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!
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) num(3), num(2) etc happens after printing, so obviously, values printed will be "high to low". If you place it after the call to num - either in the if or at the end, it will print in "low to high" order. 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.