Q:

Java program to perform subtraction without using minus (-) operator

belongs to collection: Java Basic Programs

0

Java program to perform subtraction without using minus (-) operator

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will read two integer numbers from the user and perform subtraction without using the minus (-) operator, and print the result.

Program/Source Code:

The source code to perform subtraction without using the Minus (-) operator is given below. The given program is compiled and executed successfully.

// Java program to perform subtraction 
// without using minus (-) operator

import java.util.Scanner;

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

    int num1 = 0;
    int num2 = 0;
    int sub = 0;

    System.out.printf("Enter first number: ");
    num1 = X.nextInt();

    System.out.printf("Enter second number: ");
    num2 = X.nextInt();

    sub = num1 + ~num2 + 1;

    System.out.printf("Subtraction of %d-%d=%d", num1, num2, sub);
  }
}

Output:

Enter first number: 65
Enter second number: 54
Subtraction of 65-54=11

Explanation:

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

The main() method is an entry point for the program. Here, we read two integer numbers from the user and performed the subtraction operation using "+" and "~" operators. After that, we printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to print the value in decimal, octal,... >>
<< Java program to multiply two numbers using plus (+...