Topic 10 of 83
Basic Operators
Overview
Operators perform operations on variables. Arithmetic (+, -, *, /, %) handles math, Assignment (=, +=) updates values, and Relational (==, !=, <, >) compares values.
Syntax
cpp
int a = 10, b = 3;
// Arithmetic
int sum = a + b; // 13
int mod = a % b; // 1 (Remainder)
// Assignment
a += 5; // a is now 15 (a = a + 5)
// Relational
bool isGreater = (a > b); // true
bool isEqual = (a == b); // falseCommon Pitfalls
- Using a single `=` (assignment) instead of `==` (comparison) in an `if` statement condition.
- Dividing two integers (e.g., `5 / 2`) results in integer division (`2`, not `2.5`).
Interview Tips
- Understand the difference between prefix (++i) and postfix (i++). Prefix increments then returns the value; postfix returns the original value then increments. Prefix is generally slightly faster for complex iterators.
Real-World Example
Calculating if a number is even or odd using the modulo operator.
example
cpp
#include <iostream>
using namespace std;
int main() {
int num = 42;
if (num % 2 == 0) {
cout << num << " is Even.\n";
} else {
cout << num << " is Odd.\n";
}
return 0;
}