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
EasyWrite a C program that does the following:
- Declare an integer variable
numberand initialize it with the value 17. - Use the modulo operator to calculate the remainder when
numberis divided by 5, and store the result in a variable calledremainder. - Use the modulo operator to determine if
numberis even or odd (remember booleans) - 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? 0Cheat sheet
The modulo operator % gives the remainder of a division:
result = dividend % divisor;Example:
int result = 10 % 3; // result is 1Common 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;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge