|
| 1 | +--- |
| 2 | +title: "%" |
| 3 | +title_expanded: "remainder" |
| 4 | +categories: [ "Structure" ] |
| 5 | +subCategories: [ "Arithmetic Operators" ] |
| 6 | +--- |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | += % Remainder |
| 13 | + |
| 14 | + |
| 15 | +// OVERVIEW SECTION STARTS |
| 16 | +[#overview] |
| 17 | +-- |
| 18 | + |
| 19 | +[float] |
| 20 | +=== Description |
| 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 | +[%hardbreaks] |
| 23 | + |
| 24 | + |
| 25 | +[float] |
| 26 | +=== Syntax |
| 27 | +[source,arduino] |
| 28 | +---- |
| 29 | +remainder = dividend % divisor; |
| 30 | +---- |
| 31 | + |
| 32 | +[float] |
| 33 | +=== Parameters |
| 34 | +`remainder` : variable. *Allowed data types:* int, float, double + |
| 35 | +`dividend` : variable or constant. *Allowed data types:* int + |
| 36 | +`divisor` : *non zero* variable or constant. *Allowed data types:* int |
| 37 | +[%hardbreaks] |
| 38 | + |
| 39 | +-- |
| 40 | +// OVERVIEW SECTION ENDS |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | +// HOW TO USE SECTION STARTS |
| 45 | +[#howtouse] |
| 46 | +-- |
| 47 | + |
| 48 | +[float] |
| 49 | +=== Example Code |
| 50 | + |
| 51 | +[source,arduino] |
| 52 | +---- |
| 53 | +int x = 0; |
| 54 | +x = 7 % 5; // x now contains 2 |
| 55 | +x = 9 % 5; // x now contains 4 |
| 56 | +x = 5 % 5; // x now contains 0 |
| 57 | +x = 4 % 5; // x now contains 4 |
| 58 | +x = -4 % 5; // x now contains -4 |
| 59 | +x = 4 % -5; // x now contains 4 |
| 60 | +---- |
| 61 | + |
| 62 | +[source,arduino] |
| 63 | +---- |
| 64 | +/* update one value in an array each time through a loop */ |
| 65 | +
|
| 66 | +int values[10]; |
| 67 | +int i = 0; |
| 68 | +
|
| 69 | +void setup() {} |
| 70 | +
|
| 71 | +void loop() |
| 72 | +{ |
| 73 | + values[i] = analogRead(0); |
| 74 | + i = (i + 1) % 10; // remainder operator rolls over variable |
| 75 | +} |
| 76 | +---- |
| 77 | +[%hardbreaks] |
| 78 | + |
| 79 | +[float] |
| 80 | +=== Notes and Warnings |
| 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. |
| 85 | +[%hardbreaks] |
| 86 | + |
| 87 | +-- |
| 88 | +// HOW TO USE SECTION ENDS |
| 89 | + |
| 90 | +// SEE ALSO SECTION STARTS |
| 91 | +[#see_also] |
| 92 | +-- |
| 93 | + |
| 94 | +[float] |
| 95 | +=== See also |
| 96 | + |
| 97 | +[role="language"] |
| 98 | + |
| 99 | +-- |
| 100 | +// SEE ALSO SECTION ENDS |
0 commit comments