Notifications
Clear all
Topic starter 01/08/2025 11:20 pm
In C++, if-else statements are the backbone of decision-making logic—they let your program choose between different paths based on conditions 🧠🔧
🧪 Basic if Statement
int x = 10;
if (x > 5) {
std::cout << "x is greater than 5";
}
- If the condition inside
()is true, the code inside{}runs. - If false, it’s skipped.
🔄 Adding else and else if
int x = 3;
if (x > 5) {
std::cout << "x is greater than 5";
} else if (x == 5) {
std::cout << "x is equal to 5";
} else {
std::cout << "x is less than 5";
}
else iflets you check another condition.elseruns if none of the previous conditions are true.
🧠 Real-Life Example
int score = 85;
if (score >= 90) {
std::cout << "Grade: A";
} else if (score >= 75) {
std::cout << "Grade: B";
} else if (score >= 65) {
std::cout << "Grade: C";
} else {
std::cout << "Grade: D";
}
This mimics how you’d assign grades based on score ranges.
❗ Syntax Tips
- Always use lowercase
if,else, andelse if. - Curly braces
{}are optional for single-line blocks, but recommended for clarity. - Conditions must evaluate to a Boolean (
trueorfalse).