Java Program - Arithmetic Operations¶
Concept Explanation¶
What is it?¶
Arithmetic operations are the basic mathematical calculations performed on numerical data. In Java, these are handled by arithmetic operators.
Why is it important?¶
Mathematical logic is the core of most programming tasks, from simple calculators to complex financial models and games.
Where is it used?¶
Everywhere! Calculating bills, determining player health in games, managing loops, and processing data all require arithmetic.
Algorithm¶
- Start
- Declare two variables (e.g.,
aandb). - Assign values to them.
- Apply operators:
+(Sum),-(Difference),*(Product),/(Quotient), and%(Remainder). - Display each result.
- End
Implementations¶
public class ArithmeticExample {
public static void main(String[] args) {
int a = 15;
int b = 4;
System.out.println("Number 1: " + a);
System.out.println("Number 2: " + b);
System.out.println("-------------------");
System.out.println("Sum (a + b): " + (a + b));
System.out.println("Difference (a - b): " + (a - b));
System.out.println("Product (a * b): " + (a * b));
System.out.println("Quotient (a / b): " + (a / b));
System.out.println("Remainder (a % b): " + (a % b));
}
}
Explanation¶
- Java
- Addition (+): Adds two operands.
- Subtraction (-): Subtracts the second operand from the first.
- Multiplication (*): Multiplies two operands.
- Division (/): Divides the first operand by the second. Note: Integer division discards decimals.
- Modulo (%): Returns the remainder after division.
Complexity Analysis¶
- Time Complexity: O(1)
- Space Complexity: O(1)
Flowchart¶
graph TD
A[Start] --> B[Initialize a, b]
B --> C[Calculate results]
C --> D[Print Addition]
D --> E[Print Subtraction]
E --> F[Print Multiplication]
F --> G[Print Division]
G --> H[Print Modulo]
H --> I[End]
Practice Problems¶
Easy¶
- Modify the program to accept user input using
Scanner.
Medium¶
- Implement a menu-driven calculator using a
switchstatement.
Interview Tips¶
- Explain the difference between integer division (
5 / 2 = 2) and floating-point division (5.0 / 2.0 = 2.5). - Understand operator precedence (PEMDAS).
"Mathematics is the language in which God has written the universe." - Galileo Galilei