Decimal to Binary number

Binary number is a number expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one). In this program, we start with the given decimal number, and repeatedly divide it by 2 (whole number division where the result will be only the quotient, a whole number) and note down the remainder at every step till we obtain the quotient as 0. The remainders obtained in each step when concatenated together (the last remainder taken as the first digit of the binary number) give the binary form of the decimal number. For example, the binary form of decimal number 15 is 1111.

class DecimalToBinary {

 public static void main(String[] args) {
  int num = Integer.parseInt(args[0]);
  String binary="";
  while (num > 0) {
   binary = (num % 2) + binary;
   num = num / 2;
  System.out.println("Binary number is :: " + binary);
C:\>java DecimalToBinary 15
Binary number is :: 1111
C:\>java DecimalToBinary 50
Binary number is :: 110010


Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Program to input age from user and throw user-defined exception if entered age is negative

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.