Syntax question in code

I have a question about syntax in the code snippet below:

What is meaning of using the "%" percent sign in Arduino code? I have seen this in other code but I have not been able to discover the use for this or maybe I am just not looking in the correct places.

Thanks in advance for any assistance.

Jim

Snippet:
// Removes noise from sensor data
int average(int rawIn, int *averageArray) {
long total = 0;
static int i;

i = (i + 1) % 16;
averageArray = rawIn;

  • for (int j = 0; j < 16; j++) total += averageArray[j];*
  • total += total % 16;*
  • return total >> 4 ;*

It's the Modulo operator and returns a number between 0 and (n-1),
where 'n' is the value to the right of the '%'.

For example:
x x%n (where n=5)
0 0
1 1
2 2
3 3
4 4
5 0
6 1
7 2
8 3
9 4
10 0

As Rusty says, it's the modulo (or mod) operator, also known as the remainder of integer division.

21 / 10 is 2.
21 % 10 is 1.

-j

Thanks to both of you but.......Is it 21/10 = 2 or 1? How can it be both?

Let me see. If we divide 21 by 10, it will not divide evenly and have a remainder of .5 so we round up to get 2?

As an integer, using the %(Modulo) since no fractions or decimals are allowed, then we round it to 1? :wink:

Jim

There is no rounding: integer division truncates, modulo gives an integer remainder (which of course could be zero).

I showed the division operator for comparison; it seems to have added confusion instead. oops.

-j

The modulus operator gives you the remainder after integer division:

21 / 10 = 2 (remember, it's truncating integer division)

21 % 10 = 1 (the remainder that you would get from the above division)