The modulo is the remainder of the whole division. Let's take the example of the division of 618 by 4 :
The result of the integer division of 618 by 4 is 154. The remainder of the integer division is 2.
Note: the operands of the modulo must be integers.
The modulo is a very common operator in computer science. It allows for example to test if a number is even or odd :
Here is an example of a program that tests the parity of the variable number
(we will
come back to this in detail later):
// Check if the number is even or odd
if (number % 2 == 0)
printf ("It is an even number");
else
printf ("It is an odd number");
We want to build a fence of 12345 centimeters. This fence is made with panels of 125 centimeters. Complete the program below to calculate the length that will remain to be fenced after the panels are installed.
#include <stdio.h>
int main(void) {
int length = 12345;
int pannels = 125;
int remainder;
// Calculate the remainder to be fenced
// COMPLETE HERE
printf ("%d cm left to fence.\n", remainder);
return 0;
}
What is the modulo operator (%
)?
What can the modulo operator be used for?
What will the variable x contain after the next line?
x = 12 % 4 ;
What can the variable x contain?
x = b % 3 ;
How to isolate the number of units of the variable x
?
How to isolate the tens digit of the variable x
?