Menu
Coddy logo textTech

Modulo Operator

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 20 of 93.

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

fun main() {
    println(10 % 3)  // Prints: 1 (10 = 3*3 + 1)
    println(15 % 5)  // Prints: 0 (15 = 5*3 + 0)
    println(7 % 4)   // Prints: 3 (7 = 4*1 + 3)
}

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

fun main() {
    val number = 8
    println(number % 2)  // Prints: 0 (even)
    
    val another = 7
    println(another % 2) // Prints: 1 (odd)
}

Modulo is incredibly useful in programming, from determining if a year is a leap year, to cycling through a list of items, to formatting output in rows. You'll encounter it frequently as you continue learning.

challenge icon

Challenge

Easy

Write a function getRemainder that takes dividend and divisor and returns the remainder after division.

Use the modulo operator to calculate what's left over when the first number is divided by the second.

Parameters:

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

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

Input constraints: The divisor is nonzero. All inputs and results fit in Int.

Try it yourself

fun 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

Practice on your own: Kotlin playground