I want one to explain the following function accurately.
void ToBin(int n){
if (n>1)
ToBin( n/2 );
printf( "%d", n%2 );
}
For example:
If I'm entered 7
, what's happen (the function behavior) to convert to binary 111
.
Please I want step by step explanation to I understand.
Edit
The same function but prints the result more clearly.
void ToBin( int n ){
printf("%d/2= %d -> %d\n", n, n/2 ,n%2);
if (n>1)
ToBin( n/2 );
}
With 7 in particular:
First, n = 7, so n > 1. Thus, ToBin is called again on n / 2 = 3.
Now, n = 3, so n > 1. Thus, ToBin is called again on n / 2 = 1.
Now, n = 1, so n is not greater than 1. Thus, 1 % 2 = 1 is printed, and control jumps back to the previous frame.
Here, n = 3, and 3 % 2 = 1 is printed, with control jumping back a frame again.
Here, n = 7, and 7 % 2 = 1 is printed, and as the function is left and there are no more ToBin frames left, control is returned to the function that originally called ToBin.
In general, this function works as follows:
The binary expression of a number is equal to the binary expression of the floor of half that number, with the lowest bit of the original number appended.
Thus, the function repeatedly gets the binary expression of the floor of half the input until that value is a single bit. Then, that bit, being the most significant bit of the number, is printed, and subsequently, so is each bit in descending order of significance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With