Real-Life If...Else Examples
User Authentication
A simple check for login credentials using logical operators:
Example
#include <iostream>
#include <string>
int main() {
std::string username = "admin";
std::string password = "12345";
if (username == "admin" && password == "12345") {
std::cout << "Login successful"; // no newline to match shown output
} else {
std::cout << "Invalid credentials";
}
return 0;
}
Output
Login successful
Temperature Alert System
Monitoring system that triggers messages based on thresholds:
Example
#include <iostream>
int main() {
double temperature = 85.5;
if (temperature > 100) {
std::cout << "CRITICAL: Shutdown required!";
} else if (temperature > 90) {
std::cout << "WARNING: Approaching limits";
} else if (temperature > 80) {
std::cout << "Notice: Elevated temperature";
} else {
std::cout << "Normal operating range";
}
return 0;
}
Output
Notice: Elevated temperature
E-commerce Discount Rules
Applying tiered discounts depending on purchase amount:
Example
#include <iostream>
int main() {
double purchaseAmount = 150.0;
double discount = 0.0;
if (purchaseAmount > 200) {
discount = 0.2; // 20% discount
} else if (purchaseAmount > 100) {
discount = 0.1; // 10% discount
} else if (purchaseAmount > 50) {
discount = 0.05; // 5% discount
}
double total = purchaseAmount * (1 - discount);
std::cout << "Total after discount: $" << total;
return 0;
}
Output
Total after discount: $135
Game Character Status
Determining a character's current state in a game:
Example
#include <iostream>
int main() {
bool isAlive = true;
bool hasWeapon = true;
int ammo = 3;
if (!isAlive) {
std::cout << "Game Over";
} else if (!hasWeapon) {
std::cout << "Find a weapon!";
} else if (ammo == 0) {
std::cout << "Reload needed";
} else {
std::cout << "Ready for combat";
}
return 0;
}
Output
Ready for combat
Best Practices
- Use descriptive variable names for conditions (e.g., `isAlive`, `hasWeapon`).
- Keep conditions simple and extract complex checks into functions.
- Order checks from most critical/specific to most general.
- Add comments when intent is not obvious.
- For many fixed-value conditions, consider using a `switch` statement instead of `if...else`.
- Avoid `using namespace std;` in global scope; prefer qualified names like `std::cout`.