The task
A coffee shop gives one free cup for every 6 cups you buy, so 6 paid cups bring 7 in total. The variable cups holds the number of cups you paid for. The exercise is to print the total number of cups you receive, paid and free together. If you paid for 12 cups, you receive 2 free ones, and the total is 14.
Approach
The total has two parts:
- the cups you paid for, which is
cups; - the free cups, one for each complete group of 6 paid cups.
The second part is a "how many times does 6 fit into cups" question. That is the quotient of cups divided by 6, and with Int values the operator / computes it. A partial group earns nothing, and integer division drops exactly that partial group. For example, 13 cups hold two complete groups of 6 and one cup left over, so 13 / 6 is 2.
Step by step
- Compute the free cups:
cups / 6. With 213 paid cups, 213 / 6 is 35. - Add them to the paid cups:
cups + cups / 6, which is 213 + 35 = 248. - Print the sum with
println.
No parentheses are needed. The division runs before the addition, so Scala reads the expression as cups + (cups / 6).
The solution in Scala
val cups: Int = 213
println(cups + cups / 6)
The output is:
248
Why integer division is the right tool
The type of cups is Int, and 6 is an Int literal, so cups / 6 is an Int division and has no fractional part. If cups were a Double, then cups / 6 would give 35.5 for 213 paid cups, and you would need to round down yourself. Half a free cup is not something the shop can hand out.
The cups left over in the last, incomplete group are cups % 6. For 213 that is 3. These cups are paid for, and they stay in the total through the cups + part of the expression. They just do not earn a free cup.
Edge cases and common mistakes
- Fewer than 6 cups. With 5 paid cups,
5 / 6is 0, so the total is 5. No free cup appears early. - Exactly 6 cups.
6 + 6 / 6is 7, as the offer says. - Zero cups. The total is 0.
- Multiplying groups by 7.
cups / 6 * 7counts only complete groups and ignores the leftover paid cups. For 213 it prints245instead of248. - Dividing by 7. The free cup is earned per 6 paid cups, so the divisor is 6.
- Counting the free cups as paid. Free cups do not earn more free cups. The count is based on
cups, not on the running total.
Key takeaways
- Integer division counts complete groups:
cups / 6. - The leftover part of an incomplete group is dropped by
/and available as%. - The total is the paid cups plus the free ones:
cups + cups / 6.
