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
EasyWrite 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 divideddivisor(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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground