Decimal to Binary conversion (using array)

Conversion of decimal to binary using array

import java.io.*;
import java.util.*;

class binaryArray
{
// function to convert decimal to binary
static void decToBinary(int n)
{
// array to store binary number
int[] binaryNum = new int[1000];

// counter for binary array
int i = 0;
while (n > 0)
{
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}

// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
System.out.print(binaryNum[j]);
}

// driver program
public static void main (String[] args)
{ Scanner sc=new Scanner(System.in);
int n ;
System.out.println("Enter a decimal value:");
n=sc.nextInt();
decToBinary(n);
}
}

Output:

Enter a decimal value:
7
111

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.