This tutorial will not only demonstrate how to find out whether a number is odd or even using C#, but it will also explain what the modulus (%) operator means in C# and how to properly and strategically use it.
In C#, the modulus operator (%) is an operator that is meant to find the remainder after dividing the first operand (the first number) by the second.
The best way to understand how the modulus works is to see it in action. Take a look at the example below:
Console.WriteLine(5%2) Console.WriteLine(6%3) Console.WriteLine(10%4)
The output of the above code would be as follows:
1 0 2
Remember, the modulus calculates the remainder that is a result of the first operand being divided by the second — it’s not meant to solve the division equation. So in the first example, you are left with a remainder because 2 does not go into 5 evenly. It goes into 5 exactly 2 and a half times, so you’re left with a remainder of 1 (half of 2 is 1). Conversely, 3 does go into 6 evenly, so for the second example you’re left with no remainder, and your answer is 0. Much like in the first example, 4 does not go into 10 evenly. 4 goes into ten two and a half times, so your remainder will be 2 (half of 4 is 2).
You may have to revisit some elementary school fractions and division techniques to really get a sense of how to handle remainders.
One great way to use the modulus operator is to check if a number is even or odd. The modulus is perfect for this sort of test because any even number is, by definition, evenly divisible by 2. So any number that’s divided by 2 with no remainder must be even.
Knowing this, we can easily use the modulus operator come up with some code that will determine if a number’s remainder when dived by 2, equals zero, and if this is true, then the number is even. Take a look at the code below:
if(num%2 == 0){ Console.WriteLine("Number is even") }else{ Console.WriteLine("Number is odd") }
Thanks to the modulus operator, this simple code is all we need to determine if a number is odd or even. There are many reasons in C# why you might want to test the oddness or evenness of a number — most of the time it would probably be to execute different functions based on the results. If you’d like to use the above code in that way, just make sure that you insert your desired functions within the if…else statements instead of the “Console.WriteLine” commands.