Lesson 11 +10 XP

Arithmetic & Assignment Operators

Arithmetic & Assignment Operators

Operators tell C# to perform operations on values and variables.

Arithmetic operators

OperatorNameExample
+additionx + y
-subtractionx - y
*multiplicationx * y
/divisionx / y
%modulus (remainder)x % y
++increment by 1x++
--decrement by 1x--
int x = 100 + 50;    // 150
int y = 10 % 3;      // 1  (remainder of 10/3)
x++;                 // x becomes 151

Division of integers

When you divide two ints, the result is an int - the decimal part is dropped:

Console.WriteLine(10 / 3);   // 3, not 3.33

Use double values if you need decimals:

Console.WriteLine(10.0 / 3); // 3.333...

Assignment operators

The = operator assigns a value. There are shortcuts that combine assignment with an operation:

OperatorSame as
x = 5assigns 5
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3
x %= 3x = x % 3
x &= 3x = x & 3
`x= 3``x = x3`

TL;DR

  • Arithmetic: + - * / % ++ and --.
  • Integer division drops the decimal part.
  • Assignment shortcuts like += combine operation and assignment.