Menu
Coddy logo textTech

Integer Division and Modulo

Part of the Fundamentals section of Coddy's R journey — lesson 13 of 78.

Beyond basic division, R provides two special operators for working with whole numbers: integer division and modulo.

Integer division (%/%) divides two numbers and returns only the whole number part, discarding any remainder:

17 %/% 5  # Returns 3 (not 3.4)

Think of it as asking "how many complete times does 5 fit into 17?" The answer is 3 complete times.

Modulo (%%) returns the remainder after division:

17 %% 5  # Returns 2 (the remainder)

This tells you what's left over after dividing 17 by 5. Since 5 goes into 17 three times (15), the remainder is 2.

These operators are incredibly useful in programming. The modulo operator is commonly used to check if a number is even or odd - if number %% 2 equals 0, the number is even. Integer division helps when you need to distribute items into groups or convert units like minutes to hours.

challenge icon

Challenge

Easy

Convert a total number of minutes into hours and remaining minutes using integer division and modulo.

You are provided with the following variable:

total_minutes <- 197

Using the integer division and modulo operators:

  1. Create a variable called hours that stores how many complete hours are in total_minutes
  2. Create a variable called remaining_minutes that stores the leftover minutes after extracting the complete hours

Use the print() function to display hours and remaining_minutes in that exact order.

Cheat sheet

R provides two special operators for working with whole numbers:

Integer division (%/%) returns only the whole number part, discarding any remainder:

17 %/% 5  # Returns 3

Modulo (%%) returns the remainder after division:

17 %% 5  # Returns 2

Common use cases include checking if a number is even (number %% 2 == 0) and converting units (e.g., minutes to hours).

Try it yourself

# Given variable
total_minutes <- 197

# TODO: Write your code below
# Use integer division (%/%) to calculate complete hours
# Use modulo (%%) to calculate remaining minutes


# Output the results
print(hours)
print(remaining_minutes)
quiz iconTest yourself

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

All lessons in Fundamentals