I was hoping someone could please walk me through on how this works.
Code:/* Code that accepts a user number and puts it into a function to_binary */ void to_binary(int n) { int r; r = n % 2; if (n >= 2) to_binary(n/2); putchar('0' + r); return; }
This is a discussion on recursion within the C Programming forums, part of the General Programming Boards category; I was hoping someone could please walk me through on how this works. Code: /* Code that accepts a user ...
I was hoping someone could please walk me through on how this works.
Code:/* Code that accepts a user number and puts it into a function to_binary */ void to_binary(int n) { int r; r = n % 2; if (n >= 2) to_binary(n/2); putchar('0' + r); return; }
could you mentally execute the program for
n = 0, 1, 2, 3, 4... ?
If I have eight hours for cutting wood, I spend six sharpening my axe.
ok so 0 and 1 i get.. it prints out either 0 or 01
now lets take 2 for example.. r = 0
2 is = to 2 so 2 / 2 is 1
now r =1 r is < 2 so it prints 01
but thats wrong. how am i looking at this wrong?
No, it calls to_binary(1) before printing the current result, so the final output is '10' as expected.now r =1 r is < 2 so it prints 01
Each digit is processed from the left to the right and then everything is printed in the
reversed order.