Post

Created by @nathanedwards
 at October 31st 2023, 3:50:52 pm.

Question:
Write a Java program that takes two integer inputs num1 and num2 from the user. The program should perform the following operations and display the results:

  1. Calculate the sum of num1 and num2.
  2. Calculate the difference between num1 and num2.
  3. Calculate the product of num1 and num2.
  4. Calculate the quotient of num1 divided by num2 (integer division).
  5. Calculate the remainder of num1 divided by num2.

Write the program for the above requirements and test it by taking num1 = 10 and num2 = 3.

Answer:

import java.util.Scanner;

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

        System.out.print("Enter the value for num1: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the value for num2: ");
        int num2 = scanner.nextInt();

        int sum = num1 + num2;
        int difference = num1 - num2;
        int product = num1 * num2;
        int quotient = num1 / num2;
        int remainder = num1 % num2;

        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);
        System.out.println("Product: " + product);
        System.out.println("Quotient: " + quotient);
        System.out.println("Remainder: " + remainder);
    }
}

Explanation:

  1. The program starts by importing the Scanner class from the java.util package to read user input.
  2. It then declares a Scanner object to read the input from the user.
  3. The program prompts the user to enter the value for num1 using System.out.print statement.
  4. The value entered by the user is stored in the variable num1 using scanner.nextInt() method.
  5. Similarly, the program prompts the user to enter the value for num2.
  6. The value entered by the user is stored in the variable num2.
  7. The program calculates the sum of num1 and num2 using the + operator and stores the result in the variable sum.
  8. The program calculates the difference between num1 and num2 using the - operator and stores the result in the variable difference.
  9. The program calculates the product of num1 and num2 using the * operator and stores the result in the variable product.
  10. The program calculates the quotient of num1 divided by num2 using the / operator and stores the result in the variable quotient.
  11. The program calculates the remainder of num1 divided by num2 using the % operator and stores the result in the variable remainder.
  12. Finally, the program displays the results of the calculations using System.out.println statements.