TL ; DR:
The modulo operator (
%) calculates the remainder of dividing two values:print(10 % 2) // Output: 0 print(15 % 4) // Output: 3 print(20 % 3) // Output: 2It can also be used with variables:
var a = 2 var b = 4 print(b % a) // Output: 0 print(11 % b) // Output: 3
Full lesson:
Remember how we first learn about the division of two integer numbers in primary school?
The quotient is the number of times a division is completed fully, while the remainder is the amount left that doesn't entirely go into the divisor.
Here are some examples:
10 / 2 = quotient 5, remainder 0
15 / 4 = quotient 3, remainder 3
20 / 3 = quotient 6, remainder 2
The modulo operator:
The modulo operator (%) calculates the remainder of dividing two values:
print(10 % 2) // Output: 0
print(15 % 4) // Output: 3
print(20 % 3) // Output: 2
It can also be used with variables:
var a = 2
var b = 4
print(b % a) // Output: 0
print(11 % b) // Output: 3
floor() function
The floor() function returns the largest integer less than or equal to a given number:
print(Int(floor(3.9))) // Output: 3
print(Int(floor(5.2))) // Output: 5
print(Int(floor(7.0))) // Output: 7
We can use this function if we want to compute the integral part of some division (quotient):
var a = 2
var b = 3
var c = b / a
print(c) // Output: 1
Quotient and remainder:
In programming, we combine both these concepts to get the quotient and remainder of some divison:
// Let's divide 26 by 3:
var quotient = 26 / 3
var remainder = 26 % 3
print(quotient) // Output: 8
print(remainder) // Output: 2
Assignment
Follow the Coding Tutorial and let's practice with quotient and remainder!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.