➕ C++ Operators – Perform Calculations and Comparisons
Operators are like magic tools in C++ — they help you perform actions like adding, comparing, or even checking conditions. 🧮⚔️
🔧 Types of Operators in C++
- Arithmetic Operators – Do math (e.g.,
+,-,*,/,%) - Comparison Operators – Compare values (e.g.,
==,!=,>,<) - Logical Operators – Combine conditions (e.g.,
&&,||,!) - Assignment Operators – Assign values (e.g.,
=,+=,-=)
🧪 Example: Arithmetic Operators
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 3;
cout << "a + b = " << a + b << endl;
cout << "a - b = " << a - b << endl;
cout << "a * b = " << a * b << endl;
cout << "a / b = " << a / b << endl;
cout << "a % b = " << a % b << endl;
return 0;
}
🧠 Comparison Operators
==– Equal to!=– Not equal to>– Greater than<– Less than>=– Greater than or equal to<=– Less than or equal to
🔍 Example: Comparison
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 10;
cout << "x == y: " << (x == y) << endl;
cout << "x != y: " << (x != y) << endl;
cout << "x < y: " << (x < y) << endl;
return 0;
}
🧠 Logical Operators
&&– Logical AND||– Logical OR!– Logical NOT
🎯 Example: Logical
#include <iostream>
using namespace std;
int main() {
int age = 20;
if (age > 18 && age < 30) {
cout << "You're a young adult!" << endl;
}
return 0;
}
📝 Assignment Operators
=– Assigns a value+=– Adds and assigns-=– Subtracts and assigns*=– Multiplies and assigns/=– Divides and assigns
💡 Example: Assignment
#include <iostream>
using namespace std;
int main() {
int x = 5;
x += 3; // same as x = x + 3
cout << "x = " << x << endl;
return 0;
}