Java Programs

Add two numbers without addition operator

We will learn to write a program to add two numbers without using the addition operator in Java.

How will this Java program behave?

This program will take two numbers as input. After performing some operations according to the program, it will return the addition.

Suppose we input 35 and 20. Our program will return 55 as output without using any addition operator.

Program:

import java.util.Scanner;

public class Main {
 
	public static void main(String[] arg) {
	   int x, y ;
	   Scanner sc = new Scanner(System.in);	
	   System.out.print("Please Give first number: ");
	   x = sc.nextInt(); 
	   System.out.print("Please Give second number: ");
	   y = sc.nextInt(); 
      
	   while(y != 0) {
           int temp = x & y;
           x = x ^ y;
           y = temp << 1;
       }
	   
       System.out.print("Sum = "+x);   	
	}		
}

Output:

Please Give first number: 20
Please Give second number: 30
Sum = 50

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs