Lesson 3.2. modulo

Modulo

The modulo is the remainder of the whole division. Let's take the example of the division of 618 by 4 :

In C, modulo is the remainder of the integer division

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.

Example

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");

Exercise

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;
}

Quiz

What is the modulo operator (%)?

Check Bravo! The modulo operator calculates the remainder of the integer division. Try again...

What can the modulo operator be used for?

Check Bravo ! The remainder of the division informs us about the divisibility of the operands. Try again...

What will the variable x contain after the next line?

x = 12 % 4 ;
Check Bravo! 12 being divisible by 4, the remainder is 0. Try again...

What can the variable x contain?

x = b % 3 ;
Check Bravo! The remainder of the division by 3 can only be 0, 1 or 2. Try again...

How to isolate the number of units of the variable x?

Check Bravo! The remainder of the division by 10 will give the number of units. Try again...

How to isolate the tens digit of the variable x?

Check Bravo! There are indeed two solutions. Try again...

See also


Last update : 09/19/2023