Code

Arithmetic Operators

Arithmetic operators in C# are the same ones you use on numeric values in math to perform mathematical operations such as addition, subtraction, multiplication, division etc.

Arithmetic Operators in C#

Operator Description Examples
+ Add Add two operands together. a + b
Subtract Subtract the value of right-hand operand from left-hand operand. a – b
* Multiply Multiplies both operands. a * b
/ Division Divide the left-hand operand with the right-hand operand (numerator by de-numerator) a / b
% Modulo Divide the left-hand operand by the right operand and then returns the remainder. a % b
++ Increment Increase the value of the operand by 1. a++
– – Decrement Decrease the value of the operand by 1. a – –

Increment and Decrement Operators (++, –)

int a = 3;
a++; // 3 
--a; // Still 3 
++a; // 4

int a = 0;
Console.WriteLine($"a is now {a}");
Console.WriteLine($"a++ : Outputs {a++}, a is now {a}");
Console.WriteLine($"++a : Outputs {++a}, a is now {a}");
Console.WriteLine($"--a : Outputs {--a}, a is now {a}");

Run Demo

OUTPUT

a is now 0
a++ : Outputs 0, a is now 1
++a : Outputs 2, a is now 2
–a : Outputs 1, a is now 1

Modulus (%)

int a = 13 % 3; // 1
int b = 30 % 7; // 2
Console.WriteLine($"remainder : {a}");
Console.WriteLine($"remainder : {b}");
OUTPUT

remainder : 1
remainder : 2

int a = 30;
int b = 7;
int c = a - (a / b) * b;
Console.WriteLine($"a – (a / b) * b : remainder is {c}");
Console.WriteLine($"a % b : remainder is {a % b}");

Run Demo

OUTPUT

remainder : 1
remainder : 2
a – (a / b) * b : remainder is 2
a % b : remainder is 2

More Examples

int addition = 20 + 10;
int subtraction = 20 - 10;
int multiplication = 20 * 10;
int division = 20 / 10;
int modulus_1 = 7 % 3;
double modulus_2 = 14.9 % 3.9;

Run Demo

OUTPUT

addition: 30
subtraction: 10
multiplication: 200
division: 2
modulus_1: 1
modulus_2: 3.2

Tagged in :

Add Comment

Click here to post a comment

Subscribe

Most Popular

Popular Video