Write a Java program to add two binary numbers.
Input:
Binary_1 = 010 // decimal number is 2
Binary_2 = 011 // decimal number is 3
Output:
Addition of the binary number = 101 //decimal number is 5=2+3
import java.io.*; import java.util.*; public class temp{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int a[]=new int[10]; int i,X,Y,t,c=0; System.out.print("Enter the Binary 1: "); int Binary_1 = sc.nextInt(); System.out.print("Enter the Binary 2: "); int Binary_2 = sc.nextInt(); for(i=a.length-1;i>=0;i--) { X = Binary_1 % 10; Y = Binary_2 % 10; Binary_1 = Binary_1 / 10; Binary_2 = Binary_2 / 10; t = X + Y + c; if(t==1) { a[i]=1; c=0; } else if(t==2) { a[i]=0; c=1; } else if(t==3) { a[i]=1; c=1; } } i=0; while(a[i]==0)i++; System.out.print("Addition of the two binary number is "); for(;i<a.length;i++) System.out.print(a[i]); } }
INPUT_1:
Enter the Binary 1: 010
Enter the Binary 2: 011
OUTPUT:
Addition of the two binary number is 101
INPUT_2:
Enter the Binary 1: 101
Enter the Binary 2: 101
OUTPUT:
Addition of the two binary number is 1010
INPUT_3:
Enter the Binary 1: 1010
Enter the Binary 2: 101
OUTPUT:
Addition of the two binary number is 1111
INPUT_4:
Enter the Binary 1: 1111
Enter the Binary 2: 001
OUTPUT:
Addition of the two binary number is 10000
INPUT_5:
Enter the Binary 1: 1011
Enter the Binary 2: 100
OUTPUT:
Addition of the two binary number is 1111
INPUT_6:
Enter the Binary 1: 1011
Enter the Binary 2: 0100
OUTPUT:
Addition of the two binary number is 1111
INPUT_7:
Enter the Binary 1: 0110
Enter the Binary 2: 0111
OUTPUT:
Addition of the two binary number is 1101
INPUT_8:
Enter the Binary 1: 110
Enter the Binary 2: 111
OUTPUT:
Addition of the two binary number is 1101
ILLUSTRATION