C++ If … Else Statement

πŸ”€ C++ If … Else Statement

if...else statement ka use conditions ke basis par decision lene ke liye hota hai.
Agar condition true hoti hai to if ka block run hota hai, warna else ka.


πŸ”Ή 1. Basic if Statement

int age = 20;

if (age >= 18) {
cout << "Eligible to vote";
}


πŸ”Ή 2. if...else Statement

int age = 16;

if (age >= 18) {
cout << "Adult";
} else {
cout << "Minor";
}


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

int marks = 82;

if (marks >= 90) {
cout << "Grade A";
} else if (marks >= 75) {
cout << "Grade B";
} else if (marks >= 60) {
cout << "Grade C";
} else {
cout << "Fail";
}


πŸ”Ή 4. Multiple Conditions (Logical Operators)

int age = 25;
bool hasID = true;

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


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

int num = 5;

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


πŸ”Ή 6. if without Braces {}

if (age >= 18)
cout << "Adult";
else
cout << "Minor";

⚠️ Multiple statements ke liye braces zaroori hain.


πŸ”Ή 7. Ternary Operator (Short if...else)

int a = 10, b = 20;
int max = (a > b) ? a : b;

cout << max;


❌ Common Mistakes

if (a = 10) // ❌ assignment instead of comparison

βœ” Correct:

if (a == 10)

πŸ“Œ Summary

  • if β†’ condition true ho to

  • else β†’ condition false ho to

  • else if β†’ multiple conditions

  • Logical operators combine conditions

  • Ternary = short form of if...else

You may also like...