JAVA program to convert a decimal number to a binary number

JAVA program to convert a decimal number to a binary number

This JAVA program is to convert a decimal number to a binary number.

For example 18(DECIMAL) —>  10010(BINARY).

Logic

Take a decimal number and keep breaking it down like find remainder and quotient.

Dry Run of the Program

Take an input decimal number ‘n’. Let us say n=2

1st iteration while(n!=0)  while(2!=0)

b[i]=n%2   i.e b[0]=2%2   hence b[0]=0

n=n/2   i.e n=2/2  hence n=1

i++; ie i=1

c++ ie c=1

2nd iteration while(n!=0)  while(1!=0)

b[i]=n%2   i.e b[1]=2%2   hence b[0]=0

n=n/2   i.e n=1/2  hence n=0

i++; ie i=2

c++ ie c=2

While loop ends as n=0

Then we get into the for loop

1st iteration for(i=c-1;i>=0;i–)    i.e. for(i=1;i>=0;i–)   as c=2

print b[i] i.e b[1] = 1    print 1

2nd iteration for(i=c-1;i>=0;i–)    i.e. for(i=0;i>=0;i–)

print b[i] i.e b[0] = 0     print 1 0

For loop ends and 2’s binary number –> 1 0 (BINARY)

Program

import java.util.*;

class decTobin {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the decimal no");
        int n = sc.nextInt();
        int i=0,c=0;
	int b[] = new int[21];
	while(n!=0)
	{
		b[i]=n%2;
		n=n/2;	
		i++;		
		c++;
	}
		
 	System.out.println("Binary number");
	for(i=c-1;i>=0;i--)
	 	System.out.print(b[i]);
    }
}

Output

Share Me!