Mathmatical Operations

I want to be able to use the remainder of a math operation in a program.
I want an LED output to flash on-off based on object distance, and I want it to change with 20 cm of movement change in the object, so that I get a “strobe effect” when I move my hand back and forth in front on a distance sensor.
What is a command for recording the remainder of a number? For example, I will divide the sonic sensor reading by a value corresponding to 20 cm, and will be looking at the size of the remainder to determine if the LED is set to on or off.
If anyone has a cheat sheet for other math operators, like absolute values, this would help too.

Thanks - Marc Wheeler

You’re looking for the modulo operator (


%

)


printf("%d\n", 0 % 4); // prints 0
printf("%d\n", 1 % 4); // prints 1
printf("%d\n", 2 % 4); // prints 2
printf("%d\n", 3 % 4); // prints 3
printf("%d\n", 4 % 4); // prints 0
printf("%d\n", 5 % 4); // prints 1
printf("%d\n", 6 % 4); // prints 2
printf("%d\n", 7 % 4); // prints 3
printf("%d\n", 8 % 4); // prints 0
// and so on

So something like z = (%x/y);
would store the remainder of x divided by y as z?

Thanks for the quick reply

You understand the idea and are just a tad off in implementation.

You would use z = x%y;

If x is 5, and y is 2, z would equal 1 after that line of code.

Thanks, this makes sense now.