Skip to main content

πŸ“ 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 bool results
  • 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
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division10 / 25
%Remainder (modulo)7 % 31

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 / int gives an int (fraction discarded). If you want decimals, make sure at least one side is a double or decimal.

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 to5 == 5true
!=Not equal to5 != 3true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal to5 >= 5true
<=Less than or equal to3 <= 2false
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:

ABA && BA || B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

βœ… 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:

ShortcutMeans
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:

  1. Parentheses ( )
  2. Multiplication, division, remainder: * / %
  3. Addition, subtraction: + -
  4. Comparisons: < > <= >=
  5. Equality: == !=
  6. Logical AND &&, then logical OR ||

Exercise & Quiz

πŸ‹οΈ Exercise: A Mini Calculator

Objective: Combine arithmetic, comparison, and logical operators in one small program.

Instructions:

  1. Create a new project called Calc.
  2. Declare two int variables, a = 17 and b = 5.
  3. Print their sum, difference, product, integer quotient (a / b), and remainder (a % b).
  4. Print whether a is greater than b (a comparison β†’ bool).
  5. Print whether a is 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 / int discards the fraction. Use a double/decimal to keep decimals.
  • Comparisons (==, !=, <, >, <=, >=) produce a bool. 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

πŸš€ 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.