Csharp/CSharp Tutorial/Operator/Arithmetic Operators
Arithmetic Operators
C# defines the following arithmetic operators:
Operator Meaning + Addition - Subtraction (also unary minus)
Multiplication / Division % Modulus ++ Increment -- Decrement
When / is applied to an integer, any remainder will be truncated.
For example, 10/3 will equal 3 in integer division.
using System;
class MainClass
{
static void Main(string[] args)
{
int a,b,c,d,e,f;
a = 1;
b = a + 6;
Console.WriteLine(b);
c = b - 3;
Console.WriteLine(c);
d = c * 2;
Console.WriteLine(d);
e = d / 2;
Console.WriteLine(e);
f = e % 2;
Console.WriteLine(f);
}
}
Compound operator
using System;
public class CompoundAssApp
{
public static void Main(string[] args)
{
int nCalc = 10;
nCalc += 5;
Console.WriteLine(nCalc);
nCalc -= 3;
Console.WriteLine(nCalc);
nCalc *= 2;
Console.WriteLine(nCalc);
nCalc /= 4;
Console.WriteLine(nCalc);
nCalc %= 4;
Console.WriteLine(nCalc);
}
}
postfix and prefix
using System;
class MainClass
{
static void Main(string[] args)
{
int a,b,c,d,e,f;
a = 1;
b = a + 1;
b = b - 1;
c = 1; d = 2;
++c;
Console.WriteLine(c);
--d;
Console.WriteLine(d);
e = --c;
Console.WriteLine(e);
f = c--;
Console.WriteLine(f);
}
}
2 1 1 1
shortcut Operators
using System;
class MainClass
{
static void Main(string[] args)
{
int a, b, c, d, e;
a = 1;
a += 1;
Console.WriteLine(a);
b = a;
b -= 2;
Console.WriteLine(b);
c = b;
c *= 3;
Console.WriteLine(c);
d = 4;
d /= 2;
Console.WriteLine(d);
e = 23;
e %= 3;
Console.WriteLine(e);
}
}
2 0 0 2 2