Programming Exercise: Basic Arithmetic Operations
This exercise reinforces your knowledge of:
- Reading integer input using the
Scannerclass. - Performing the four basic arithmetic operations.
- Using
System.out.print()to format results on a single line, separated by spaces.
Problem Statement:
Given two integers, A and B, as input. Print the results of the following four operations in the specified order: addition (A+B), multiplication (A*B), subtraction (A-B), and division (A/B).
| Constraint | Value |
| Input Format | Two separate lines, each containing a single integer. |
| Output Format | A single line containing the four results, separated by a single space. |
Example:
| Input | Output | Explanation |
| A: 4 B: 5 | 9 20 -1 0 | Addition 4 + 5 = 9 Multiplication 4 × 5 = 20 Subtraction 4 − 5 = −1 Division 4 / 5 = 0 |
Java Solution and Breakdown
The solution uses the Scanner for input and relies on System.out.print() (or a single System.out.println() with concatenation) to ensure all results stay on the same line, separated by spaces.
1. Complete Java Code
import java.util.Scanner;
public class BasicArithmetic {
public static void main(String[] args) {
// 1. Initialize the Scanner object for input.
Scanner sc = new Scanner(System.in);
// 2. Read the two integers, A and B.
int A = sc.nextInt();
int B = sc.nextInt();
sc.close();
// 3. Calculate and print the four results on a single line.
// We use System.out.print() for each result, followed by a space,
// except for the last one.
// A + B (Addition)
System.out.print(A + B);
System.out.print(" "); // Separator
// A * B (Multiplication)
System.out.print(A * B);
System.out.print(" "); // Separator
// A - B (Subtraction)
System.out.print(A - B);
System.out.print(" "); // Separator
// A / B (Division)
// Integer division results in an integer (truncates the decimal part).
System.out.println(A / B);
// System.out.println() is used here to end the entire output line.
}
}
2. Explanation of Key Concepts
| Concept | Code Section | Description |
| Integer Input | int A = sc.nextInt(); | The sc.nextInt() method is used to read and store the user’s input as an integer (int). |
| Arithmetic Operators | A + B, A * B, etc. | These are the standard Java arithmetic operators. Since A and B are int types, the results will also be integers. |
| Integer Division | A / B | When dividing two integers (int), Java performs integer division, meaning any fractional part is truncated (discarded). For example, $4/5$ results in $0$. |
| Single-Line Output | System.out.print(" ") | To ensure all four numbers are on the same line, the System.out.print() method is used for the first three results. A space (" ") is explicitly printed after each result to act as the required separator. |
| Line End | System.out.println(A / B); | The final result uses System.out.println() to print the value and then move the cursor to the next line, effectively ending the program’s output. |
