Operators and Expressions

Beginner 15 min read Lesson 4 of 13

What are Operators?

Operators are symbols that tell C# to perform specific operations on data. Think of them like the buttons on a calculator - they help you add, subtract, compare, and combine values.

Arithmetic
Math calculations

Comparison
Compare values

Logical
True/False decisions

Arithmetic Operators

Use these operators to do math calculations. They work like a calculator.

Operator Meaning Example Result
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 6 * 7 42
/ Division 15 / 3 5
% Modulus (Remainder) 10 % 3 1
Important! When you divide two integers, C# gives you an integer result (no decimals). Use double if you need decimal results.
// ===== BASIC MATH =====
int a = 10;
int b = 3;

int sum = a + b;           // 13
int difference = a - b;      // 7
int product = a * b;        // 30
int quotient = a / b;      // 3 (not 3.33 - integer division)
int remainder = a % b;     // 1 (10 divided by 3 leaves 1)

// If you want decimal result, use double
double exact = 10.0 / 3;    // 3.333...

Comparison Operators

Use these operators to compare values. They always return true or false.

Operator Meaning Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 10 > 5 true
< Less than 3 < 7 true
>= Greater or equal 10 >= 10 true
<= Less or equal 5 <= 10 true
// ===== COMPARING VALUES =====
int x = 5;
int y = 10;

bool isEqual = x == y;        // false (5 is not 10)
bool isNotEqual = x != y;     // true (5 is not 10)
bool isGreater = x > y;        // false (5 is not greater than 10)
bool isLess = x < y;           // true (5 is less than 10)
bool isGreaterOrEqual = x >= y;  // false
bool isLessOrEqual = x <= y;     // true

Logical Operators

Use these operators to combine conditions. They help you make complex decisions.

Operator Meaning Example Result
&& AND (both must be true) true && true true
|| OR (at least one is true) true || false true
! NOT (flips the value) !true false
// ===== LOGICAL OPERATORS IN ACTION =====
int age = 20;
bool hasLicense = true;
bool hasPassedTest = false;

// AND - both conditions must be true
bool canDrive = age >= 18 && hasLicense;  // true

// OR - at least one condition must be true
bool canRentCar = hasLicense || hasPassedTest;  // true

// NOT - flips the value
bool isMinor = !(age >= 18);  // false (age is 20, so not a minor)

// Complex condition
bool canVote = age >= 18 && (hasLicense || hasPassedTest);
Remember: && is like saying "and" - everything must be true. || is like saying "or" - at least one must be true.

Assignment Operators

These operators assign values to variables. The = operator is the most basic one.

Operator Meaning Example Result
= Assign value x = 5 x is 5
+= Add and assign x += 3 x = x + 3
-= Subtract and assign x -= 2 x = x - 2
*= Multiply and assign x *= 2 x = x * 2
/= Divide and assign x /= 3 x = x / 3
%= Modulus and assign x %= 3 x = x % 3
// ===== ASSIGNMENT SHORTCUTS =====
int num = 5;

num += 3;   // num = 8  (same as: num = num + 3)
num -= 2;   // num = 6  (same as: num = num - 2)
num *= 2;   // num = 12 (same as: num = num * 2)
num /= 3;   // num = 4  (same as: num = num / 3)
num %= 3;   // num = 1  (same as: num = num % 3)

// These shortcuts are very common in C#

Increment and Decrement

These operators increase or decrease a number by 1.

Increment (++)

Adds 1 to a variable

count++; // count = count + 1
Decrement (--)

Subtracts 1 from a variable

count--; // count = count - 1
// ===== INCREMENT (++) =====
int count = 5;

count++;               // count = 6 (post-increment)
++count;              // count = 7 (pre-increment)

// ===== DECREMENT (--) =====
count--;               // count = 6 (post-decrement)
--count;              // count = 5 (pre-decrement)

// Pre vs Post: When used alone, they do the same thing.
// But in expressions, they differ:

int x = 5;
int y = x++;          // y = 5, then x becomes 6
                        
int a = 5;
int b = ++a;          // a becomes 6, then b = 6

Operator Precedence (Order of Operations)

Like in math, some operators are evaluated before others. Use parentheses () to control the order.

// ===== ORDER OF OPERATIONS =====
// 1. Parentheses
// 2. Multiplication, Division, Modulus
// 3. Addition, Subtraction

int result = 5 + 3 * 2;   // 11 (3*2=6, then 5+6=11)
int result2 = (5 + 3) * 2; // 16 (5+3=8, then 8*2=16)

// Use parentheses to be clear and avoid mistakes
int total = (price + tax) * quantity;
Tip: When in doubt, use parentheses () to make your intention clear!

Real-World Examples

🧮 Calculate Total Price
decimal total = price + (price * taxRate);
📊 Average Score
double average = (score1 + score2 + score3) / 3;
✅ Eligibility Check
bool eligible = age >= 18 && hasLicense;
🔄 Round Robin
int nextPlayer = (currentPlayer + 1) % totalPlayers;

Quick Reference

Category Operators Use
Arithmetic + - * / % Math calculations
Comparison == != < > <= >= Compare values
Logical && || ! Combine conditions
Assignment = += -= *= /= %= Assign values
Increment/Decrement ++ -- Add or subtract 1

Exercise: Pizza Order Calculator

Task: Create a pizza order calculator using operators.

Instructions:
  1. Create a console application called "PizzaOrder"
  2. Declare variables for:
    • Pizza price (decimal) - $12.99
    • Topping price (decimal) - $2.50 per topping
    • Number of toppings (int)
    • Tax rate (decimal) - 0.08 (8%)
    • Number of pizzas (int)
  3. Calculate:
    • Base cost = pizza price × number of pizzas
    • Topping cost = topping price × number of toppings
    • Subtotal = base cost + topping cost
    • Tax amount = subtotal × tax rate
    • Total = subtotal + tax amount
  4. Print all the values with proper formatting
  5. Use at least 3 different operators (+, *, %, etc.)
  6. Use string interpolation to display the total
Hint: Your output should look like:
Pizza Price: $12.99
Number of Pizzas: 3
Toppings per Pizza: 2
--------------------------------
Base Cost: $38.97
Topping Cost: $15.00
Subtotal: $53.97
Tax (8%): $4.32
--------------------------------
Total: $58.29
Key Takeaway

Operators are the building blocks of calculations and decisions in C#. Use arithmetic operators for math, comparison operators to compare values, logical operators for complex conditions, and assignment operators to update values.

Test Your Knowledge - Take Quiz