C++ Nested If-Else Statements
Nested if-else statements in C++ allow you to check multiple conditions by placing one if-else statement inside another. This helps in handling complex decision-making scenarios.
1. Nested If-Else Example
A nested if-else allows executing different blocks based on hierarchical conditions.
C++
Example: Nested if-else statement
#include <iostream>
using namespace std;
int main() {
int num = 75;
if (num >= 0) {
if (num == 0) {
cout << "Number is zero" << endl;
} else {
cout << "Number is positive" << endl;
}
} else {
cout << "Number is negative" << endl;
}
return 0;
}
2. Common Mistakes
Be careful with indentation and braces. Missing braces can cause inner blocks to behave unexpectedly.
C++
Incorrect nested if example
#include <iostream>
using namespace std;
int main() {
int num = 5;
if (num > 0)
if (num < 10)
cout << "Single-digit positive" << endl;
else
cout << "This else may not behave as expected" << endl;
return 0;
}
Conclusion
Nested if-else statements help in checking multiple hierarchical conditions. Proper use of braces and indentation ensures clarity and prevents logic errors.
Codecrown