Arithmetic Operators in C#

Arithmetic operators are the most common operators used in programming. They perform mathematical operations on numerical values and return a numerical result. They are the same signs and operations that are used in math and everyday life.

If you aren’t generally familiar with operators and precedence in programming, then I suggest that you check out my blog post on Working with Operators in C#.

Here are the arithmetic operators used in C#:

Operand Description
++ Increment opreator. Increments an operand by 1.
-- Decrement operator. Decrements an operand by 1.
* Multiplication operator. Multiplies two operands.
/ Division operator. Divides an operand by another operand.
% Modulus operator. Divides an operand by another operand to find the remainder.
+ Addition operator. Adds two operands.
- Subtraction operator. Subtracts two operands.

Prefix and postfix

When using the increment and decrement operators it’s important to understand how using them as a prefix and as a postfix works.

Applying the increment or decrement operators to a variable will increase or decrease its value by one. When one of the operators is placed before the variable and used as a prefix, the new value is calculated first and the result can immediately be returned. When one of the operators is placed after the variable and used as a postfix, the new value is calculated after the last and the original value of the variable is returned first.

Examples using arithmetic operators

Here are some examples of using arithmetic operators to perform calculations on two variables and the values they contain:

int x = 8;
int y = 4;

x++;  // x = 8 until after this statement
Console.WriteLine(x);   //  Output: 9

x--;  // x = 9 until after this statement
Console.WriteLine(x);   //  Output: 8

Console.WriteLine(++y); //  Output: 5
Console.WriteLine(--y); //  Output: 4

Console.WriteLine(x * y);   //  Output: 32
Console.WriteLine(x / y);   //  Output: 2
Console.WriteLine(x % y);   //  Output: 0
//  Console.WriteLine(x / 0);   Output: DivideByZeroException

Console.WriteLine((x++) + y);   //  Output: 12
Console.WriteLine(x - (++y));   //  Output: 4
comments powered by Disqus