Given a decimal number, Write a java program to convert decimal to binary number.
For example :
Input : 4 , Output : 100
Input : 5 , Output : 101
Input : 10 , Output : 1010
Java Program to Convert Decimal to Binary Number
In this coding example, we are going to write a java code which convert decimal number to binary number. Here is the list of things we have in this code.
i) In this program, we have store the remainder in an array, when the number is divided by 2.
ii) Then, In next step divide the number by 2.
iii) Repeat the above two steps until the number is greater than zero.
iv) In last step, print the array in reverse order.
Java Program to Reverse Each Words of a String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
/** * Convert Decimal Number to Binary Number */ public class DecimalToBinary { public static void decimalToBinary(int num) { //Declared an array int arr[] = new int[20]; int count = 0; //Run a loop until a number is greater than zero while(num > 0) { //Assign the value at array index and increment the value of count arr[count++] = num % 2; //Divide the number by 2 num = num/2; } //Traverse an array and print the result for(int i = count - 1; i >=0 ; i--) { System.out.print(arr[i] + " "); } } public static void main(String[] args) { int num = 8; decimalToBinary(num); } } |
Find Common Elements in Two Arrays
How to Convert Decimal to Binary Number : Video Tutorial
In this tutorial, I have explained how to convert a decimal to binary number.