C# Tutorial menu

C# Operators

Operators do work on values: they calculate, compare and combine them.

Arithmetic Operators

OperatorMeaningExampleResult
+Add12 + 517
-Subtract12 - 57
*Multiply12 * 560
/Divide12 / 52
%Remainder12 % 52
++Add 1x++
--Subtract 1x--

Example

csharp
int totalDays = 45;
int weeks = totalDays / 7;
int days = totalDays % 7;
Console.WriteLine($"{weeks} weeks and {days} days");
Console.WriteLine(45 / 7.0);
Output
6 weeks and 3 days
6.428571428571429

Dividing two int values gives an int and drops the decimal part. Use at least one double (like 7.0) to get the decimal answer.

Assignment Operators

OperatorSame as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5
x %= 5x = x % 5

Example

csharp
int points = 100;
points += 50;   // bonus
points -= 30;   // penalty
points *= 2;    // double weekend
Console.WriteLine(points);
Output
240

Comparison Operators

These give a bool: True or False.

OperatorMeaning
==Equal to
!=Not equal to
> / <Greater / less than
>= / <=Greater or equal / less or equal

Logical Operators

  • && and: both sides must be true
  • || or: at least one side must be true
  • ! not: reverses the value

Example

csharp
int age = 17;
bool withParent = true;

Console.WriteLine(age >= 18);
Console.WriteLine(age >= 18 || withParent);
Console.WriteLine(!withParent);
Output
False
True
False

The Math Class

C# has a built-in Math class for common calculations:

MethodExampleResult
Math.Max(a, b)Math.Max(4, 9)9
Math.Min(a, b)Math.Min(4, 9)4
Math.Sqrt(x)Math.Sqrt(64)8
Math.Pow(x, y)Math.Pow(2, 5)32
Math.Round(x)Math.Round(4.6)5
Math.Abs(x)Math.Abs(-7)7

Example

csharp
double bill = 2347.567;
Console.WriteLine(Math.Round(bill, 2));
Console.WriteLine(Math.Sqrt(144));
Output
2347.57
12

Order of Operations

*, / and % happen before + and -. Use brackets to be clear:

Example

csharp
int a = 6 + 4 * 2;     // 14
int b = (6 + 4) * 2;   // 20

Exercise

Exercise

What does Console.WriteLine(20 % 6); print?

Learn C# with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp