Operators and expressions
Arithmetic, comparison, logical and assignment operators, integer division, remainders, precedence and increment.
+ or >. An expression is any piece of code that produces a value: price * quantity, age >= 18, or just 5.
Try the operators
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | 7 + 2 | 9 | |
- | 7 - 2 | 5 | |
* | 7 * 2 | 14 | |
/ | 7 / 2 · 7.0 / 2 | 3 · 3.5 | |
% | 7 % 2 | 1 |
int total = 245;int count = 3; double wrong = total / count; // 81 (int division first!)double right = (double)total / count; // 81.666... Console.WriteLine(wrong);Console.WriteLine(right.ToString("F2")); Output
81 81.67
Comparison operators give a bool
| Operator | Meaning |
|---|---|
== | |
!= | |
< > | |
<= >= |
Logical operators combine conditions
| Operator | Name | True when… |
|---|---|---|
&& | ||
|| | ||
! |
int age = 22;bool hasId = true; bool canEnter = age >= 18 && hasId; // truebool discount = age < 12 || age > 60; // falsebool isMinor = !(age >= 18); // false Console.WriteLine($"{canEnter} {discount} {isMinor}"); Output
True False False
&& and || are short-circuit: if the left side already decides the answer, the right side is not evaluated. x != 0 && 10 / x > 1 is safe even when x is 0.
Assignment shortcuts and ++ / --
int score = 10;score += 5; // score = score + 5 → 15score -= 3; // → 12score *= 2; // → 24score /= 4; // → 6score %= 4; // → 2score++; // add 1 → 3score--; // subtract 1 → 2 int a = 5;int b = a++; // b = 5, then a becomes 6 (post-increment)int c = ++a; // a becomes 7 first, then c = 7 (pre-increment)Console.WriteLine($"{score} {a} {b} {c}"); Output
2 7 5 7
Precedence: which runs first?
*, /, % before + and -; then comparisons; then &&; then ||; assignment last. When in doubt, add brackets. They make code clearer even when not required.
int r1 = 2 + 3 * 4; // 14, not 20int r2 = (2 + 3) * 4; // 20bool ok = 5 > 3 && 2 > 1 || false; // (true && true) || false → true Practice
int totalMinutes = 135;, print it as hours and minutes, like “2 h 15 min”.
Show a hint
Show the solution
int totalMinutes = 135;int hours = totalMinutes / 60;int minutes = totalMinutes % 60;Console.WriteLine($"{hours} h {minutes} min"); Output
2 h 15 min
Remember
int / intis integer division; cast one side todoublefor decimals.%gives the remainder: great for even/odd checks and splitting units.Comparisons give bool; combine them with&&,||,!(short-circuit).=assigns,==compares. Use brackets to make precedence obvious.