π Lesson 2.2: Operators and Expressions
Now that your programs can store data, let's make them calculate. You'll do arithmetic, compare values, and combine true/false conditions β the raw material for every decision a program makes.
π― Learning Objectives
By the end of this lesson, you will be able to:
- Use arithmetic operators, including the remainder operator
% - Explain the surprise of integer division and how to avoid it
- Compare values with comparison operators to produce
boolresults - Combine conditions with the logical operators
&&,||, and! - Use assignment shortcuts and understand operator precedence
Estimated Time: 45 minutes
Project: Build a small calculator that also answers true/false questions about its result.
In This Lesson
Expressions and Operators
An operator is a symbol that performs an action on values β like + for addition. An expression is any piece of code that produces a value, such as 3 + 4 (which produces 7).
π Definitions
Operator: a symbol that performs an operation (+, -, >, &&, β¦).
Operand: a value the operator works on. In 3 + 4, the operands are 3 and 4.
Expression: code that evaluates to a single value. 3 + 4 evaluates to 7.
You can store an expression's result in a variable, because the expression is replaced by its value when the program runs:
int total = 3 + 4; // the expression 3 + 4 becomes 7
Console.WriteLine(total); // 7
Arithmetic Operators
These do exactly what you'd expect from math class β with one newcomer, the remainder operator:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 10 / 2 | 5 |
% | Remainder (modulo) | 7 % 3 | 1 |
The remainder operator % (often called "modulo") gives you what's left over after division. It's more useful than it first looks:
Console.WriteLine(7 % 3); // 1 (7 = 2*3 + 1, remainder 1)
Console.WriteLine(10 % 2); // 0 (evenly divisible)
Console.WriteLine(10 % 3); // 1
π‘ A classic use of %: even or odd
A number is even when dividing by 2 leaves no remainder. So number % 2 == 0 is true for even numbers and false for odd ones. You'll use this pattern constantly.
The Integer Division Trap
Here's a genuine surprise that trips up nearly every beginner. What is 7 / 2?
int a = 7;
int b = 2;
Console.WriteLine(a / b); // 3 β NOT 3.5 !
β οΈ Why 3 and not 3.5?
When both operands are whole numbers (int), C# performs integer division: it divides and then throws away any fractional part (it does not round). 7 / 2 is 3, and 7 % 2 is the leftover 1.
To get the decimal answer, at least one operand must be a decimal type (double or decimal):
double a = 7;
double b = 2;
Console.WriteLine(a / b); // 3.5
// or force it inline by making a value a double:
Console.WriteLine(7.0 / 2); // 3.5
Console.WriteLine(7 / 2.0); // 3.5
π‘ Rule of thumb:int / intgives anint(fraction discarded). If you want decimals, make sure at least one side is adoubleordecimal.
Comparison Operators
Comparison operators ask a yes/no question about two values. Their result is always a bool β true or false. These are the seeds of every decision a program makes (next lesson).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
> | Greater than | 5 > 3 | true |
< | Less than | 5 < 3 | false |
>= | Greater than or equal to | 5 >= 5 | true |
<= | Less than or equal to | 3 <= 2 | false |
int age = 20;
bool isAdult = age >= 18;
Console.WriteLine(isAdult); // True
Console.WriteLine(age == 21); // False
Console.WriteLine(age != 21); // True
β οΈ = vs == β the #1 beginner mix-up
One equals sign = assigns a value. Two equals signs == compare for equality. x = 5 puts 5 into x; x == 5 asks "is x equal to 5?" Mixing these up is extremely common β watch for it.
Logical Operators
Logical operators combine or flip bool values, letting you build more complex conditions like "old enough and has a ticket."
| Operator | Name | True when⦠|
|---|---|---|
&& | AND | β¦both sides are true |
|| | OR | β¦at least one side is true |
! | NOT | β¦flips true to false and false to true |
int age = 20;
bool hasTicket = true;
// AND: both must be true
Console.WriteLine(age >= 18 && hasTicket); // True
// OR: at least one must be true
Console.WriteLine(age < 13 || age > 65); // False
// NOT: flips the value
Console.WriteLine(!hasTicket); // False
A helpful way to picture AND and OR is a truth table:
| A | B | A && B | A || B |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
β Read them like English
age >= 18 && hasTicket reads as "age is at least 18 and has a ticket." || is "or," and ! is "not." Reading conditions aloud is a great habit for getting them right.
Assignment Shortcuts
Updating a variable based on its own value is so common that C# offers compact shortcuts:
| Shortcut | Means |
|---|---|
x += 5; | x = x + 5; |
x -= 5; | x = x - 5; |
x *= 2; | x = x * 2; |
x /= 2; | x = x / 2; |
x++; | add 1 to x (x = x + 1) |
x--; | subtract 1 from x (x = x - 1) |
int score = 10;
score += 5; // now 15
score++; // now 16
score -= 6; // now 10
Console.WriteLine(score); // 10
π‘ ++ is everywhere
The "add one" operator ++ is used constantly for counting β for example, counting through the steps of a loop, which you'll see in Lesson 3.2.
Operator Precedence
When several operators appear together, C# follows precedence rules β the same "order of operations" you learned in math. Multiplication and division happen before addition and subtraction:
Console.WriteLine(2 + 3 * 4); // 14, not 20 (3*4 first, then +2)
Console.WriteLine((2 + 3) * 4); // 20 (parentheses first)
π‘ When in doubt, add parentheses. Even when they're not strictly required, parentheses make your intent obvious to anyone reading the code β including future you. Clarity beats cleverness.
A simplified order, highest to lowest:
- Parentheses
( ) - Multiplication, division, remainder:
*/% - Addition, subtraction:
+- - Comparisons:
<><=>= - Equality:
==!= - Logical AND
&&, then logical OR||
Exercise & Quiz
ποΈ Exercise: A Mini Calculator
Objective: Combine arithmetic, comparison, and logical operators in one small program.
Instructions:
- Create a new project called
Calc. - Declare two
intvariables,a = 17andb = 5. - Print their sum, difference, product, integer quotient (
a / b), and remainder (a % b). - Print whether
ais greater thanb(a comparison β bool). - Print whether
ais even and greater than 10 (combine%,==, and&&).
Starter Code:
int a = 17;
int b = 5;
Console.WriteLine("Sum: " + (a + b));
// TODO: difference, product, quotient, remainder
// TODO: is a greater than b?
// TODO: is a even AND greater than 10?
π‘ Hint
"Even" is a % 2 == 0. Combine two conditions with &&. Wrap arithmetic in parentheses when concatenating with +, e.g. "Sum: " + (a + b), so C# adds the numbers before joining the text.
β Solution
int a = 17;
int b = 5;
Console.WriteLine("Sum: " + (a + b)); // 22
Console.WriteLine("Difference: " + (a - b)); // 12
Console.WriteLine("Product: " + (a * b)); // 85
Console.WriteLine("Quotient: " + (a / b)); // 3 (integer division)
Console.WriteLine("Remainder: " + (a % b)); // 2
Console.WriteLine("a > b? " + (a > b)); // True
Console.WriteLine("Even and > 10? " + (a % 2 == 0 && a > 10)); // False
Output:
Sum: 22
Difference: 12
Product: 85
Quotient: 3
Remainder: 2
a > b? True
Even and > 10? False
(a is 17, which is odd, so the last line is False β try changing a to 18 and see it flip to True.)
π― Quick Quiz
Question 1: What is the value of 7 / 2 when both are int?
Question 2: Which operator checks whether two values are equal?
Question 3: When is A && B true?
Summary
π Key Takeaways
- Arithmetic:
+ - * /and%(remainder).%is great for even/odd and cycling. - Integer division trap:
int / intdiscards the fraction. Use adouble/decimalto keep decimals. - Comparisons (
==,!=,<,>,<=,>=) produce abool. Don't confuse=(assign) with==(compare). - Logical operators:
&&(AND),||(OR),!(NOT) combine conditions. - Shortcuts like
+=and++update variables concisely; precedence follows math order β use parentheses for clarity.
π Additional Resources
- Arithmetic operators β reference
- Comparison operators β reference
- Boolean logical operators β reference
π What's Next?
You can now compute values and produce true/false results. In Lesson 2.3: Console Input and Output, you'll read what the user types, turn that text into numbers, and print results cleanly with string interpolation β making your programs genuinely interactive.
π Great work!
Your programs can now calculate and reason about values. Next, let's let the user talk to them.