Hey there guys
I've got a sample code on converting numbers into binary by using recursions
heres the function:
Code:
void printBinary (int n) {
if (n < 2) {
printf ("%d ", n);
} else {
printf ("testX "); //this is hear to see how recursive pattern works
// recursively print the leading bits
printBinary (n/2);
printf ("testY "); //this is also hear to see how recursive pattern works
// print the least significant bit
printf ("%d ", n%2);
}
}
Output:
Code:
Enter an integer to display in binary
8
testX testX testX 1 testY 0 testY 0 testY 0
ok so the output is 1000, however it recurs 3 times before printing a 1 without therefore:
8 / 2 = 4 (first time)
4 / 2 = 2 (second time)
2 / 2 = 1 (third time)
since 1 < 2 it prints out 1, fair enough. now from here on it gets confusing O_O. How is it going to this part of the function:
Code:
// print the least significant bit
printf ("%d ", n%2);
3 times?
thanks guys.