This Java program converts a decimal number to its binary equivalent. The program prompts the user to enter a decimal number, then reads the input using a Scanner.
The program defines a method called decimal2Binary, which takes an integer argument n (the decimal number to be converted). Inside the method, the program declares an integer array binaryNum with a capacity of 1000 to store the binary digits of the converted number.
The method then performs a loop to convert the decimal number to binary. Inside the loop, it divides the decimal number n by 2 and stores the remainder (0 or 1) in the binaryNum array. It then updates n by dividing it by 2 and repeating the process until n becomes 0.
Finally, the method performs another loop to print out the binary digits in reverse order. It starts from the highest index of the binaryNum array (i.e., i-1, where i is the index of the first unused element in the array) and prints out each digit until it reaches the first element.
The main method of the program calls the decimal2Binary method, passing the user input as an argument. It then prints out the original decimal number and the resulting binary number using System.out.print.
import java.util.Scanner; public class decimal_binary { public static void decimal2Binary(int n) { int[] binaryNum = new int[1000]; int i = 0; while (n > 0) { binaryNum[i] = n % 2; n = n / 2; i++; } for (int j = i - 1; j >= 0; j--) System.out.print(binaryNum[j]); } public static void main(String args[]) { Scanner in =new Scanner(System.in); System.out.println("Enter The Decimal No : "); int n = in.nextInt(); System.out.println("Decimal No : " + n); System.out.print("Binary No : "); decimal2Binary(n); } }
Enter The Decimal No : 10 Decimal No : 10 Binary No : 1010To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions