You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
*Modulo* operation calculates the remainder when one integer is divided by another. It is useful for keeping a variable within a particular range (e.g. the size of an array). The `%` (percent) symbol is used to carry out modulo operation.
21
+
*Remainder* operation calculates the remainder when one integer is divided by another. It is useful for keeping a variable within a particular range (e.g. the size of an array). The `%` (percent) symbol is used to carry out remainder operation.
22
22
[%hardbreaks]
23
23
24
24
@@ -55,6 +55,8 @@ x = 7 % 5; // x now contains 2
55
55
x = 9 % 5; // x now contains 4
56
56
x = 5 % 5; // x now contains 0
57
57
x = 4 % 5; // x now contains 4
58
+
x = -4 % 5; // x now contains -4
59
+
x = 4 % -5; // x now contains 4
58
60
----
59
61
60
62
[source,arduino]
@@ -69,14 +71,17 @@ void setup() {}
69
71
void loop()
70
72
{
71
73
values[i] = analogRead(0);
72
-
i = (i + 1) % 10; // modulo operator rolls over variable
74
+
i = (i + 1) % 10; // remainder operator rolls over variable
73
75
}
74
76
----
75
77
[%hardbreaks]
76
78
77
79
[float]
78
80
=== Notes and Warnings
79
-
The modulo operator does not work on floats.
81
+
1. The remainder operator does not work on floats.
82
+
83
+
2. If the *first* operand is negative, the result is negative (or zero).
84
+
Therefore, the result of `x % 10` will not always be between 0 and 9 if `x` can be negative.
0 commit comments