### Experiment 3: Arithmetic Expressions

While simple expressions are sometimes useful, the process of computation involves the application of operators to operands. Java provides a number of arithmetic operators that can be applied to numeric operands, including:
 + addition, computes the sum of two (integer or real) operands - subtraction, computes the difference of two (integer or real) operands * multiplication, computes the product of two (integer or real) operands / division, computes the quotient of the division two (integer or real) operands % modulus, computes the remainder of the division of two integer operands

While addition, subtraction and multiplication are similar for integers and real numbers (and presumably well known to any reader of this manual), division and modulus are quite different, so let's spend some time exploring them.

1. Modify the output statement in the source program, to enable you to complete the following table, for int variables i and j, and double variables x and y (Hint: To speed things up, either do all of the values at once, or add an input statement that allows you to enter the values for i, j, x and y from the keyboard):

i

j

x

y

x / y

i / j

i % j

4

1

4.0

1.0

4

2

4.0

2.0

4

3

4.0

3.0

4

4

4.0

4.0

4

5

4.0

5.0

4

6

4.0

6.0

4

7

4.0

7.0

4

8

4.0

8.0

4

9

4.0

9.0

To understand integer division, it helps to revert to primary school and remember how your teacher taught you to divide when you only knew about integers, not real numbers:

```   "Four goes into nine two times, with a remainder of one."
```

For this reason, the % operator is sometimes called the remainder operator, but modulus is its "official" name.

2. Now, suppose that ABCD are the 4 digits of an integer value. With or without the computer, give the values of the following expressions in terms of A, B, C and D:

```   ABCD / 1     = __________            ABCD % 1     = __________
ABCD / 10    = __________            ABCD % 10    = __________
ABCD / 100   = __________            ABCD % 100   = __________
ABCD / 1000  = __________            ABCD % 1000  = __________
```

If you look for the pattern, you can see that integer division and remaindering can be used to "tear apart" integer values.

3. How can integer remaindering be used to determine if an integer i is evenly divisible by an integer j?

4. How can integer remaindering be used to determine if an integer i is even? If i is odd?

From this exercise, you should see that the five arithmetic operators in Java allow you to build expressions using the four normal arithmetic operations, as well as the "remainder" operation from integer division, which is surprisingly useful.

Back to the Exercise List

Forward to the Next Experiment