Module 3: Operators and Expressions
Chapter 3 • Beginner
Operators and Expressions
Operators are symbols that perform operations on variables and values. Expressions combine variables, operators, and values to produce results.
What are Operators?
Operators are special symbols that tell the compiler to perform specific mathematical, logical, or relational operations.
Expressions are combinations of operators, variables, and values that evaluate to a single value.
Types of Operators
1. Arithmetic Operators
Perform mathematical operations.
| Operator | Operation | Example | Result |
|---|---|---|---|
| `+` | Addition | `5 + 3` | `8` |
| `-` | Subtraction | `10 - 4` | `6` |
| `*` | Multiplication | `3 * 4` | `12` |
| `/` | Division | `15 / 3` | `5` |
| `%` | Modulus (remainder) | `10 % 3` | `1` |
Example:
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 1
Important Notes:
- Integer division truncates (drops decimal part)
- Modulus only works with integers
- Division by zero causes runtime error
2. Assignment Operators
Assign values to variables.
| Operator | Example | Equivalent To |
|---|---|---|
| `=` | `x = 5` | `x = 5` |
| `+=` | `x += 3` | `x = x + 3` |
| `-=` | `x -= 2` | `x = x - 2` |
| `*=` | `x *= 4` | `x = x * 4` |
| `/=` | `x /= 2` | `x = x / 2` |
| `%=` | `x %= 3` | `x = x % 3` |
Example:
int x = 10;
x += 5; // x is now 15
x -= 3; // x is now 12
x *= 2; // x is now 24
x /= 4; // x is now 6
3. Increment and Decrement Operators
Increase or decrease value by 1.
| Operator | Name | Effect |
|---|---|---|
| `++x` | Pre-increment | Increment first, then use |
| `x++` | Post-increment | Use first, then increment |
| `--x` | Pre-decrement | Decrement first, then use |
| `x--` | Post-decrement | Use first, then decrement |
Example:
int a = 5;
int b = ++a; // a becomes 6, b becomes 6
int c = a++; // c becomes 6, a becomes 7
int x = 10;
int y = --x; // x becomes 9, y becomes 9
int z = x--; // z becomes 9, x becomes 8
4. Relational Operators
Compare two values and return true or false.
| 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 | `5 >= 5` | `true` |
| `<=` | Less than or equal | `5 <= 3` | `false` |
Example:
int age = 20;
bool isAdult = age >= 18; // true
bool isTeen = age < 18; // false
bool isExactly20 = age == 20; // true
5. Logical Operators
Combine boolean expressions.
| Operator | Name | Description | Example | ||||
|---|---|---|---|---|---|---|---|
| `&&` | AND | Both must be true | `true && false` = `false` | ||||
| ` | ` | OR | At least one true | `true | false` = `true` | ||
| `!` | NOT | Reverses boolean | `!true` = `false` |
Truth Tables:
AND (&&):
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
OR (||):
| A | B | A | B | |
|---|---|---|---|---|
| true | true | true | ||
| true | false | true | ||
| false | true | true | ||
| false | false | false |
NOT (!):
| A | !A |
|---|---|
| true | false |
| false | true |
Example:
int age = 20;
bool hasLicense = true;
bool canDrive = age >= 18 && hasLicense; // true
int score = 85;
bool passed = score >= 60 || score == 100; // true
bool isWeekend = false;
bool isWorkday = !isWeekend; // true
6. Bitwise Operators
Operate on individual bits (advanced topic).
| Operator | Operation | Example | ||
|---|---|---|---|---|
| `&` | AND | `5 & 3` = `1` | ||
| ` | ` | OR | `5 | 3` = `7` |
| `^` | XOR | `5 ^ 3` = `6` | ||
| `~` | NOT | `~5` | ||
| `<<` | Left shift | `5 << 1` = `10` | ||
| `>>` | Right shift | `5 >> 1` = `2` |
7. Conditional (Ternary) Operator
Shorthand for if-else statements.
Syntax: condition ? value_if_true : value_if_false
Example:
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
// status is "Adult"
int max = (a > b) ? a : b; // Returns larger value
Operator Precedence
Operators are evaluated in a specific order when multiple operators appear in an expression.
Order (highest to lowest):
- Parentheses
() - Unary operators (
++,--,!,-) - Multiplicative (
*,/,%) - Additive (
+,-) - Relational (
<,>,<=,>=) - Equality (
==,!=) - Logical AND (
&&) - Logical OR (
||) - Assignment (
=,+=, etc.)
Example:
int result = 2 + 3 * 4; // 14 (not 20!)
int result2 = (2 + 3) * 4; // 20
bool check = 5 > 3 && 2 < 4; // true
Best Practice: Use parentheses to make precedence clear, even when not necessary.
Type Conversions in Expressions
When different types are used in expressions, C++ performs automatic conversions.
Rules:
- Smaller types are promoted to larger types
int+double→doublechar+int→int
Example:
int a = 5;
double b = 3.5;
double result = a + b; // a is converted to double, result is 8.5
Common Expressions
Mathematical Expressions
double area = 3.14159 * radius * radius; // Circle area
double celsius = (fahrenheit - 32) * 5.0 / 9.0; // Temperature conversion
Boolean Expressions
bool isValid = age >= 18 && age <= 65;
bool isWeekend = day == 6 || day == 7;
bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
String Concatenation
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName; // "John Doe"
Best Practices
- ✅ Use parentheses for clarity, even when not needed
- ✅ Avoid complex expressions - break into multiple statements
- ✅ Be careful with integer division - use
doubleif you need decimals - ✅ Use meaningful variable names in expressions
- ✅ Understand operator precedence or use parentheses
- ✅ Avoid side effects in expressions (like
++in complex expressions)
Common Mistakes
- ❌ Forgetting that integer division truncates:
5 / 2 = 2(not 2.5) - ❌ Using
=instead of==in comparisons - ❌ Confusing
&&(logical) with&(bitwise) - ❌ Not understanding operator precedence
- ❌ Modulus with floating-point numbers (only works with integers)
Next Module
In Module 4, we'll learn about Control Flow - how to make decisions with if/else statements and repeat code with loops!
Hands-on Examples
Arithmetic Operators
#include <iostream>
using namespace std;
int main() {
int a = 15, b = 4;
cout << "a = " << a << ", b = " << b << endl;
cout << "Addition: " << a + b << endl;
cout << "Subtraction: " << a - b << endl;
cout << "Multiplication: " << a * b << endl;
cout << "Division: " << a / b << endl;
cout << "Modulus: " << a % b << endl;
// Integer division note
cout << "\nNote: Integer division truncates:" << endl;
cout << "15 / 4 = " << (15 / 4) << " (not 3.75)" << endl;
// For decimal division, use double
double x = 15.0, y = 4.0;
cout << "15.0 / 4.0 = " << (x / y) << endl;
return 0;
}This example demonstrates all basic arithmetic operators. Note that integer division truncates the decimal part. To get decimal results, use floating-point types (double or float).
Practice with Programs
Reinforce your learning with hands-on practice programs