Write a program to convert a binary to decimal number without using array
This is a Java program to convert a binary number to a decimal number. Here is a step-by-step explanation of the code:
- The first line of code imports the Scanner class from the java.util package. This class is used to read input from the user.
- The program declares a public class named "Binary_Decimal" which contains the main method.
- Inside the main method, a new Scanner object named input is created to read input from the user.
- The program prompts the user to enter a binary number by printing the string "Enter Binary Number : " using the System.out.print method.
- The input from the user is read as an integer using the nextInt method of the Scanner class and stored in the variable n.
- Several integer variables, n1, p, dec, i, and d, are declared and initialized to 0 or 1.
- The variable n1 is assigned the value of n so that the original binary number can be printed later.
- A for loop is used to convert the binary number to a decimal number. The loop starts from j=n and continues until j is greater than 0. The loop variable j is divided by 10 in each iteration to remove the last digit of the binary number.
- Inside the for loop, the last digit of the binary number is extracted by taking the remainder of j divided by 10 and stored in the variable d.
- The variable p is calculated as either 1 or 2 depending on the position of the digit in the binary number.
- The variable dec is calculated as the sum of each digit multiplied by the corresponding power of 2.
- The loop variable i is incremented by 1 to keep track of the position of the current digit in the binary number.
- After the for loop is complete, the program prints the original binary number using the System.out.println method with the string "Binary Number : ".
- The program then prints the decimal equivalent of the binary number using the System.out.println method with the string "Decimal Number : " and the variable dec.
Source Code
import java.util.Scanner;
class Binary_Decimal
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Binary Number : ");
int n = input.nextInt();
int n1,p=1;
int dec=0,i=1,j,d;
n1=n;
for (j=n;j>0;j=j/10)
{
d = j % 10;
if(i==1)
p=p*1;
else
p=p*2;
dec=dec+(d*p);
i++;
}
System.out.println("Binary Number : "+n1);
System.out.println("Decimal Number : "+dec);
}
}
Output
Enter Binary Number : 100100
Binary Number : 100100
Decimal Number : 36