ApexSensei

Drills › Write Apex

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: 3 and Case A leftover: 2
  • 20 seats in packs of 5 → Case B packs: 4 and Case B leftover: 0

Requirements:

  1. Compute full packs by dividing seatsSold by packSize.
  2. Compute leftover seats with Math.mod(seatsSold, packSize).
  3. Print Case A packs: and Case A leftover: for 17 seats.
  4. After the starter sets seatsSold = 20;, compute both again and print Case B packs: and Case 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.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Quick win: is the name blank? · Money is a Decimal ›