The following assignment, found in line 18 of Listing 9.6
height = height + 100;
as you know, increments the variable height by 100. Frequently, and in particular in connection with iteration statements, variables are incremented with a specific amount. C# offers a condensed way of writing this type of assignment through the plus-equals (+=) operator. It allows us to express the previous assignment statement as
where the left operand is added to the right operand (step 1) and the result is then assigned to the left operand (step 2).
C# contains five combination assignment operators, one for each of the binary operators +, -, *, /, and %. They are all displayed in Table 9.2.
Operator | Name | Example | Equivalent to |
---|---|---|---|
+= | Addition assignment | height += 100; | height = height + 100; |
-= | Subtraction assignment | sum -= 10; | sum = sum - 10; |
*= | Multiplication assignment | length *= 3; | length = length * 3; |
/= | Division assignment | height /= 2; | height = height / 2; |
%= | Modulus assignment | days %= 7; | days = days % 7; |
Syntax Box 9.6 Combination assignmentCombination_assignment::= <Variable> <Combination_assignment_operator> <Expression> Note:
|
Listing 9.9 demonstrates the four combination assignment operators +=, -=, *=, and /= in action and allows the program to print out a counting table as shown in the sample output.
01: using System; 02: 03: class CountingTable 04: { 05: public static void Main() 06: { 07: int countUp = 0; 08: int countDown = 100; 09: int fastUp = 1; 10: int fastDown = 1024; 11: 12: Console.WriteLine("+= -= *= /="); 13: for (int i = 0; i < 10; i++) 14: { 15: countUp += 5; 16: countDown -= 20; 17: fastUp *= 2; 18: fastDown /= 2; 19: Console.WriteLine("{0,2} {1,4} {2,4} {3,4} ", 20: countUp, countDown, fastUp, fastDown); 21: } 22: } 23: } += -= *= /= 5 80 2 512 10 60 4 256 15 40 8 128 20 20 16 64 25 0 32 32 30 -20 64 16 35 -40 128 8 40 -60 256 4 45 -80 512 2 50 -100 1024 1
The program utilizes a for loop to repeat the loop body in lines 15 20 ten times. For every repetition, the four combination assignment operators are used to update the four different variables in lines 15 18. As the for loop progresses through the ten loops, the value of each variable is printed (lines 19 and 20) to form the table shown in the sample output.