Core Module
12 min forge
C++ If-Else & Conditionals
Mastering logical flow with if, else if, else, and nested conditions.
C++ If-Else & Conditionals
π What is it
Conditionals allow you to execute different blocks of code based on whether a condition is true or false.
β‘ When to use
Use these for decision-making in your algorithms (e.g., checking if a number is even, or if a user is authorized).
π§ Time complexity
- Check: $O(1)$
π» Code example
cpp Standardint age = 18; if (age >= 18) { std::cout << "Eligible to vote!" << std::endl; } else { std::cout << "Not eligible." << std::endl; }
β Common mistakes
- Using
=instead of==in the condition. - Forgetting
{}for multi-line blocks (though single lines don't strictly require them, it's best practice). - Redundant conditions:
if (x == true)is same asif (x).