Write a recursive method that voidprintbinary( int n)
Answers
- Write a recursive method int printbinary(int n) that displays binary equivalent of a number.
This is written in Java.
int printbinary(int n){
if(n==0)
return n;
return (n%2)+printbinary(n/2)*10;
}
Lets test our result.
Consider a decimal number - 10
>> printbinary(10)
10 is not equal to zero.
So, it returns - (10%2) + printbinary(10/2)*10
= 0 + printbinary(5)*10
= 0 + 10 * [(5%2) + 10 * printbinary(5/2)] (As 5 not equals 0)
= 0 + 10 * [1 + 10 * [(2%2) + 10 * printbinary(2/2)] ] (Again, 2 not equals 0)
= 0 + 10 * [1 + 10 * [0 + 10 * [(1%2) + 10 * [printbinary(1/2)] ] ] (1 not equals 0)
= 0 + 10 * [1 + 10 * [0 + 10 * [1 + 10 * 0] ] ] (As 0 equals 0)
= 0 + 10 * [1 + 10 * [0 + 10 * [1 + 0] ] ]
= 0 + 10 * [1 + 10 * [0 + 10] ]
= 10 * [1 + 10 * 10]
= 10 * [1 + 100]
= 10 * 101
= 1010
So,
→ (10)₁₀ = (1010)₂
⊕ In this way, the function converts the decimal number to binary.
- A recursive function is a function which calls itself.
- A recursive function must have at least one base case. The base case is a condition that terminates the recursion. Here in this code, the base case is - (n == 0)