Menu
Coddy logo textTech

Modulo Operator

Part of the Fundamentals section of Coddy's Swift journey — lesson 17 of 86.

The modulo operator (%) returns the remainder after dividing one number by another. While division tells you how many times a number fits into another, modulo tells you what's left over.

let remainder = 10 % 3  // 1
print(remainder)        // 1

Here, 3 fits into 10 exactly 3 times (which equals 9), leaving a remainder of 1. This operator is incredibly useful for determining if a number is divisible by another — when the remainder is 0, the division is exact.

let evenCheck = 8 % 2   // 0 (8 is even)
let oddCheck = 7 % 2    // 1 (7 is odd)

A common use case is checking whether a number is even or odd. If a number modulo 2 equals 0, it's even; otherwise, it's odd. You'll also find modulo helpful for tasks like cycling through values or wrapping numbers within a range.

challenge icon

Challenge

Easy
Write a function getRemainder that takes two integers dividend and divisor, and returns the remainder when the dividend is divided by the divisor.

Use the modulo operator to calculate what's left over after division.

Parameters:

  • dividend (Int): The number being divided
  • divisor (Int): The number to divide by

Returns: The remainder after dividing dividend by divisor (Int)

Cheat sheet

The modulo operator (%) returns the remainder after dividing one number by another:

let remainder = 10 % 3  // 1
print(remainder)        // 1

When the remainder is 0, the division is exact (the number is divisible):

let evenCheck = 8 % 2   // 0 (8 is even)
let oddCheck = 7 % 2    // 1 (7 is odd)

Common use case: checking if a number is even or odd. If number % 2 equals 0, it's even; otherwise, it's odd.

Try it yourself

func getRemainder(dividend: Int, divisor: Int) -> Int {
    // Write code here
}
quiz iconTest yourself

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

All lessons in Fundamentals