Convert a given decimal number to binary form

Posted By: Java Examples - 11:09 AM

Share

& Comment

Description of program :
This program takes a decimal number from console and it converts it into binary format . Input number is taken as Integer so convert it into an integer data using the while loop method. The Decimal number is divided by 2 and this reminder save in array .Print the binary number in reverse array using for loop


Java version of the decimal number to binary is given below :
/**
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package statement;

import java.util.Scanner;

/**
 *
 * @author ACHCHUTHAN
 */
public class Dec2Bin {

    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        int n;
        int i = 0;
        System.out.println("Enter Decimal Number :");
        n = s.nextInt();
        int[] bin = new int[20];
        while (n > 0) {
            bin[i] = n % 2;
            i++;
            n = n / 2;
        }
       System.out.print("Number converted into binary is:");
        for (int j = i - 1; j >= 0; j--) {
            System.out.print(bin[j]);
        }
    }
}

Output of this program is given bellow :

run:

Enter Decimal Number :
25
Number converted into binary is:11001

BUILD SUCCESSFUL (total time: 7 seconds)

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .