Home

AAP-2.C Evaluate expressions that use arithmetic operators +, -, *, /, and MOD

Understanding Arithmetic Operators in Java

Welcome to your introduction to arithmetic operators in Java! In this lesson, we'll cover the basic arithmetic operators you'll use to perform calculations in your programs. These operators are similar to the math you do every day but are written in a way that the computer understands. Let's dive in!

1. Explanation of the Concept

Arithmetic Operators

In Java, arithmetic operators are used to perform basic math operations. Here are the main ones you need to know:

Examples

Let's see how these operators work with some simple examples:

int sum = 5 + 3; // sum is 8
int difference = 9 - 4; // difference is 5
int product = 7 * 6; // product is 42
int quotient = 20 / 4; // quotient is 5
int remainder = 10 % 3; // remainder is 1

2. Real-World Example

Let's say you went shopping and bought several items. You want to calculate the total cost, find out how much money you will have left after spending a certain amount, or divide the total cost among friends. Arithmetic operators help us solve these problems.

For example, if you bought items costing $15, $22, and $9, you can find the total cost like this:

int totalCost = 15 + 22 + 9; // totalCost is 46

3. A Full Program in Java

Here is a simple Java program that demonstrates the use of arithmetic operators. This program calculates the total price of items in a shopping cart and shows how much each person needs to pay if the cost is split among friends.

public class ShoppingCart {
    public static void main(String[] args) {
        // Prices of items in the cart
        int item1 = 15;
        int item2 = 22;
        int item3 = 9;

        // Calculate the total cost
        int totalCost = item1 + item2 + item3;
        System.out.println("Total cost: $" + totalCost);

        // Number of friends sharing the cost
        int friends = 3;

        // Calculate the cost per friend
        int costPerFriend = totalCost / friends;
        System.out.println("Cost per friend: $" + costPerFriend);

        // Calculate the remainder if the cost is not evenly divisible
        int remainder = totalCost % friends;
        System.out.println("Remainder when divided among friends: $" + remainder);
    }
}

Explanation:

4. Programming Problem

Now it's your turn to practice using arithmetic operators!

Problem:

Write a Java program that calculates the following:

  1. The total score of three exams.

  2. The average score.

  3. The remainder when the total score is divided by the number of exams.

Instructions:

Example:

If the scores are 85, 90, and 78, your output should be:

Total score: 253
Average score: 84
Remainder: 1

Give it a try and see how well you can use arithmetic operators in your program. Happy coding!