java

Write a Java Program to Add Two Binary Numbers

In this tutorial, we are going to see how to write a Java program to add two binary numbers. The binary system only has two symbols 0 and 1, so a binary number consists only of 0 and 1. Before writing a program that calculates the sum, look at the image below, to see the different steps to add two binary numbers:
 

 

 

Example :

In the following code, we use the Scanner class to get the user’s input (the user enters the two binary numbers that we need to add) and then we add them using the while loop and storing the result in an array.

import java.util.Scanner;

public class Main {
	public static void main(String[] args)
	{
		long b1, b2;
		int i = 0, remainder = 0;
		int[] sum = new int[50];
		Scanner sc = new Scanner(System.in);

		System.out.print("Enter the first binary number: ");
		b1 = sc.nextLong();
		System.out.print("Enter the second binary number: ");
		b2 = sc.nextLong();

		while (b1 != 0 || b2 != 0) 
		{
			sum[i++] = (int)((b1 % 10 + b2 % 10 + remainder) % 2);
			remainder = (int)((b1 % 10 + b2 % 10 + remainder) / 2);
			b1 = b1 / 10;
			b2 = b2 / 10;
		}
		
		if (reste != 0) {
			sum[i++] = remainder;
		}
		--i;
		System.out.print("The addition of the two binary numbers is: ");
		
		while (i >= 0) {
			System.out.print(sum[i--]);
		}
		System.out.print("\n");  
	}
}

Output:

Enter the first binary number:  11001
Enter the second binary number: 01010
The addition of the two binary numbers is: 100011
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *