Almost every program calculates something: the total of a basket, the time left on a timer, whether a user is old enough to sign in, the score in a game. Operators are the symbols that do this work: + adds, > compares, && combines two conditions.
Most C# operators work just like in maths, but a few details trip up beginners in every language. Dividing two whole numbers throws away the fraction, so 7 / 2 is 3, not 3.5. The % operator gives a remainder, which turns out to be surprisingly useful. And = assigns a value, while == compares two values.
In this lesson you'll calculate with arithmetic operators, update variables with shortcuts like += and ++, compare values, combine conditions with logical operators, and use the built-in Math class for rounding, powers, square roots and more. You'll also generate random numbers for games and simulations.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 5 + 2 | 7 |
- | Subtract | 5 - 2 | 3 |
* | Multiply | 5 * 2 | 10 |
/ | Divide | 5 / 2 | 2 (both ints) |
/ | Divide | 5.0 / 2 | 2.5 |
% | Remainder | 5 % 2 | 1 |
- When both numbers are integers,
/does integer division and drops the fraction. Make one of them adoubleordecimalto get a decimal result. %is perfect for checking even numbers (n % 2 == 0) and for wrapping around, such as minutes past the hour.- Multiplication and division happen before addition and subtraction. Use brackets to make the order clear:
(a + b) * c.
Assignment shortcuts
int score = 10;
score += 5; // score = score + 5 -> 15
score -= 3; // 12
score *= 2; // 24
score /= 4; // 6
score++; // 7
score--; // 6++ and -- add or subtract one. On their own line, score++ and ++score do the same thing. Inside a bigger expression they differ: x++ gives the old value and then increments, while ++x increments first. Keeping ++ on its own line avoids confusion.
Comparison and logical operators
Comparisons give a bool: == equal, != not equal, <, >, <=, >=.
Logical operators combine bools:
&&(and) is true when both sides are true.||(or) is true when at least one side is true.!(not) flips true and false.
C# short-circuits: in a && b, if a is false, b isn't even evaluated. That lets you write safe checks like name != null && name.Length > 0.
The Math class
Math.Round(2.567, 2)gives2.57;Math.Floorrounds down andMath.Ceilingrounds up.Math.Pow(2, 10)gives1024;Math.Sqrt(81)gives9.Math.Max(a, b),Math.Min(a, b)andMath.Abs(-5).Math.Clamp(value, min, max)keeps a value inside a range.
For random numbers, Random.Shared.Next(1, 7) gives a whole number from 1 to 6: the upper bound is excluded.
Overflow, division by zero and NaN
Integer types have limits, and by default C# doesn't warn you when a calculation goes past them. The value simply wraps around:
int big = int.MaxValue;
big = big + 1;
Console.WriteLine(big); // -2147483648
int safe = int.MaxValue;
int result = checked(safe + 1); // throws OverflowExceptionUse checked where an overflow would be a real bug, such as totals and quantities, or switch to long for bigger numbers.
Dividing by zero behaves differently depending on the type:
| Expression | Result |
|---|---|
10 / 0 with int values | DivideByZeroException |
1m / 0m with decimal values | DivideByZeroException |
1.0 / 0 | Infinity (double.PositiveInfinity) |
0.0 / 0 | NaN, meaning "not a number" |
NaN is unusual because it isn't equal to anything, not even itself, so check for it with double.IsNaN(x) rather than ==.
Remainders with negative numbers
The % operator keeps the sign of the left-hand number, so -7 % 3 is -1, not 2. That surprises people who expect a result between 0 and the divisor, for example when moving backwards through a list of days. A common fix is to add the divisor and take the remainder again:
int index = -7;
int wrapped = ((index % 3) + 3) % 3; // 2The same trick keeps an index inside an array of any length: replace 3 with array.Length.
C# Basics Syntax
Operators
int a = 7 / 2; // 3
double b = 7 / 2.0; // 3.5
int r = 7 % 2; // 1
x += 1; x++; x--;
bool ok = age >= 18 && hasTicket;
bool any = isAdmin || isOwner;
bool not = !isBanned;
Math.Round(2.345, 2) // 2.35
Math.Pow(3, 2) // 9
Math.Clamp(150, 0, 100) // 100
Random.Shared.Next(1, 7) // 1 to 6C# Basics Summary
- + - * / and % do arithmetic; int / int drops the fraction.
- % gives the remainder, useful for even checks and wrapping around.
- += -= *= /= and ++ -- update variables in place.
- Comparisons return bool; && || and ! combine them, with short-circuiting.
- The Math class rounds, powers, square roots, clamps and more.
C# Basics Examples
Each example shows the code, the output it produces and what each part does.
Splitting a bill
int total = 95;
int people = 4;
Console.WriteLine(total / people);
Console.WriteLine(total % people);
Console.WriteLine((double)total / people);
decimal bill = 95.00m;
decimal tip = bill * 0.15m;
decimal each = (bill + tip) / people;
Console.WriteLine(Math.Round(each, 2));23
3
23.75
27.31Line-by-line explanation
- Line 4Both values are ints, so the result is a whole number.
- Line 5% gives what's left over after dividing evenly.
- Line 6Casting one side to double gives a decimal answer.
- Lines 9 to 1095 plus a 14.25 tip is 109.25, and 109.25 divided by 4 is 27.3125.
- Line 11Math.Round keeps two decimal places for a price.
Updating a score
int score = 0;
score += 50;
score *= 2;
score -= 15;
score++;
Console.WriteLine($"Score: {score}");
int lives = 3;
int before = lives--;
Console.WriteLine($"{before} {lives}");
int minutes = 135;
Console.WriteLine($"{minutes / 60}h {minutes % 60}m");Score: 86
3 2
2h 15mLine-by-line explanation
- Lines 2 to 50 + 50 = 50, doubled is 100, minus 15 is 85, plus one is 86.
- Line 9lives-- gives the old value, 3, and then decreases lives to 2.
- Line 13Integer division gives the hours and % gives the remaining minutes.
Conditions and the Math class
int age = 17;
bool hasPermission = true;
bool canJoin = age >= 18 || hasPermission;
Console.WriteLine(canJoin);
string? name = null;
bool valid = name != null && name.Length > 2;
Console.WriteLine(valid);
Console.WriteLine(Math.Pow(2, 8));
Console.WriteLine(Math.Sqrt(144));
Console.WriteLine(Math.Clamp(130, 0, 100));
Console.WriteLine(Math.Round(2.5));
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero));True
False
256
12
100
2
3Line-by-line explanation
- Line 3|| is true because one side, hasPermission, is true.
- Line 7&& short-circuits: name is null, so name.Length is never evaluated and nothing crashes.
- Lines 10 to 11Pow and Sqrt return doubles; whole-number doubles print without a decimal point.
- Line 12Clamp limits 130 to the maximum of 100.
- Lines 13 to 14Default rounding sends 2.5 to the even number 2; AwayFromZero gives 3.
Common C# Basics Mistakes
Expecting a decimal from integer division
double average = 7 / 2; // 3, because the division happens with intsdouble average = 7 / 2.0; // 3.5Using = instead of ==
if (count = 10) { } // error CS0029: cannot convert int to boolif (count == 10) { }Off-by-one with Random.Next
int dice = Random.Shared.Next(1, 6); // only 1 to 5int dice = Random.Shared.Next(1, 7); // 1 to 6C# Basics in Real Projects
Operators in real code
Checkout code multiplies quantities by prices and applies discounts with decimal arithmetic. Pagination uses integer division and % to work out the number of pages and items on the last page. Games use Math.Clamp to keep health between 0 and 100, and Random.Shared for dice rolls and loot drops. Access rules combine conditions such as isAdmin || (isOwner && !isLocked).
C# Basics FAQ
Why does 7 / 2 equal 3 in C#?
When both operands are integers, / performs integer division and throws away the fraction. Make at least one operand a double or decimal, such as 7.0 / 2 or (double)a / b, to get 3.5. Casting the result instead, as in (double)(a / b), is too late because the fraction has already gone.
How do I round to 2 decimal places in C#?
Use Math.Round(value, 2). Remember that the default mode is banker's rounding, so pass MidpointRounding.AwayFromZero if you want halves to round up. If you only need two decimals for display, format the value instead with {value:F2} and keep the full number for calculations.
What is the difference between x++ and ++x?
Both add one to x. Used inside a larger expression, x++ gives the value from before the increment and ++x gives the value after it. When the statement is just x++; on its own line, there's no difference.
How do I calculate a power or square root in C#?
C# has no power operator, and ^ means exclusive-or, not "to the power of". Use Math.Pow(2, 10) for powers and Math.Sqrt(81) for square roots; both return a double. Cast the result with (int) if you need a whole number.
What is the difference between & and && in C#?
&& is the conditional "and": it skips the right-hand side when the left side is already false. & evaluates both sides every time, and on integers it performs a bitwise AND. For ordinary conditions use && and ||, so that checks like s != null && s.Length > 0 stay safe.
C# Basics Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code to add 10 to points.
int points = 5;
points 10;
What does this print?
Console.WriteLine(17 % 5);
What does this print?
int x = 5;
int y = x++ + 1;
Console.WriteLine($"{x} {y}");
Why is name != null && name.Length > 0 safe when name is null?
What does Math.Round(3.5) return by default?
C# Basics Quiz
5 questions to check what you learned.
What is
10 / 4in C# when both are ints?- 2.5
- 3
- 2
- 2.0
What does the || operator mean?
- And
- Not
- Equal
- Or
What range does
Random.Shared.Next(1, 11)return?- 0 to 10
- 1 to 11
- 0 to 11
- 1 to 10
What does
Math.Clamp(-5, 0, 10)return?- -5
- 0
- 10
- 5
Which expression checks whether n is even?
- n / 2 == 0
- n % 2 == 1
- n % 2 == 0
- n == 2