Operators and expressions
Do math and logic in C# — and avoid the classic integer-division trap.
11 min read
You will learn
- Use arithmetic operators, including integer division and remainder
- Combine conditions with &&, || and !
- Use compound assignment and increment operators
- Know how operator precedence works
Expressions
An expression is anything that produces a value: 42, price * quantity, age >= 18. Operators combine values into new values. You already know most of them from math class — with a couple of programming twists.
Arithmetic
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 5 / 2 | 2 (!) |
% | Remainder | 5 % 2 | 1 |
The integer division trap
When both sides of / are integers, C# does integer division and throws away the fraction:
Console.WriteLine(7 / 2); // 3
Console.WriteLine(7 / 2.0); // 3.5 — one double is enough
Console.WriteLine(7.0 / 2); // 3.5
int total = 7, count = 2;
double average = total / count; // 3 — the division happened as int!
double correct = (double)total / count; // 3.5Watch out
double average = total / count; is one of the most common beginner bugs. The type of the variable on the left doesn't matter — the division is computed with the types on the right.
Remainder % is surprisingly useful
int minutes = 135;
Console.WriteLine($"{minutes / 60}h {minutes % 60}m"); // 2h 15m
bool isEven = number % 2 == 0; // even numbers have no remainder
int lastDigit = 1234 % 10; // 4Assignment shortcuts
int score = 10;
score += 5; // score = score + 5 → 15
score -= 3; // → 12
score *= 2; // → 24
score /= 4; // → 6
score++; // add one → 7
score--; // subtract one → 6Comparison operators
Comparisons produce a bool:
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
<, > | less than, greater than |
<=, >= | less/greater than or equal |
bool canVote = age >= 18;
bool isZero = balance == 0;Note
= assigns, == compares. Writing if (x = 5) is a compile error in C# — the compiler protects you from this classic bug.
Logical operators
| Operator | Meaning | True when… |
|---|---|---|
&& | AND | both sides are true |
|| | OR | at least one side is true |
! | NOT | the value is false |
bool canRent = age >= 25 && hasLicense;
bool isWeekend = day == "Saturday" || day == "Sunday";
bool isClosed = !isOpen;&& and || short-circuit: if the left side already decides the answer, the right side isn't evaluated. That makes this safe:
if (name != null && name.Length > 0) { ... } // Length is never read when name is nullPrecedence
Like in math, *, / and % bind tighter than + and -, and comparisons come before &&, which comes before ||:
int a = 2 + 3 * 4; // 14
int b = (2 + 3) * 4; // 20When in doubt, add parentheses — they make intent obvious to the next reader, too.
The Math class
For anything beyond the basics, use Math:
Math.Max(3, 7); // 7
Math.Abs(-5); // 5
Math.Pow(2, 10); // 1024
Math.Sqrt(81); // 9
Math.Round(2.567, 2); // 2.57Try it
C# runtime not loaded
Key takeaways
/between two integers drops the fraction — make one side adoublewhen you need decimals.%gives the remainder: great for even/odd checks and splitting units.&&,||and!combine conditions, and&&/||short-circuit.- Use parentheses whenever precedence isn't obvious.
Exercise
Implement three small methods. ToHoursAndMinutes(125) should return "2h 5m". CelsiusToFahrenheit converts using F = C × 9 / 5 + 32. IsLeapYear returns true for years divisible by 4, except years divisible by 100 — unless they're also divisible by 400.
C# runtime not loaded
Hint 1
Integer division drops the remainder: 125 / 60 is 2. The remainder operator gives what's left: 125 % 60 is 5.
Hint 2
For Fahrenheit, celsius is a double so the math stays in floating point: celsius * 9 / 5 + 32.
Hint 3
Translate the rule literally: (divisible by 4 AND NOT divisible by 100) OR divisible by 400.
Show solution
string ToHoursAndMinutes(int totalMinutes) => $"{totalMinutes / 60}h {totalMinutes % 60}m";
double CelsiusToFahrenheit(double celsius) => celsius * 9 / 5 + 32;
bool IsLeapYear(int year) => (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
Console.WriteLine(ToHoursAndMinutes(125));
Console.WriteLine(CelsiusToFahrenheit(100));
Console.WriteLine(IsLeapYear(2024));Quiz
4 questions · 3 correct to pass1.What is the value of `7 / 2` in C#?
2.What is `17 % 5`?
3.After `int x = 5; x += 3; x++;`, what is x?
4.What does `2 + 3 * 4` evaluate to?
To complete this lesson
- ○ Solve the exercise
- ○ Pass the quiz (3/4 correct)