Java program to add two numbers without using the + operator | Java code geeks


1. Introduction

In this article, you will learn how to write a java program to add two numbers without using the + or ++ operators. It sounds interesting enough for novices to think beyond their abilities, but it is very easy for math enthusiasts. Before that in the last tutorial we explained how to add two numbers in java and show the problems that occur. And also showed the example to read user input using the scanner.

2. Java program for adding without operator +

Let’s move on to our topic today. How can you solve this problem? As stated before, if you have mastered the basic concepts of math, then you would have guessed the solution. The answer will be very, very simple.

Hint: in the problem statement, it is mentioned that must not use the + operator, But you can still use the remaining operators.

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

01

02

03

04

05

06

07

08

09

ten

11

12

13

14

15

16

17

18

19

20

21

22

package com.javaprogramto.engineering.programs;

import java.util.Scanner;

public class SumOfTwoNumbersWithOutPlusOperator {

    public static void main(String[] args) {

        

        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();

        

        int output = input1 -(- input2);

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

    }

}

Exit:

1

2

3

Enter First Number : 12

Enter Second Number : 2

Scanner example to Sum of two numbers (12, 2) = 14

Here used a simple formula result = a – (- b) which is equivalent to “A + b”.

3. Conclusion

In this tutorial you have learned that we can always add two numbers even if you don’t use the + operator.

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



Source link

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *