0
0
CConceptBeginner · 3 min read

What is Modulo Operator in C: Explanation and Examples

In C, the % symbol is the modulo operator, which gives the remainder after dividing one number by another. It returns the leftover part after division, for example, 7 % 3 results in 1 because 7 divided by 3 leaves a remainder of 1.
⚙️

How It Works

The modulo operator % in C works like finding the leftover part after sharing something evenly. Imagine you have 7 candies and want to share them equally among 3 friends. Each friend gets 2 candies, but 1 candy is left undistributed. That leftover candy is what the modulo operator returns.

Mathematically, when you divide one number by another, you get a quotient (how many times it fits) and a remainder (what is left). The modulo operator gives you that remainder. It only works with integers in C, so it tells you how much is left after full divisions.

💻

Example

This example shows how to use the modulo operator to find the remainder of two numbers.

c
#include <stdio.h>

int main() {
    int a = 7;
    int b = 3;
    int remainder = a % b;
    printf("The remainder of %d divided by %d is %d\n", a, b, remainder);
    return 0;
}
Output
The remainder of 7 divided by 3 is 1
🎯

When to Use

The modulo operator is useful when you need to find out if a number is divisible by another or to cycle through values repeatedly. For example, you can check if a number is even or odd by using number % 2. If the result is 0, the number is even; if 1, it is odd.

It is also used in programming tasks like wrapping around array indexes, creating repeating patterns, or working with time calculations like hours and minutes.

Key Points

  • The modulo operator % returns the remainder after division.
  • It only works with integer values in C.
  • Useful for checking divisibility and cycling through values.
  • Commonly used to determine even or odd numbers.

Key Takeaways

The modulo operator (%) returns the remainder after integer division in C.
It helps check if numbers divide evenly or find leftover parts.
Use it to determine even/odd numbers or cycle through repeating sequences.
Modulo only works with integers, not floating-point numbers.