Integer division and Math.mod
Write Apex · Beginner · 10 min · Runs in your Salesforce Developer org · Free
Scenario. An event coordinator sells seats in packs of five and needs a reliable order summary.
Count full seat packs with integer division and leftover seats with Math.mod for two order sizes.
What you will learn
Use Integer for whole counts. Dividing one Integer by another keeps only the whole part, so 17 / 5 is 3. Math.mod(a, b) gives what is left over.
// 3 full boxes
Integer boxes = 17 / 5;
// 2 items left over
Integer loose = Math.mod(17, 5);
Gotcha. Integer division drops the fraction. It does not round, so 19 / 5 is 3, not 4. Use Decimal when the fraction matters.
The task
Work out full seat packs and leftover seats for orders of 17 and 20 seats.
Examples:
- 17 seats in packs of 5 →
Case A packs: 3andCase A leftover: 2 - 20 seats in packs of 5 →
Case B packs: 4andCase B leftover: 0
Requirements:
- Compute full packs by dividing
seatsSoldbypackSize. - Compute leftover seats with
Math.mod(seatsSold, packSize). - Print
Case A packs:andCase A leftover:for 17 seats. - After the starter sets
seatsSold = 20;, compute both again and printCase B packs:andCase B leftover:from the new values.
Starter code
Integer seatsSold = 17;
Integer packSize = 5;
// Case A: 17 seats
// Case B: 20 seats
seatsSold = 20;
When it passes
17 seats give 3 packs and 2 leftover seats. 20 seats give 4 packs and 0 leftover seats.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.