Module lessons (2/3)
Operators
Operators in C++ are used to perform operations on variables and values. They are mainly divided into four categories: arithmetic, assignment, relational, and logical.
Arithmetic Operators
These are used to perform common mathematical operations:
| Operator | Operation | Example |
|---|---|---|
+ | Addition | 5 + 3 (8) |
- | Subtraction | 5 - 3 (2) |
* | Multiplication | 5 * 3 (15) |
/ | Division | 10 / 3 (3 if integers, 3.333 if float/double) |
% | Modulo (remainder of integer division) | 10 % 3 (1) |
Assignment Operators
Used to assign values to variables. C++ also supports compound assignment operators:
int x = 10;
x += 5; // Equivalent to x = x + 5 (15)
x *= 2; // Equivalent to x = x * 2 (30)
Relational Operators (Comparison)
These return a boolean value (true or false):
==Equal to!=Not equal to>Greater than<Less than>=Greater than or equal to<=Less than or equal to
bool result = (10 > 5); // true
Logical Operators
Used to combine multiple boolean expressions:
&&Logical AND: true if both expressions are true.||Logical OR: true if at least one expression is true.!Logical NOT: reverses the truth value.
bool isAdult = true;
bool hasTicket = false;
bool canEnter = isAdult && hasTicket; // false
Try it yourself
Calculate the remainder of dividing 17 by 5 using the modulo % operator. Save the result in an integer variable named remainder and print it with std::cout.
Show hint
L'operatore modulo in C++ è `%`.
Solution available after 3 attempts
Given age = 20 and hasLicense = true, verify if the person can drive (canDrive). Both conditions must be true. Use the && operator, store the result in a boolean variable named canDrive, and print it.
Show hint
Usa l'operatore logico AND `&&` per unire le due condizioni.
Solution available after 3 attempts