Expressions and Arithmetic Operators

Site: Saylor Academy
Course: CS101: Introduction to Computer Science I
Book: Expressions and Arithmetic Operators
Printed by: Guest user
Date: Tuesday, June 18, 2024, 8:19 AM

Description

Read this chapter, which discusses arithmetic operations in greater detail along with solving expressions with mixed data types.

1. Expressions and Arithmetic Operators

This chapter continues the discussion of arithmetic expressions, integer operators, and floating point operators.

Chapter Topics:

        • Review of Expressions
        • Arithmetic Operators
        • Integer operators
        • Floating point operators
        • Mixed Floating point and Integer Expressions
        • Constants

Question 1:

(Review: ) Is the following correct?

    13 * 6 -

Source: Bradley Kjell, http://programmedlessons.org/Java9/chap10/ch10_01.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial 3.0 License.

2. Expressions


Answer:

No.

Expressions

The literals (the integers) and the operators are out of order in the above incorrect expression. (One legal arrangement is    13 * -6     for 13 times minus 6.)


Expressions contain operators and operands. You already know what an operator is (a symbol such as +-*, or / that calls for an arithmetic operation).

An operand
The parts of an expression must be arranged correctly. The syntax of Java describes the correct arrangements. The rules for correct Java expressions are nearly the same as for algebra:
  1. Each operator must have the correct number of operands.

    • Multiplication *, Division /, Addition +, Subtraction - should have two operands, one on each side.
    • Negation - and unary plus + should be followed by one operand.
  2. Parentheses () can surround a legal expression to make it an operand.

In 13 - 5 the 13 and the 5 are the operands and the - is the operator.

In Java expressions, operators and operands must be explicit. In

14*sum 

14 and sum are the operands. The star for multiplication must be present. The expression 14sum is incorrect.

In a correct expression, parentheses are balanced. Parentheses are balanced when they form matching pairs. Each left parenthesis has a matching right parenthesis. Balanced pairs of parentheses can be nested within other balanced pairs.

For example, the following are balanced:

      • ( )
      • ( ( ) ( ) )
      • ( ( ) ) ( )
      • ( ) ( ( )( ) ) ( )

The following are NOT balanced:

      • (
      • ( ( ( ) )
      • ( ( ) ) ( ))
      • ( ) ( )( ) ) ( )

The details of expression syntax are in the Java documentation, should you care to dig through it. The best way to learn these rules is to study some examples.


Question 2:

Which minus sign in the following stands for "subtraction" and which stands for "negation"?

    -23 - 3

3. Practice


Answer:

    -23 - 3
The first minus sign is "negation" and the second minus sign is "subtraction". The spaces in the
expression emphasize the different roles, but are not necessary. The following expression is
equivalent:
    -23-3

Practice

Examine the following expressions. Assume that each variable has already been correctly declared. Decide if the expression is correct, then click on the button.


