Control flow is how you give your program "brains." Up until now, your code has run in a straight line from top to bottom. With conditionals, you can tell the program to skip certain parts or run different code based on specific conditions.
1. The if Statement
The most basic form of control. If the condition inside the parentheses is true, the code inside the curly braces {} runs.
2. The else Statement
This acts as a "fallback." If the if condition is false, the else block runs automatically.
3. The else if Statement
Used when you have multiple specific conditions to check in order. The program stops at the first true condition it finds.
4. The switch Statement
Think of this as a "cleaner" way to write many else if statements when you are comparing a single variable against several constant values (like a menu).
Code Example: Grade & Access Level System
This program checks a student's score to assign a grade and uses a switch for a menu.
#include <iostream>
using namespace std;
int main() {
int score;
cout << "Enter your exam score (0-100): ";
cin >> score;
// 1. Using if-else if-else logic
if (score >= 90) {
cout << "Result: Grade A" << endl;
}
else if (score >= 75) {
cout << "Result: Grade B" << endl;
}
else if (score >= 50) {
cout << "Result: Grade C" << endl;
}
else {
cout << "Result: Fail" << endl;
}
// 2. Using switch for a simple menu
int option;
cout << "\nChoose an action: \n1. Restart\n2. Shutdown\n3. Exit\n";
cin >> option;
switch (option) {
case 1:
cout << "Restarting..." << endl;
break; // Essential to stop it from falling into the next case
case 2:
cout << "Shutting down..." << endl;
break;
case 3:
cout << "Exiting. Goodbye!" << endl;
break;
default:
cout << "Invalid selection." << endl;
}
return 0;
}Critical Tip: The break keyword
In a switch statement, if you forget the break;, the program will continue executing the code in the next case even if the condition doesn't match! This is called fall-through.