Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Operators  ›  Lesson

Arithmetic Operators

Operators 12 minThe arithmetic operators work on numbers, the result takes the wider operand's type, whole-number division drops the remainder that % returns, and a var can be updated with forms like +=.

Arithmetic Operators

The logbook shows pace as minutes and seconds per kilometre, like 5:06, not as 306 seconds. Turning one into the other takes three arithmetic operators and a clear idea of what each one keeps.

The rule

/ keeps the whole part, % keeps the leftover; the wider type wins.

Scala's arithmetic operators are the familiar ones:

Operator Meaning Example Result
+ add 5.0 + 8.5 13.5
- subtract 10 - 3 7
* multiply 12 * 400 4800
/ divide 306 / 60 5
% remainder 306 % 60 6
  • With two whole numbers, / gives the whole part and throws away the rest, and % gives exactly what / threw away. 306 / 60 is 5 and 306 % 60 is 6, because 5 × 60 + 6 = 306.
  • If either side is a Double, the result is a Double: 306 / 60.0 is 5.1.
  • The sign of % follows the left side: -7 % 3 is -1.
  • Whole-number division by zero throws an ArithmeticException. Decimal division by zero does not: 10.0 / 0 is Infinity.

A var can be updated in place with +=, -=, *=, /= and %=:

var weekKm = 0.0
weekKm += 5.0     // same as weekKm = weekKm + 5.0
weekKm += 8.5     // now 13.5

There is no ++ or -- in Scala. laps++ is a compile error; write laps += 1.

The + operator also joins strings: "Asha" + " ran" is "Asha ran".

The shortcut

For anything counted in groups of a fixed size, such as 60 seconds to a minute, use the pair trick: total / size gives the big units and total % size gives the leftover small units. Check with big × size + leftover = total.

Turning 1530 seconds for 5 km into a paceStep 1 of 4
  1. Seconds per kilometre

    Both are whole numbers: 1530 / 5 is 306 seconds for each kilometre.

The trap: letting a Double into the pair trick. 306.0 / 60 is 5.1, which means 5.1 minutes, not 5 minutes and 10 seconds.

Drills

Answer fast — trust the rule.

quick drill

What is 1530 / 60?

quick drill

What is 1530 % 60?

quick drill

What is -7 % 3 in Scala?

quick drill

Given var laps = 12, how do you add one lap?

quick drill

What do 10 / 0 and 10.0 / 0 do?

Remember

  • / keeps the whole part of a whole-number division and % keeps the leftover; any Double makes the result a Double.
  • Pair trick: total / size and total % size, checked by big × size + leftover.
  • Trap: Scala has no ++, and a Double in the pair trick gives decimal minutes.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainFormatting a pace

A 10 km run took 3125 seconds. Using only whole-number arithmetic, work out the pace per kilometre as minutes and seconds, show each expression and its result, and explain why a Double would give a misleading answer.