🤔 C++ if/else Statement – Making Decisions in Code
The if/else statement in C++ helps your program make decisions. It checks conditions and runs code based on whether the result is true
or false
. Think of it as your program saying, “If this happens, I’ll do that!” 🎯
🧠 Syntax of if / else
if (condition) { // Code if condition is true } else if (another_condition) { // Code if another condition is true } else { // Code if none of the above conditions are true }
🔧 Example: Simple if / else
#include <iostream> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; if (age >= 18) { cout << "You're an adult!" << endl; } else { cout << "You're a minor." << endl; } return 0; }
🧪 Example: if…else if…else
#include <iostream> using namespace std; int main() { int score; cout << "Enter your score: "; cin >> score; if (score >= 90) { cout << "Grade A!" << endl; } else if (score >= 75) { cout << "Grade B!" << endl; } else if (score >= 60) { cout << "Grade C!" << endl; } else { cout << "Better luck next time!" << endl; } return 0; }
💡 When to Use if / else?
- When your program needs to decide between multiple outcomes.
- When different actions must occur based on input or conditions.
- When logic requires branching into different paths.
Now your program can finally think for itself! 🧠💻