KnowledgeBoat Logo

Computer Applications

Write a program to input a number and display it into its Binary equivalent.
Sample Input: (21)10
Sample Output: (10101)2

Java

Java Iterative Stmts

ICSE

15 Likes

Answer

import java.util.*;

public class KboatDecimaltoBinary
{
    public static void main(String args[])  {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the decimal number: ");
        long decimal = in.nextLong();    
        long binary = 0, m = 1, rem = 0;
        
        while(decimal > 0)    {
             rem = decimal % 2;
             binary = binary + (rem * m);
             m *= 10;
             decimal /= 2;
        }
        System.out.println("Equivalent binary number: " + binary);
    }
}

Output

BlueJ output of Write a program to input a number and display it into its Binary equivalent. Sample Input: (21) 10 Sample Output: (10101) 2

Answered By

6 Likes


Related Questions