Menu
Coddy logo textTech

Modulo Operator

Part of the Fundamentals section of Coddy's C journey — lesson 17 of 63.

The modulo operator % in C gives the remainder of a division. It's used with a simple syntax:

result = dividend % divisor;
  • dividend: The number being divided.
  • divisor: The number that divides the dividend.
  • result: The remainder of the division.

For example:

int result = 10 % 3;

Here, 10 is divided by 3. 3 goes into 10 three times, with a remainder of 1. So, result will be 1.

The modulo operator is often used for checking if a number is even or odd:

  • If a number is even, dividing it by 2 will leave a remainder of 0.
  • If a number is odd, dividing it by 2 will leave a remainder of 1.
challenge icon

Challenge

Easy

Write a C program that does the following:

  1. Declare an integer variable number and initialize it with the value 17.
  2. Use the modulo operator to calculate the remainder when number is divided by 5, and store the result in a variable called remainder.
  3. Use the modulo operator to determine if number is even or odd (remember booleans)
  4. Print the results using three separate printf() calls, each ending with \n, in the following format:
printf("Number: %d\n", number);
printf("Remainder when divided by 5: %d\n", remainder);
printf("%d is even? %d\n", number, is_even);

The expected output is:

Number: 17
Remainder when divided by 5: 2
17 is even? 0

Cheat sheet

The modulo operator % gives the remainder of a division:

result = dividend % divisor;

Example:

int result = 10 % 3;  // result is 1

Common use case - checking if a number is even or odd:

  • Even numbers: number % 2 == 0
  • Odd numbers: number % 2 == 1

Try it yourself

#include <stdio.h>

int main() {
    // Declare and initialize variables here
    
    // Calculate remainder
    
    // Check if number is even or odd
    
    // Print results
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals