Topic 13 of 83
If...Else
Overview
If statements execute blocks of code conditionally based on a boolean expression. They form the backbone of decision-making in logic.
Syntax
cpp
int score = 85;
if (score >= 90) {
cout << "Grade: A";
} else if (score >= 80) {
// Nested if
if (score == 85) {
cout << "Grade: B (Solid)";
} else {
cout << "Grade: B";
}
} else {
cout << "Grade: C or lower";
}Common Pitfalls
- Forgetting braces `{}` for multi-line if blocks (only the first line is conditional without braces).
- Using assignment `=` instead of equality `==`.
Interview Tips
- Explain the concept of 'branch prediction' in modern CPUs and how highly unpredictable 'if' statements inside large loops can slow down performance.
Real-World Example
Validating user input boundaries.
example
cpp
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter age: ";
cin >> age;
if (age < 0 || age > 120) {
cout << "Invalid age.\n";
} else if (age >= 18) {
cout << "Access granted.\n";
} else {
cout << "Access denied.\n";
}
return 0;
}