C# Arithmetic Operators
Arithmetic operators are used to perform common mathematical calculations on numbers. If you have ever used a calculator, these will feel familiar: addition, subtraction, multiplication, and division. C# also adds a handy modulus operator for finding remainders, plus quick ways to increase or decrease a value by one.
The five basic arithmetic operators
C# gives you five core arithmetic operators. Four of them match everyday math, and the fifth, modulus, returns the remainder left over after a division.
Arithmetic operators
Trying each operator
int a = 7;
int b = 2;
Console.WriteLine(a + b); // 9
Console.WriteLine(a - b); // 5
Console.WriteLine(a * b); // 14
Console.WriteLine(a % b); // 1 (remainder)Watch out for integer division
When you divide two int values, C# throws away any fractional part and keeps only the whole number. So 7 / 2 gives 3, not 3.5. If you need the decimal result, at least one of the values must be a double.
Integer vs decimal division
int x = 7;
int y = 2;
Console.WriteLine(x / y); // 3, the .5 is lost
double d = 7.0;
Console.WriteLine(d / y); // 3.5, correct decimalIncrement and decrement
Adding or subtracting one from a value is so common that C# has shortcuts. The increment operator ++ adds one, and the decrement operator -- subtracts one. You will see these constantly inside loops.
Using ++ and --
int count = 5;
count++; // now 6
count--; // back to 5
Console.WriteLine(count); // 5- count++ means count = count + 1.
- count-- means count = count - 1.
- These change the variable in place, so nothing else needs to be assigned.