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) // 1Here, 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
EasyWrite 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 divideddivisor(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) // 1When 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
}
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 OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input