Pages

Wednesday, March 31, 2021

Java Program to Add Two Numbers Without Using + operator

1. Introduction


In this article, You will learn how to write a java program to add two numbers without using + or ++ operators. This looks quite interesting for freshers to think beyond their capability but it is very easy for mathematic lovers. Before that in the last tutorial, we have explained how to add two numbers in java and shown the problems that occur. And also shown the example to read the input from user using Scanner,

Java Program to Add Two Numbers Without Using + operator


2. Java Program for addition without + operator


Let us jump into our topic today. How can you solve this problem? As told earlier if you are good at mathematics core concepts then by this time you would have guessed the solution. The answer will be very very simple.

Clue: In the problem statement it is mentioned that should not use + operator, But still you can use remaining operators.

Before seeing the solution, first put your thoughts on papers and see the original answer.

package com.javaprogramto.engineering.programs;

import java.util.Scanner;

public class SumOfTwoNumbersWithOutPlusOperator {

    public static void main(String[] args) {

        // reading input from user
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter First Number : ");
        int input1 = scanner.nextInt();
        System.out.print("Enter Second Number : ");
        int input2 = scanner.nextInt();

        // summing two numbers
        int output = input1 -(- input2);

        System.out.println("Scanner example to Sum of two numbers without using + operator (" + input1 + ", " + input2 + ") = " + output);

    }
}

Output:

Enter First Number : 12
Enter Second Number : 2
Scanner example to Sum of two numbers (12, 2) = 14

Here used simple formula result = a -(-b) which is equivalent to the "a + b".

3. Conclusion


In this tutorial, you have learned that we can still add two numbers even though not using + operator.

In the next tutorial, We will discuss and understand how to add two numbers without using any operator.

1 comment:

Please do not add any spam links in the comments section.