
You want to see examples of the modulo division operation in the C# language, which allows you to execute code once every several iterations of a loop. The modulo operator uses the percentage sign % character in the lexical syntax and has some unique properties. Here we look at the modulo division operation.
Estimated costs of instructions Add: 1 ns Subtract: 1 ns Multiply: 2.7 ns Divide: 35.9 ns
Example 1
Modulo division is expressed with the percentage sign % character. It is implemented with the rem instruction in the intermediate language. The rem instruction takes the top two values on the evaluation stack and performs the mathematical computation that returns the remainder of the division, and then pushes that value onto the evaluation stack for the next instructions to use.This example demonstrates the mathematics behind modulo and the modulo expressions here are actually turned into constants during the C# compilation step, so no rem instructions are generated.
Program that uses modulo operator [C#] using System; class Program { static void Main() { // // When 1000 is divided by 90, the remainder is 10. // Console.WriteLine(1000 % 90); // // When 100 is divided by 90, the remainder is also 10. // Console.WriteLine(100 % 90); // // When 81 is divided by 80, the remainder is 1. // Console.WriteLine(81 % 80); // // When 1 is divided by 1, the remainder is zero. // Console.WriteLine(1 % 1); } } Output 10 10 1 0

Results. You can see that 1000 and 100 divide into parts of 90 with a remainder of 10. If the first argument to the predefined modulo operator is 81 and the second operand is 80, the expression evaluates to a value of 1. Finally, if you apply modulo division on the same two operands, you receive 0 because there is no remainder. If you perform modulo division by zero, you will get either a compile error or a runtime exception depending on how well the C# compiler can analyze your code.
Modulo loop example
You can actually apply the modulo operator in the C# language in a loop to achieve an interval or step effect. If you use a modulo operation on the loop index variable, which is called an induction variable, you can execute code at an interval based on the induction variable. This example shows how you can write to the screen every ten iterations in the for-loop.Program that uses modulo division in loop [C#] using System; class Program { static void Main() { // // Prints every tenth number from 0 to 200. // Includes the very first iteration. // for (int i = 0; i < 200; i++) { if ((i % 10) == 0) { Console.WriteLine(i); } } } } Output 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190
No comments:
Post a Comment