Operators & Math

C# · Lesson 6 of 31 6 min read Updated

Operators are the symbols that do work on values: + adds, > compares, && combines conditions. Most of them behave as you expect from school maths, but a few have surprises that catch beginners in every batch, such as integer division and rounding.

In this lesson you will learn the arithmetic, assignment, comparison and logical operators, the useful methods of the Math class, and what happens when a number becomes too big for its type.

Arithmetic operators

C# has the usual +, -, * and /, plus % (remainder). The most important rule: when both values are integers, / does integer division and throws away the fraction.

C#
int sweets = 17;
int children = 5;

Console.WriteLine(sweets / children);
Console.WriteLine(sweets % children);
Console.WriteLine(sweets / 5.0);
Console.WriteLine((double)sweets / children);
Console.WriteLine(2 + 3 * 4);
Console.WriteLine((2 + 3) * 4);
Console.WriteLine(-17 / 5);
Console.WriteLine(-17 % 5);
Output
3
2
3.4
3.4
14
20
-3
-2

Seventeen sweets shared among five children gives each child 3, with 2 left over. To get 3.4, at least one value must be a double: write 5.0 or cast one side with (double). Note that casting after dividing, as in (double)(sweets / children), is too late: the answer is already 3.

Multiplication and division happen before addition and subtraction, so 2 + 3 * 4 is 14. Use brackets whenever the order is not obvious. Integer division rounds towards zero, so -17 / 5 is -3, and the remainder keeps the sign of the left number.

Assignment and increment

Compound assignment operators update a variable using its current value. ++ and -- add or subtract one.

C#
int score = 100;
score += 6;   // 106
score -= 4;   // 102
score *= 2;   // 204
score /= 3;   // 68
Console.WriteLine(score);

int a = 5;
int b = a++;  // b gets the old value, then a becomes 6
int c = ++a;  // a becomes 7 first, then c gets 7
Console.WriteLine($"a={a}, b={b}, c={c}");
Output
68
a=7, b=5, c=7

a++ (postfix) gives the old value and then increments; ++a (prefix) increments first and gives the new value. When ++ is on a line by itself, both forms do the same thing. Avoid using ++ inside bigger expressions; it makes code hard to read.

Comparison and logical operators

Comparison operators produce a bool: == (equal), != (not equal), <, >, <= and >=. Logical operators combine bools: && (and), || (or) and ! (not).

C#
int age = 17;
bool hasLicence = false;
string city = "Pune";

Console.WriteLine(age >= 18);
Console.WriteLine(age >= 18 && hasLicence);
Console.WriteLine(age >= 18 || age == 17);
Console.WriteLine(!hasLicence);
Console.WriteLine(city == "Pune");
Console.WriteLine(city == "pune");
Output
False
False
True
True
True
False

&& and || are short-circuit operators: if the left side already decides the answer, the right side is not even evaluated. In age >= 18 && hasLicence, C# never looks at hasLicence because age >= 18 is already false.

Unlike Java, == on two strings in C# compares their text, so city == "Pune" is true. The comparison is case-sensitive, so "pune" does not match.

The Math class

The Math class holds common mathematical functions. Most of them work with double.

C#
Console.WriteLine(Math.Pow(2, 10));
Console.WriteLine(Math.Sqrt(144));
Console.WriteLine(Math.Abs(-250));
Console.WriteLine(Math.Max(78, 91));
Console.WriteLine(Math.Ceiling(4.1));
Console.WriteLine(Math.Floor(4.9));
Console.WriteLine(Math.Clamp(120, 0, 100));
Console.WriteLine(Math.PI);
Console.WriteLine(Math.Round(2.5));
Console.WriteLine(Math.Round(3.5));
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero));
Console.WriteLine(Math.Round(1532.8249, 2));
Output
1024
12
250
91
5
4
100
3.141592653589793
2
4
3
1532.82

Math.Ceiling rounds up and Math.Floor rounds down. Math.Clamp(value, min, max) keeps a value inside a range, handy for marks that must stay between 0 and 100.

The surprise is Math.Round(2.5), which gives 2, not 3. By default, .NET uses banker's rounding: a value exactly halfway goes to the nearest even number, so 2.5 becomes 2 and 3.5 becomes 4. This avoids a bias when you round thousands of values. If you want the school rule ("halves go up"), pass MidpointRounding.AwayFromZero.

