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 oddChallenge
EasyCreate a program that uses the modulo operator (%) to solve the following problems:
- Declare an integer variable
totalMinuteswith a value of 197 - Calculate and store the number of complete hours in
totalMinutesusing integer division - Calculate and store the remaining minutes using the modulo operator
- Print the time in hours and minutes with the EXACT following format:
197 minutes is 3 hours and 17 minutes.Then:
- Declare an integer variable
coinswith a value of 57 - Calculate and store how many quarters (25 coins) can be made from
coins - Calculate and store the remaining coins using the modulo operator
- 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 = 1Checking Even/Odd Numbers:
int number = 15;
bool isEven = (number % 2) == 0; // false, 15 is oddTime Conversion Example:
int totalMinutes = 197;
int hours = totalMinutes ~/ 60; // Integer division: 3
int minutes = totalMinutes % 60; // Remainder: 17Try 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.");
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Comparison OperatorsLogical ANDLogical ORLogical NOTType Test OperatorsRecap - Making Comparisons7Working with Strings
String ConcatenationString InterpolationMulti-line StringsString PropertiesBasic String Methods10Collections - Maps Basics
What are Maps?Creating a MapAccessing Values by KeyKey-Value PairsGetting Map SizeGetting KeysGetting ValuesChecking if a Key Exists13Null Safety In Depth
Understanding NullNullable TypesNon-Nullable TypesNull Assertion OperatorLate InitializationRecap - Handling Null Safely16Fundamentals Challenges
Challenge: List of calculationChallenge: Sum of numbersChallenge: Find product2Variables and Basic Data Types
What are Variables?StringsIntegers (int)Doubles (double)Booleans (bool)Type Inference with 'var'Final VariablesConstant VariablesNaming ConventionsBasic Null SafetyRecap - Declaring Variables8Control Flow - Loops
The 'for' LoopThe 'while' LoopThe 'do-while' LoopUsing 'break' in LoopsUsing 'continue' in LoopsRecap - Repeating Code3Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorIncrement and DecrementAssignment ShortcutsRecap - Simple Calculations6Control Flow - Decision Making
The 'if' StatementThe 'else' StatementThe 'else if' StatementRecap - Simple DecisionsNested 'if' StatementsThe 'switch' Statement9Collections - Lists Basics
What are Lists?Creating a ListAccessing by IndexGetting List LengthAdding ElementsRemoving ElementsChecking if a List is EmptyIterating Over a List12Functions Advanced
Optional Positional ParametersNamed ParametersRequired Named ParametersDefault Parameter ValuesRecap - Function Parameters15Project: Simple Calculator
Setting UpDeclaring Number