C++ Nested if Statement

πŸ” C++ Nested if Statement

Nested if ka matlab hota hai ek if ke andar doosra if.
Iska use tab hota hai jab ek condition true hone ke baad hi doosri condition check karni ho.


πŸ”Ή 1. Syntax

if (condition1) {
if (condition2) {
// code
}
}

πŸ”Ή 2. Basic Nested if Example

int age = 20;
bool hasID = true;

if (age >= 18) {
if (hasID) {
cout << "Entry Allowed";
}
}


πŸ”Ή 3. Nested if...else

int num = 5;

if (num > 0) {
if (num % 2 == 0) {
cout << "Positive Even";
} else {
cout << "Positive Odd";
}
} else {
cout << "Zero or Negative";
}


πŸ”Ή 4. Login System Example (Real-life)

string username = "admin";
string password = "1234";

if (username == "admin") {
if (password == "1234") {
cout << "Login Successful";
} else {
cout << "Wrong Password";
}
} else {
cout << "Invalid Username";
}


πŸ”Ή 5. Nested vs Logical Operators (Better Way)

❌ Nested:

if (age >= 18) {
if (hasID) {
cout << "Allowed";
}
}

βœ” Better:

if (age >= 18 && hasID) {
cout << "Allowed";
}

πŸ”Ή 6. Deep Nesting ❌ (Avoid)

if (a) {
if (b) {
if (c) {
// confusing
}
}
}

βœ” Better:

if (a && b && c) {
// clear
}

❌ Common Mistake

if (a > 0)
if (b > 0)
cout << "Both positive";
else
cout << "Negative";

⚠️ Dangling else problem

βœ” Correct:

if (a > 0) {
if (b > 0) {
cout << "Both positive";
}
} else {
cout << "Negative";
}

πŸ“Œ Summary

  • Nested if = if inside if

  • Used when second condition depends on first

  • Logical operators often simplify nested code

  • Avoid deep nesting for readability

You may also like...