Loading lessons...
Arithmetic & Assignment Operators
Arithmetic & Assignment Operators
Operators tell C# to perform operations on values and variables.
Arithmetic operators
| Operator | Name | Example |
|---|---|---|
+ | addition | x + y |
- | subtraction | x - y |
* | multiplication | x * y |
/ | division | x / y |
% | modulus (remainder) | x % y |
++ | increment by 1 | x++ |
-- | decrement by 1 | x-- |
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:
| Operator | Same as | ||
|---|---|---|---|
x = 5 | assigns 5 | ||
x += 3 | x = x + 3 | ||
x -= 3 | x = x - 3 | ||
x *= 3 | x = x * 3 | ||
x /= 3 | x = x / 3 | ||
x %= 3 | x = x % 3 | ||
x &= 3 | x = x & 3 | ||
| `x | = 3` | `x = x | 3` |
TL;DR
- Arithmetic:
+ - * / % ++and--. - Integer division drops the decimal part.
- Assignment shortcuts like
+=combine operation and assignment.