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 # 0One 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
EasyYou are provided with the following variables:
total_items = 23
items_per_box = 5Use the modulo operator to calculate and display the following values, each on a separate line:
- The number of items that won't fit in a complete box (remainder when dividing
total_itemsbyitems_per_box) - The result of
17 % 4 - The result of
100 % 10 - The result of
15 % 2(to check if 15 is odd) - 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 # 0Common 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 % 6This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False