A girl and a robot thinking together

Think together · Start with a story

There are 14 pieces of candy, and each bag holds 4. After filling as many whole bags as possible, how many pieces are left on the table?

Break down the process

Follow the numbered steps, then explain them in your own words
  1. First bag10 pieces remain
  2. Second bag6 pieces remain
  3. Third bag2 pieces remain
  4. RemainderNot enough for another bag

For the non-negative integers in this example, 14 % 4 is 2: the remainder after division by 4.

The operator can help check divisibility and cycle through labels. For example, after labels 0, 1, and 2, (2 + 1) % 3 returns to 0.

01What does % calculate?

In C++, % calculates the remainder for integer operands:

17 % 5   // 2

Because 17 = 5 × 3 + 2.

02How do you check whether a number is odd or even?

if (n % 2 == 0) {
    // even
}

If a number divides evenly by 2, its remainder is 0; otherwise, it is odd.

03How do you check whether a number divides evenly?

To check whether a is divisible by b, test:

a % b == 0

For example, 20 % 5 == 0, so 20 is divisible by 5.

04Why is % so useful for cycling through positions?

If there are 7 positions and you want their labels to repeat:

position = step % 7;
0123456back to 0

This is common with weekdays, circular arrays, and repeating animations.

05Be careful with negative numbers

In C++, integer division truncates toward zero, and the remainder satisfies:

a == (a / b) * b + a % b

Therefore:

-7 % 3   // -1
 7 % -3  //  1

06Can you use % with decimals?

C++'s built-in % operator works with integer types. It cannot be used directly with double.

Floating-point remainders have other functions, such as std::fmod. It is not the same operator as integer %.

What you have learned

  • In C++, % calculates the remainder of integer division.
  • It is often used to check odd/even, divisibility, and cycling positions.
  • The divisor must not be 0.
  • Remainders with negative numbers follow C++ integer-division rules and are not necessarily non-negative.
  • The built-in % cannot be used directly with floating-point numbers.

Next: Comparing Two Numbers

Your turn to try

There are 17 pieces of candy and 5 per bag. What is 17 % 5?

Ready? Open to see the explanation

You can fill 3 bags, using 15 pieces, with 2 left over. So the remainder is 2. Check by multiplying the quotient by the divisor, then adding the remainder.