Modulo for dummies
by Antoine - categories : Programming
The modulo is a mathematical operation useful as a programming operator when one needs to repeat an event every n times. Written «%»), the modulo actually returns the rest of an euclidean division.
A common application for it is to make a treatment for even iterations in a loop, and another one for odds. For example, this is can be useful for applying a conversation-like style in a comment flow like in my site. A "left to right" style is applied on odd iterations, and a "righ to left" on even iterations. But it can be useful for many other needs.
Examples
- 12 / 6 == 2, remains 0, so 12 % 6 == 0.
Another method, with the same operation, the goal is to "remove" as many times as possible "2" from the figure "7" to get as close as possible to zero : 7 -> 5 -> 3 -> 1 We can remove three times "2" from it, but we can't get lower than... 1, the remainder, and by the way the result of our modulo.
-
7 / 2 == 3, 1 remains, so 7 % 2 = 1
-
Same method with 8 % 3 = 8 -> 5 -> 2
Code
PHP
$i = 0;
while ($i < 10) {
$mod = $i % 3;
echo $mod;
$i++;
}
Ouput
0120120120
Python
Same example as above
i = 0
while (i < 10):
mod = i % 3
print(mod)
i += 1
Python output
0
1
2
0
1
2
0
1
2
0
Another example
list = ["com1", "com2", "com3", "com4"]
for i in range(len(list)): # Iterate over list indexes
if i % 2 == 1:
print(f'{list[i]} -> {i} % 2 -> 1 -> odd')
else:
print(f'{list[i]} -> {i} % 2 -> 0 -> even')
Python output
com1 -> 0 % 2 -> 0 -> even
com2 -> 1 % 2 -> 1 -> odd
com3 -> 2 % 2 -> 0 -> even
com4 -> 3 % 2 -> 1 -> odd
Be the first to comment 🡮