Answer and Explanation:
import java.util.Scanner;
public class convertToBinary {
public static String declToBin(int value){
if(value == 1){
return declToBin((value/2) + "" + (value%2);
}
else{
declToBin((value/2) + "" + (value%2);
}
}
public static void main(String args[]){
int number;
Scanner change = new Scanner(System.in);
System.out.print("Enter decimal value: ");
number = change.nextInt();
System.out.println(declToBin(number));
}
}
The recursive function declToBin(int value) keeps executing code until value==1. Recursive functions reduces lines of code and makes it more efficient.
Note: Decimal is number in base 10(denary). To convert a decimal number to base 2(binary), we keep dividing the decimal number entered by the user by 2 until the result is zero(when the number divided is one)
We use the Java programming language here. First we import the Scanner object(import.java.util.Scanner). We use the method nextint() from the object to convert the string value entered by the user to int value( because our declToBin function takes an int parameter).