A realistic example: a GST bill

Money calculations should use decimal. Math.Round also works with decimal values.

C#
decimal price = 1299m;
decimal gstRate = 0.18m;

decimal gst = price * gstRate;
decimal total = price + gst;
decimal emi = Math.Round(total / 9, 2);

Console.WriteLine($"Price:     Rs {price}");
Console.WriteLine($"GST (18%): Rs {gst}");
Console.WriteLine($"Total:     Rs {total}");
Console.WriteLine($"9 EMIs of  Rs {emi}");
Output
Price:     Rs 1299
GST (18%): Rs 233.82
Total:     Rs 1532.82
9 EMIs of  Rs 170.31

1532.82 / 9 is 170.3133..., and rounding to two places gives 170.31. A real shop would also make sure the nine instalments add up to the total, but that is a problem for another day.

Overflow

Every number type has a limit. If an int calculation goes past int.MaxValue, by default it silently wraps around to a large negative number. You can ask C# to check instead with the checked keyword, which throws an error.

C#
int big = int.MaxValue;
big++;
Console.WriteLine(big);

int max = int.MaxValue;
int result = checked(max + 1);
Console.WriteLine(result);
Output
-2147483648
Unhandled exception. System.OverflowException: Arithmetic operation resulted in an overflow.

The second WriteLine never runs: the program stops with an exception (followed by a stack trace, not shown here). You will learn to handle exceptions in Exceptions. For values that can grow large, such as population counts or file sizes, use long.

Common mistakes

  • Integer division by accident. int percent = marks / total * 100; is 0 when marks < total. Write marks * 100 / total, or use double.
  • Expecting Math.Round(2.5) to be 3. Use MidpointRounding.AwayFromZero if you need that.
  • Using = instead of ==. if (x = 5) is a compile error in C# because x = 5 is an int, not a bool.
  • Mixing double and decimal. decimal total = price * 1.18; fails. Write 1.18m.
  • Ignoring overflow. Use long for big totals, or checked where a wrong answer would be dangerous.

Key points

  • / between two integers drops the fraction; % gives the remainder.
  • +=, -=, *=, /= update a variable; x++ returns the old value, ++x the new one.
  • Comparisons return bool; && and || short-circuit; == compares string text.
  • Math provides Pow, Sqrt, Abs, Max, Min, Ceiling, Floor, Clamp and Round.
  • Math.Round uses banker's rounding by default; pass MidpointRounding.AwayFromZero for "halves up".
  • int silently wraps on overflow unless you use checked.

Exercise

Kabir's class has 43 students, and each bench seats 2. Write a program that prints how many full benches are needed, how many students sit alone, and the total benches needed (use Math.Ceiling). Then calculate his test percentage: he scored 67 out of 80. Print the percentage as a double and rounded to one decimal place.

Show solution
C#
int students = 43;
int perBench = 2;

int fullBenches = students / perBench;
int alone = students % perBench;
double totalBenches = Math.Ceiling(students / (double)perBench);

Console.WriteLine($"Full benches: {fullBenches}");
Console.WriteLine($"Students alone: {alone}");
Console.WriteLine($"Benches needed: {totalBenches}");

int scored = 67;
int outOf = 80;
double percent = scored * 100.0 / outOf;
Console.WriteLine($"Percentage: {percent}");
Console.WriteLine($"Rounded: {Math.Round(percent, 1)}");
Output
Full benches: 21
Students alone: 1
Benches needed: 22
Percentage: 83.75
Rounded: 83.8

Dividing by (double)perBench gives 21.5, which Math.Ceiling raises to 22. Using 100.0 makes the percentage a double so the fraction is kept. 83.75 is exactly halfway, and banker's rounding picks the even digit, 83.8.

Quick Quiz

1. What does Console.WriteLine(9 / 2); print?

2. What does Math.Round(4.5) return by default?

3. After int x = 10; int y = x++;, what are x and y?

4. What happens by default when an int addition goes past int.MaxValue?

Learn C# with a mentor

Free lessons get you started. Our Programming & Software Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call