Arithmetic, comparison and logical operators
Operators are the symbols that combine values to produce another value: adding two numbers, checking whether one is greater than another, or deciding whether two conditions are true at once. Almost every program uses them on every line, so it is worth mastering them from the start. In this lesson you will see the three most important groups: arithmetic, comparison and logical, plus several C# details that surprise people coming from other languages.
Arithmetic operators
The five arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division) and % (remainder). The one that confuses most people is division: when both operands are int, the result is also an int and the decimal part is discarded. That means 7 / 2 is 3, not 3.5. To get decimals, at least one operand must be double or decimal, for example 7 / 2.0. The % operator returns what is left over: 7 % 2 is 1, and it is used to check whether a number is even (n % 2 == 0) or to wrap around in a cycle.
int a = 7;
int b = 2;
Console.WriteLine(a + b); // 9
Console.WriteLine(a - b); // 5
Console.WriteLine(a * b); // 14
Console.WriteLine(a / b); // 3 (integer division)
Console.WriteLine(a % b); // 1 (remainder)
Console.WriteLine(a / 2.0); // 3.5
Console.WriteLine((double)a / b);// 3.5 (cast one operand first)
int hour = 23;
Console.WriteLine((hour + 3) % 24); // 2: three hours after 23hLook at the last line: the remainder lets you "wrap around", which is why it appears in clocks, shifts and circular boards. You also see the explicit conversion (double)a, called a cast, which converts the value before dividing. A very common mistake is writing (double)(a / b): there the integer division happens first and the result is already 3 before it is converted. Always convert one of the operands, not the result.
Assignment and increment shortcuts
Changing a variable based on its own value is so common that there are shortcuts: x += 5 is the same as x = x + 5, and the same goes for -=, *=, /= and %=. To add or subtract one there are two more: x++ and x--. Used as a standalone statement, x++ and ++x do the same thing. The difference appears when you use them inside another expression: y = x++ stores the old value of x first and then increments; y = ++x increments first. To keep your code easy to read, use increment only on lines of its own.
int score = 10;
score += 5; // 15
score *= 2; // 30
score -= 4; // 26
score %= 10; // 6
Console.WriteLine(score);
int x = 5;
int y = x++; // y gets 5, then x becomes 6
Console.WriteLine($"x={x} y={y}");
int p = 5;
int q = ++p; // p becomes 6, then q gets 6
Console.WriteLine($"p={p} q={q}");Comparison and logical operators
Comparison operators produce a bool, that is, true or false: == (equal), != (not equal), <, >, <= and >=. Watch out for the classic beginner mistake: = assigns a value, while == compares. Logical operators combine booleans: && means "and" (both must be true), || means "or" (one is enough) and ! flips the value. Also, && and || use short-circuit evaluation: if the result is already known after the first operand, the second one is not even evaluated. This is useful to avoid errors, for example checking that a divisor is not zero before dividing.
int age = 20;
bool hasTicket = true;
bool canEnter = age >= 18 && hasTicket;
bool isChildOrSenior = age < 12 || age >= 65;
Console.WriteLine(canEnter); // True
Console.WriteLine(isChildOrSenior); // False
Console.WriteLine(!hasTicket); // False
int total = 100;
int people = 0;
// short-circuit: the division never runs when people is 0
bool ok = people != 0 && total / people > 10;
Console.WriteLine(ok); // False, and no crashPrecedence
As in mathematics, multiplication, division and remainder are calculated before addition and subtraction, and parentheses rule over everything else. So 2 + 3 * 4 is 14, but (2 + 3) * 4 is 20. Comparisons are evaluated after arithmetic, and logical operators last. You do not need to memorize the full table: when in doubt, add parentheses. They make code more readable and remove subtle bugs.
Console.WriteLine(2 + 3 * 4); // 14
Console.WriteLine((2 + 3) * 4); // 20
Console.WriteLine(10 - 4 - 3); // 3 (left to right)
Console.WriteLine(10 + 5 > 12 && 3 * 2 == 6); // TrueПроверьте себя
Вопрос 1 из 2What is 7 / 2 with two ints?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов