Write a program to convert Decimal to Binary number system


The program starts by importing the Scanner class from the java.util package, which allows user input to be read from the console. Then a class named Decimal_Binary is defined, which contains the main method that executes the program.

Inside the main method, the program declares and initializes variables to be used in the conversion process. The decimal variable stores the decimal number entered by the user, and the i variable is an index used to keep track of the current digit being converted. The binary array stores the binary digits in reverse order.

The program then prompts the user to enter a decimal number using System.out.print and reads the input value using the Scanner class.

After that, the program enters a while loop that runs as long as the decimal number is not equal to 0. Inside the loop, the program calculates the remainder of the division of the decimal number by 2 and stores it in the binary array at the current index. The i index is then incremented, and the decimal number is divided by 2 to move to the next digit.

After the loop completes, the binary array contains the binary representation of the decimal number in reverse order. The program then uses a for loop to iterate through the binary array in reverse order and print each digit to the console using System.out.print.

Source Code

import java.util.Scanner;
public class Decimal_Binary
{
   public static void main(String[] args)
   {
      int decimal, i=0;
      int[] binary = new int[20];      
      Scanner scan = new Scanner(System.in);      
      System.out.print("Enter the Decimal Number: ");
      decimal = scan.nextInt();      
      while(decimal != 0)
      {
         binary[i] = decimal%2;
         i++;
         decimal = decimal/2;
      }      
      System.out.print("Binary Number : ");
      for(i=(i-1); i>=0; i--)
         System.out.print(binary[i]);
   }
}

Output

Enter the Decimal Number: 46
Binary Number : 101110

Example Programs