Modulo Operator
Part of the Fundamentals section of Coddy's C# journey. Lesson 16 of 70.
The modulo operator % gives the remainder of a division. In C#, 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:
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.
Usually modulo is 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, or -1 if the number is negative (the remainder takes the sign of the dividend). To check for an odd number, use
number % 2 != 0.
When using modulo with floating-point numbers (doubles), it works the same way as with integers, and the result is a double. For example:
double result = 5.2 % 2.0;
// result is about 1.2Here's how it works: 2.0 goes into 5.2 two times (4.0), and the remainder is 1.2 (5.2 - 4.0 = 1.2). A double cannot store 5.2 exactly, so result actually holds 1.2000000000000002, which is very close to 1.2 but not equal to it.
Another example:
double result = 7.8 % 3.5;
// result is about 0.8Challenge
BeginnerWrite a code that initializes three variables, a (int), b (double) and c (int) with the values 9, 2.6, and 11 (respectively).
After that, initialize the following variables:
d (int)that will hold the result ofamodulo2e (int)that will hold the result ofamodulo3f (double)that will hold the result ofbmodulo1.5g (double)that will hold the result ofbmodulo3.9h (int)that will hold the result ofcmodulo10
Check out the result and see how different dividends and divisors affect the result.
Try it yourself
// Type your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Practice on your own: Online C# compiler