Expression Correct or Not Correct? Expression Correct or Not Correct?
25 25 - value
2( a - b ) (a-b) * (c-d)
A - b/c + D -sum + partial
((x+y) / z) / (a - b) ((m-n) + (w-x-z) / (p % q)


Question 3:

Are arithmetic expressions the only kind of expression?

4. Arithmetic Operators


Answer:

No. For example, the following is also an expression:
    "This is" + " a string" + " expression"
The above expression creates a new string that is the concatenation of all the strings.

Arithmetic Operators

Arithmetic expressions are especially important. Java has many operators for arithmetic. These operators can be used on floating point numbers and on integer numbers. (However, the % operator is rarely used on floating point.)

For instance, / means integer division if both operands are integers, and means floating point division if one or both operands are floating point.

Arimetic rules

For example, with 16 bit short variables, the arithmetic is done using 32 bits:

short x = 12; // 16 bit short
int result; // 32 bit int

result = x / 3; // arithmetic will be
result = x / 3; // arithmetic will be
// done using 32 bits

The expression   x / 3   divides a 32-bit value 12 by a 32-bit value 3 and puts the 32-bit answer in result. The literal 3 automatically represents a 32-bit value.

Operator   
Meaning
precedence   
-
unary minus
highest
+
unary plus
highest
*
multiplication
middle
/
division
middle
%
remainder
middle
+
addition
low
-
subtraction
low

Question 4:

Look at the example above. Does it really matter that 12 was converted to 32 bits?

5. Another Example


Answer:

Not in this example. But sometimes it does, when values are close to the limit of what can be represented in 16 bits.

Another Example

Here is another example:

short x = 12;
short y = 3;
short value;

value = x / y;

The expression   x / y   divides a 32-bit value 12 by a 32-bit value 3, even though the variables x and y are only 16 bits wide. The calculation produces a 32-bit result. Because the 32-bit result does not fit in the 16 bits of value the compiler will not compile the last statement. This can be completely baffling when it happens to you.

C:\Private>javac ShortStuff.java
ShortStuff.java:9: possible loss of precision
found : int
required: short
result = x / y;
^
1 error C:\Private>


For professional programmers, details like these are sometimes important. But for most programs, use int or long for integers and double for floating point. This will keep you out of trouble (usually). If you can't avoid the problem, use a type cast, as described in a future chapter.


Question 5:

Do you expect that a modern electronic calculator will give you the same answer as Java for
the expression  (31.5 - 12)/4.1 ?

6. Weird Integer Arithmetic


Answer:

Yes. The meaning of operators and parentheses is about the same in electronic calculators and in Java. But Java does integer and floating point math, and sometimes this can make a difference.

Weird Integer Arithmetic

The division operator / means integer division if there is an integer on both sides of it. If one or two sides has a floating point number, then it means floating point division.

The result of integer division is an integer. Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is.

There is a difference between what Java does and what a calculator does. A calculator does floating point arithmetic for the expression:

7/4

A calculator will show this as 1.75. Java regards this as an integer division and gives you:

7/4 = 1

because 4 goes into 7 just once. The result is not rounded up to 2. The remainder after division, 3, is simply dropped.

A handy way to think about integer division is to think about forming groups of pebbles. Say that you had twelve pebbles and wished to arrange them into groups of five. You can form two groups of five pebbles (with two pebbles left over).

12/5 = 2

Integer operations and floating point operations are both very common in programs. It is important to be clear about them.

(Advanced Placement Computer Science students are expected to understand integer division very well.)



Expression
Result
Expression
Result
12  3
12  6
12  7
11  2
11.0  5.0
 2
1.0  2.0
2.0  4.0


Question 6:

What is the result of evaluating the following expression:

    199/50

7. Mixed Integer and Float


Answer:

199/50 = 3 

50 goes into 199 three times and the remainder, 49, is dropped.

Mixed Integer and Float

Integer division is easy enough to see when it is by itself, but here is a more confusing case of the same thing:

1.5 + 7/2

The division is done first because / has higher precedence than +. The result of the division, 3, is an integer. Now the floating point 1.5 is added to integer 3 to get floating point 4.5.

Integer arithmetic might be used in some parts of an expression and not in others, even though the final value of the expression is floating point.

This can be very confusing. The temptation is to see a floating point value in an expression and then mistakenly do floating point with every operation. For example,

( (3/2)*5.7 ) + 9/10

This evaluates to 5.7. Here is what happens, step-by-step:

( (3/2)*5.7 ) + 9/10
( 1 *5.7 ) + 9/10
5.7 + 9/10
5.7 + 0
5.7

Question 7:

What is the result of evaluating the following expression:
    1/2 + 1/2

8. Copy-and-Paste Program


Answer:

    1/2 + 1/2 == 0

It looks as though this is a mistake, but no: each 1/2 calls for integer division,
resulting in an integer 0. The two zeros are added to get the final answer, zero.

Copy-and-Paste Program

If you really want to add one half to one half write 1.0/2.0 + 1.0/2.0 because now the decimal points make each number a double. If just one of the operands of an operator is double, then the other operand is automatically promoted to a double. Here is some Java code that illustrates these points:

public class IntegerDivision
{
public static void main ( String[] args )
{
System.out.println("The result is: " + (1/2 + 1/2) );
}
}

Copy this program to a file IntegerDivision.java, compile, and run it. (Or use one of the web-page Java compilers mentioned in the Table of Contents.) Make some changes to the program using your text editor then run it to see the effect.

Notice the parentheses around   (1/2 + 1/2). These are necessary so that the arithmetic is done first, then the result is converted to characters and appended to the string.

Edit and run the program to see each of these variations:


Expression?Result
(1/2 + 1/2)
(1.0/2 + 1/2)
(1/2.0 + 1/2)
(1/2 + 1.0/2.0)
(1/2.0 + 1.0/2.0)


Question 8:

What is the value of the expression 99/100 ?

9. The Sign of the Result


Answer:

99/100 = 0
It is tempting to think that the answer must be 1, but it is not. 100 goes into 99 zero times, so that is the result.

The Sign of the Result

The normal rules of arithmetic determine the sign of the result of division:

+num/+div == +result
-num/+div == -result
+num/-div == -result
-num/-div == +result

Here are some examples:

17/5 == 3
-17/5 == -3
17/-5 == -3
-17/ -5 == 3

Of course, you are eager to practice this right away! Mentally (or with scratch paper) decide on the value of each expression. Then click on the button to see the correct value.

Expression
Result
Expression
Result
12  3
-12  3
-10  5
10  -6
129  100
-19  -10
17  2
-19  2


Question 9:

What is the value of the expression 3/4 ?

10. Subexpressions


Answer:

0

There is no integer negative zero. So -3/4 evaluates to zero.

Subexpressions

Most of the operators we are interested in take two operands. In each of the following examples the operator has two operands:


34 + 12
19/3
90 - sum
val * x

However, unary operators take just one operand:


+93
-72
+sum
-Math.PI

A binary operator will always have exactly two operands. However, sometimes one or both operands of a binary operator is a subexpression.

subexpression

Sometimes a subexpression is a constant, like "8". Any expression can be a subexpression of a larger expression. In the following, both operands of the red operator are subexpressions.


2*3 + 8
(x - y) / 2.3
(sum - 2) * (sum + 3)

When an expression is evaluated, the subexpressions must be evaluated first before the operator that joins them can be applied.

Gotcha: a subexpression may call for integer arithmetic, even though the larger expression calls for floating point. (I keep stressing this, but that is because people get caught by this all the time.)

Question 10:

In an expression like 34.12 / 68.0 how do you know if the / means
 integer division or means floating point division ?

11. Mixed Floating Point and Integer Expressions


Answer:

You look at the operands of the operator.

Mixed Floating Point and Integer Expressions

But what if one operand is an integer and the other is a floating point? The rule is:


For example, the following are integer operations (assume that a and b are int variables):

12 * b
a - 2
56%a

Each operation in the following expressions is a floating point operation (assume that a and b are int variables, and that x and y are floating point variables):

x * b
(a - 2.0)
56*y

In complicated expressions, an operand of a particular operator might be a subexpression. But the rule still applies: if one or both operands is a floating point type then the operation is floating point. In the following, each / operation is floating point:

(12.0 * 31) / 12
(a - 2.0) / b
56*x/3

In that last example, the 56*x is a floating point subexpression that becomes an operand for the division operator. (Because * and / have equal precedence, the evaluation is done from left to right.)

Question 11:

What type (integer or floating point) of operator is the / in the following:

    (12 + 0.0) / 7

12. Mixed Expression Gotcha!


Answer:

Floating point. Adding floating point 0.0 to the integer 12 results in a floating point 12.0.
Now the division is floating point because one of its operands is floating point.

Mixed Expression Gotcha!

Look again at the rule:

If both operands are integers, then the operation is an integer operation. If any operand is floating point, then the operation is floating point.

The rule has to be applied step-by-step. Consider this expression:

( 1/2 + 3.5 ) / 2.0

What is the result? Apply the rules: innermost parentheses first. Within the parentheses the highest precedence operator first:

( 1/2 + 3.5 ) / 2.0
---
do first

Since both operands are integer, the operation is integer division, resulting in:

( 0 + 3.5 ) / 2.0

Now continue to evaluate the expression inside parentheses. The + operator is floating point because one of its operands is, so the parentheses evaluates to 3.5:

3.5 / 2.0

Finally do the last operation:

1.75

This is close to the result that you might have mistakenly expected if you thought both divisions were floating point. An insidious bug might be lurking in your program!


Question 12:

Surely you want to try another!

    int a = 6;
    double b = 12.0;

What is the result of evaluating this expression:

    ( a/b + 4) / 2

13. Fun with Mixed Expressions


Answer:

(a/b + 4) / 2 == (6/12.0 + 4) / 2 == (0.5 + 4) / 2 == 4.5/2 == 2.25

Fun with Mixed Expressions

Examine each expression in the following list. Decide if the operator in the button is an integer operation or a floating point operation. Then click on the operator to see if you are correct.

12  35
5.6  -14
( 12 + 0.01 )  2
( 18.0 - 23.3 ) / ( 73  23 )
-19.45  2.93
( 34 - 12 )  ( 9 / 10 ) + 1.2
 16 + 3.5

Note: These questions ask if the operator is floating point or integer. The value of the complete expression may be of a different type than one of its operators.


Question 13:

What is the remainder after dividing 13 by 5 (with integer division)?

If you have 13 pebbles and form two groups of 5 pebbles from them, how many pebbles are left over?

14. Remainder Operator


Answer:

3

Remainder Operator

You may recall how in grade school you did division like this:

13 divided by 5

13 / 5 == 2 with a remainder of 3.

This is because 13 == 2*5 + 3.

The symbol for finding the remainder is % (percent sign). If you look in the operators, table of table of operators you will see that it has the same precedence as / and *. Here is a program:


public class RemainderExample
{
public static void main ( String[] args )
{
int quotient, remainder; quotient = 17 / 3;
remainder = 17 % 3;

System.out.println("The quotient : " + quotient );
System.out.println("The remainder: " + remainder );
System.out.println("The original : " + (quotient*3 + remainder) );
}
}


Copy this program to a file and play with it. Change the 17 and 3 to other numbers and observe the result.

Question 14:

Will the following always print out the original integer, regardless of what it was?

    System.out.println("The original : " + (quotient*3 + remainder) );

15. Taking an Integer Apart


Answer:

Yes

Taking an Integer Apart

The integer division operator / and the remainder operator % take an integer apart.

theInteger / divisor arrow quotient

theInteger % divisor arrow remainder

The original integer can be put back together again:

quotient * divisor + remainder  arrow theInteger

In many calculations, it is convenient to do everything with integers, so both / and % are needed.


Question 15:

If you exchange 372 pennies for dollar bills, how many bills do you get? How many pennies are left over?

16. Practice with Remainder Operator


Answer:

  • Number of dollar bills is 372 / 100 == 3
  • Left over pennies is 372 % 100 == 72

Practice with Remainder Operator

For positive integers, INT % X means to fit as many X as you can into INT, and then the left over amount is the value of the expression. Try that with the following:

ExpressionResultExpressionResult
 3 5
10  510  6
129  1001999  100
17  218  2


Question 16:

If X is odd, what is X % 2?

17. Remainder with Negative Integers


Answer:

One. This is a common programming trick. Often you need to know the oddness and evenness of an integer

Remainder with Negative Integers

The remainder operator can be used with negative integers. The rule is:

  1. Perform the operation as if both operands were positive.
  2. If the left operand is negative, then make the result negative.
  3. If the left operand is positive, then make the result positive.
  4. Ignore the sign of the right operand in all cases.

For example:

17 %  3 == 2     -17 %  3 == -2     
17 % -3 == 2 -17 % -3 == -2

From the two pieces (the quotient and the remainder) the original integer can be put back together:

quotient * divisor + remainder arrow the Integer

For example,

-17 / 3 == -5  ;   -17 %  3 == -2  
(-5) * 3 + (-2) = -15 + (-2) = -17

You may wish to practice with the following:



Expression
Result
Expression
Result
7 -3
-7 5
-10 5
10 -6
-129 100
-1999 -100
-17 2
-18 2

Question 17:

Five pirates find a chest of 123 gold coins and wish to divide the 123 coins evenly among themselves. How many coins does each pirate get?

The parrot gets any leftover coins. How many coins does the parrot get?

18. Constants


Answer:

123 coins / 5 pirates is 24 coins per pirate.

123 % 5 is 3 coins left over for the parrot.

Constants

Often in a program you want to give a name to a constant value. For example you might have a tax rate of 0.045 for durable goods and a tax rate of 0.038 for non-durable goods. These are constants, because their value is not going to change during a run of the program. It is convenient to give these constants a name. This can be done:

public class CalculateTax
{
  public static void main ( String[] arg )
  {
    final double DURABLE = 0.045;
    final double NONDURABLE = 0.038;

    . . . . . .
  }
}


Now the constants can be used in expressions like:

taxamount = gross * DURABLE ;

But the following is a syntax error:

// try (and fail) to change the tax rate.

DURABLE = 0.441;   

In your programs, use a named constant like DURABLE rather than using a literal like 0.045. There are two advantages in doing this:

  1. Constants make your program easier to read and check for correctness.
  2. If a constant needs to be changed (for instance if the tax rates change) all you need to do is change the declaration of the constant. You don't have to search through your program for every occurrence of a specific number.


Question 18:

Could an ordinary variable be used to give a value a name? What is another advantage of using final?

19. End of the Chapter


Answer:

Yes. But final prevents any accidental change to a constant.

End of the Chapter

You have finally reached the end of the chapter. Click on a subject that interests you to go to where it was discussed.