Java program to convert decimal to binary.



package demo;
import java.util.Scanner;
public class DecimalToBinary
{
 public static void main(String[] args) 
 {
  Scanner sc = new Scanner(System.in);
  int decimalNumber, remainder, quotient;
  int[] binaryNumber = new int[100];
  int i = 1;
  System.out.print("Enter any decimal number: ");
  decimalNumber = sc.nextInt();
  quotient = decimalNumber;
  while (quotient != 0) 
  {
   binaryNumber[i++] = (quotient % 2);
   quotient = quotient / 2;
  }
  System.out.print("Equivalent binary value of decimal number " + (decimalNumber) + ": ");
  for (int j = i - 1; j > 0; j--) 
  {
   System.out.print(binaryNumber[j]);
  }
 }
}

Output:
Enter any decimal number: 100
Equivalent binary value of decimal number 100 =  1100100
BUILD SUCCESSFUL (total time: 3 seconds)


Algorithum
Step 1: Divide the original decimal number by 2
Step 2: Divide the quotient by 2
Step 3: Repeat the step 2 until we get quotient equal to zero.


No comments:

Post a Comment