Java-: Print the sum, multiply, subtract, divide and remainder of two numbers
Basic Arithmetic Operations
Write a Java program to print the sum (addition), multiply, subtract, divide and remainder of two numbers.
Test Data:
Input first number: 125
Input second number: 24
Pictorial Presentation:
Sample Solution-1
Java Code:
Explanation:
In the exercise above -
- It takes two integer numbers as input from the user using the Scanner class.
- Scanner in = new Scanner(System.in);
- System.out.print("Input first number: ");
- int num1 = in.nextInt();
- System.out.print("Input second number: ");
- System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); - It calculates and displays the sum of the two numbers.
- System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); - It calculates and displays the difference between the two numbers.
- System.out.println(num1 + " x " + num2 + " = " + (num1 * num2)); - It calculates and displays the product of the two numbers.
- System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); - It calculates and displays the result of dividing the first number by the second number.
- System.out.println(num1 + " mod " + num2 + " = " + (num1 % num2)); - It calculates and displays the remainder (modulus) when the first number is divided by the second number.
Sample Output:
Input first number: 125 Input second number: 24 125 + 24 = 149 125 - 24 = 101 125 x 24 = 3000 125 / 24 = 5 125 mod 24 = 5
Flowchart:
Sample Solution-2
Java Code:
Sample Output:
Input the first number: 6 Input the second number: 5 Sum = 11 Minus = 1 Multiply = 30 Subtract = 11 Divide = 1 RemainderOf2Numbers = 1
Flowchart:
For more Practice: Solve these Related Problems:
- Write a program that performs arithmetic operations on three numbers instead of two.
- Modify the program to take input from the user and display the results dynamically.
- Perform arithmetic operations, but ensure the division operation rounds to two decimal places.
- Write a program that performs arithmetic operations without using '+', '-', '*', or '/' operators.
Go to:
PREV : Product of Two Numbers.
NEXT : Multiplication Table.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.