DekGenius.com
Team LiB   Previous Section   Next Section

7.2 Mathematical Operators

C# uses five mathematical operators, four for standard calculations and one to return the remainder when dividing integers. The following sections consider the use of these operators.

7.2.1 Simple Arithmetical Operators (+, -, *, / )

C# offers operators for simple arithmetic: the addition (+), subtraction (-), multiplication (*), and division (/) operators work as you might expect, with the possible exception of integer division.

When you divide two integers, C# divides like a child in the fourth grade: it throws away any fractional remainder. Thus, dividing 17 by 4 returns a value of 4 (17/4 = 4, with C# discarding the remainder of 1).

This limitation is specific to integer division. If you do not want the fractional part thrown away, you can use one of the types that support decimal values, such as float and double. Division between two floats (using the / operator) returns a fractional answer. Integer and fractional division is illustrated in Example 7-1.

Example 7-1. Integer and float division
using System;
public class Tester
{
    public static void Main()
    {
        int smallInt = 5;
        int largeInt = 12;
        int intQuotient;
        intQuotient = largeInt / smallInt;
        Console.WriteLine("Dividing integers. {0} / {1} = {2}",
            largeInt, smallInt, intQuotient);

        float smallFloat = 5;
        float largeFloat = 12;
        float FloatQuotient;
        FloatQuotient = largeFloat / smallFloat;
        Console.WriteLine("Dividing floats. {0} / {1} = {2}",
            largeFloat, smallFloat, FloatQuotient);

    }
}
Output:
Dividing integers. 12 / 5 = 2
Dividing floats. 12 / 5 = 2.4

C# provides a special operator, modulus (%), to retrieve the remainder from integer division.

7.2.2 Using the modulus Operator (%) to Return Remainders

To find the remainder in integer division, use the modulus operator (%). For example, the statement 17%4 returns 1 (the remainder after integer division).

Example 7-2 demonstrates the effect of division on integers, floats, doubles, and decimals.

Writeline Control Characters

Consider this line from Example 7-2:

Console.WriteLine("Integer:\t{0}\nfloat:\t\t{1}\n",
   firstInt/secondInt, firstFloat/secondFloat);

It begins with a call to Console.Writeline(), passing in this partial string:

"Integer:\t{0}\n

This will print the characters Integer: followed by a tab (\t), the first parameter ({0}), and a newline character (\n). The next string snippet:

float:\t\t{1}\n

is very similar. It prints float:, followed by two tabs (to ensure alignment), the contents of the second parameter ({1}), and then another newline. Notice the subsequent line, as well:

Console.WriteLine(
 "\nRemainder(modulus) from integer division:\t{0}", 
   firstInt%secondInt);

This time the string begins with a newline character, which causes a line to be skipped just before the string Modulus: is printed. You can see this effect in the output.

Example 7-2. Modulus and integer division
using System;
class Values
{
    static void Main()
    {
        int firstInt, secondInt;
        float firstFloat, secondFloat;
        double firstDouble, secondDouble;
        decimal firstDecimal, secondDecimal;

        firstInt = 17;
        secondInt = 4;
        firstFloat = 17;
        secondFloat = 4;
        firstDouble = 17;
        secondDouble = 4;
        firstDecimal = 17;
        secondDecimal = 4;
        Console.WriteLine("Integer:\t{0}\nfloat:\t\t{1}",
            firstInt/secondInt, firstFloat/secondFloat);
        Console.WriteLine("double:\t\t{0}\ndecimal:\t{1}", 
            firstDouble/secondDouble, firstDecimal/secondDecimal);
        Console.WriteLine(
          "\nRemainder(modulus) from integer division:\t{0}", 
            firstInt%secondInt);

    }
}
Output:
Integer:        4
float:          4.25
double:         4.25
decimal:        4.25

Remainder(modulus) from integer division:       1

The modulus operator turns out to be more useful than you might at first imagine. When you perform modulus n on a number that is a multiple of n, the result is zero. Thus 80%10=0 because 80 is an even multiple of 10. This fact allows you to set up loops in which you take an action every nth time through the loop, by testing a counter to see if %n is equal to zero, as illustrated in Example 7-3.

Example 7-3. Modulus operator (%)
using System;
public class Tester
{

    public static int Main()
    {
        for (int counter=1; counter<=100; counter++)
        {
            Console.Write("{0} ", counter);

            if ( counter % 10 == 0 )
            {
                Console.WriteLine("\t{0}", counter);
            }
        }
        return 0;
    }
}
Output:
1 2 3 4 5 6 7 8 9 10    10
11 12 13 14 15 16 17 18 19 20   20
21 22 23 24 25 26 27 28 29 30   30
31 32 33 34 35 36 37 38 39 40   40
41 42 43 44 45 46 47 48 49 50   50
51 52 53 54 55 56 57 58 59 60   60
61 62 63 64 65 66 67 68 69 70   70
71 72 73 74 75 76 77 78 79 80   80
81 82 83 84 85 86 87 88 89 90   90
91 92 93 94 95 96 97 98 99 100  100

In Example 7-3, the value of the counter variable is incremented each time through the loop. Within the loop, the value of counter is compared with the result of modulus 10 (counter % 10). When this evaluates to zero, the value of counter is evenly divisible by 10, and the value is printed in the right-hand column.

    Team LiB   Previous Section   Next Section