Menu
Coddy logo textTech

Modulo Operator

Part of the Fundamentals section of Coddy's Ruby journey — lesson 12 of 88.

The modulo operator (%) returns the remainder after division. When you divide one number by another, modulo gives you what's left over rather than the quotient.

For example, when dividing 17 by 5, you get 3 with a remainder of 2. The modulo operator captures that remainder:

remainder = 17 % 5  # 2
leftover = 10 % 3   # 1
even_check = 8 % 2  # 0

One of the most common uses of modulo is checking if a number is even or odd. If a number divided by 2 has a remainder of 0, it's even. If the remainder is 1, it's odd:

14 % 2  # 0 (even)
9 % 2   # 1 (odd)

Modulo is also useful for checking divisibility. When the result is 0, it means the first number is perfectly divisible by the second. This becomes especially handy when you need to determine if a number is a multiple of another.

challenge icon

Challenge

Easy

You are provided with the following variables:

total_items = 23
items_per_box = 5

Use the modulo operator to calculate and display the following values, each on a separate line:

  1. The number of items that won't fit in a complete box (remainder when dividing total_items by items_per_box)
  2. The result of 17 % 4
  3. The result of 100 % 10
  4. The result of 15 % 2 (to check if 15 is odd)
  5. The result of 24 % 6 (to check if 24 is divisible by 6)

Cheat sheet

The modulo operator (%) returns the remainder after division:

remainder = 17 % 5  # 2
leftover = 10 % 3   # 1
even_check = 8 % 2  # 0

Common uses include checking if a number is even or odd:

14 % 2  # 0 (even)
9 % 2   # 1 (odd)

When the result is 0, the first number is perfectly divisible by the second.

Try it yourself

# Variables provided
total_items = 23
items_per_box = 5

# TODO: Write your code below
# Use the modulo operator (%) to calculate and print:
# 1. Remainder when dividing total_items by items_per_box
# 2. Result of 17 % 4
# 3. Result of 100 % 10
# 4. Result of 15 % 2
# 5. Result of 24 % 6
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals