Modulus Operator in C

Modulus Operator in C


This article will demonstrate multiple methods of how to use the modulo operator in C.

Use % Modulo Operator to Calculate Remainder in Division in C

Modulo % is one of the binary arithmetic operators in the C language. It produces the remainder after the division of two given numbers. Modulo operator can’t be applied to floating-point numbers like float or double. In the following example code, we showcase the simplest possible case for using the % operator, printing modulus 9 results of the given int array.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int arr[8] = {10, 24, 17, 35, 65, 89, 55, 77};

    for (int i = 0; i < 8; ++i) {
        printf("%d/%d yields the remainder of - %d\n", arr[i], 9, arr[i] % 9);
    }

    exit(EXIT_SUCCESS);
}

Output:

10/9 yields the remainder of - 1
24/9 yields the remainder of - 6
17/9 yields the remainder of - 8
35/9 yields the remainder of - 8
65/9 yields the remainder of - 2
89/9 yields the remainder of - 8
55/9 yields the remainder of - 1
77/9 yields the remainder of - 5

Use % Modulo Operator to Implement Leap Year Checking Function in C

Alternatively, we can use % operator to implement more complex functions. The next example code demonstrates isLeapYear boolean function that checks if the given year is a leap or not. Note that a year is considered a leap year if its value is divisible by 4 but is not divisible by 100. Additionally, if the year value is divisible by 400, it’s a leap year.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool isLeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
        return true;
    else
        return false;
}

int main(void) {

    uint year = 2021;
    isLeapYear(year) ?
        printf("%d is leap\n", year) :
        printf("%d is not leap\n", year);

    exit(EXIT_SUCCESS);
}