Menu
Coddy logo textTech

Modulo Operator

Part of the Fundamentals section of Coddy's Dart journey — lesson 18 of 94.

The modulo operator (%) gives us the remainder after division. Let's explore how it works with some straightforward examples.

Basic Modulo Operation

void main() {
  int dividend = 10;
  int divisor = 3;
  int remainder = dividend % divisor;
  
  print('Remainder of $dividend ÷ $divisor = $remainder');
}

Output: Remainder of 10 ÷ 3 = 1

When we divide 10 by 3, we get 3 with a remainder of 1. The modulo operator % captures that remainder value.

Checking for Even and Odd Numbers

We can determine whether a number is even or odd using the modulo operator:

void main() {
  int number = 15;
  int remainder = number % 2;
  
  print('$number % 2 = $remainder');
  
  // Even numbers have remainder 0 when divided by 2
  bool isEven = remainder == 0;
  
  // Using direct boolean evaluation instead of if/else
  String result = isEven ? '$number is even' : '$number is odd';
  print(result);
}

Output:

15 % 2 = 1
15 is odd
challenge icon

Challenge

Easy

Create a program that uses the modulo operator (%) to solve the following problems:

  1. Declare an integer variable totalMinutes with a value of 197
  2. Calculate and store the number of complete hours in totalMinutes using integer division
  3. Calculate and store the remaining minutes using the modulo operator
  4. Print the time in hours and minutes with the EXACT following format:
197 minutes is 3 hours and 17 minutes.

Then:

  1. Declare an integer variable coins with a value of 57
  2. Calculate and store how many quarters (25 coins) can be made from coins
  3. Calculate and store the remaining coins using the modulo operator
  4. Print the result with the EXACT following format:
57 coins can be divided into 2 quarters and 7 remaining coins.

Cheat sheet

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

int remainder = 10 % 3; // remainder = 1

Checking Even/Odd Numbers:

int number = 15;
bool isEven = (number % 2) == 0; // false, 15 is odd

Time Conversion Example:

int totalMinutes = 197;
int hours = totalMinutes ~/ 60;     // Integer division: 3
int minutes = totalMinutes % 60;    // Remainder: 17

Try it yourself

void main() {
  // Declare your variables here
  int totalMinutes = ?;
  
  // Calculate hours and remaining minutes
  int hours = totalMinutes ? 60;
  int remainingMinutes = totalMinutes ? 60;
  
  // Print the time result
  print("$totalMinutes minutes is $hours hours and $remainingMinutes minutes.");
  
  // Calculate quarters and remaining coins
  int coins = ?;
  int quarters = coins ~/ ?;
  int remainingCoins = coins % ?;
  
  // Print the coins result
  print("$coins coins can be divided into $quarters quarters and $remainingCoins remaining coins.");
}
quiz iconTest yourself

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

All lessons in Fundamentals