ADVERTISEMENT
ADVERTISEMENT

Java program to find the sum of two numbers using binary addition

Given two numbers, we have to find the sum of two numbers using binary addition.
Submitted by Nidhi, on March 02, 2022

Problem Solution:

In this program, we will read two integer numbers from the user and find the sum of input numbers using binary addition.

Program/Source Code:

The source code to find the sum of two numbers using binary addition is given below. The given program is compiled and executed successfully.

// Java program to find the sum of two numbers 
// using binary addition

import java.util.Scanner;

public class Main {
  static int binAddition(int a, int b) {
    int c; //carry

    while (b != 0) {
      c = (a & b) << 1;
      a = a ^ b;
      b = c;
    }
    return a;
  }

  public static void main(String[] args) {
    Scanner SN = new Scanner(System.in);

    int num1 = 0;
    int num2 = 0;
    int add = 0;

    System.out.printf("Input first integer value: ");
    num1 = SN.nextInt();

    System.out.printf("Input second integer value: ");
    num2 = SN.nextInt();

    add = binAddition(num1, num2);
    System.out.printf("Binary Addition is: %d\n", add);
  }
}

Output:

Input first integer value: 34
Input second integer value: 23
Binary Addition is: 57

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains two static methods binAddition() and main().

The binAddition() method is used to add two integer numbers using binary addition and return the result to the calling method.

The main() method is an entry point for the program. Here, we read two integer numbers from the user using the Scanner class. Then we calculated the sum of given numbers using the binAddition() method and printed the result.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.