C# - Arithmatic Operators
Advertisements
Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10 and variable B holds 20 then:
| Operator | Description | Example |
|---|---|---|
| + | Adds two operands | A + B will give 30 |
| - | Subtracts second operand from the first | A - B will give -10 |
| * | Multiply both operands | A * B will give 200 |
| / | Divide numerator by de-numerator | B / A will give 2 |
| % | Modulus Operator and remainder of after an integer division | B % A will give 0 |
| ++ | Increment operator increases integer value by one | A++ will give 11 |
| -- | Decrement operator decreases integer value by one | A-- will give 9 |
Example
Try following example to understand all the arithmetic operators available in C#:
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces following result:
Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2 Line 5 - Value of c is 1 Line 6 - Value of c is 21 Line 7 - Value of c is 22