Lesson 4 • Beginner
Control Flow
Make your programs intelligent — use if statements, switch cases, and the ternary operator to control which code runs and when.
What You'll Learn
- ✓ If, else if, and else statements
- ✓ Nested conditions and complex logic
- ✓ Switch statements for exact matching
- ✓ The ternary operator for concise conditions
If Statements — Making Decisions
If statements let your program choose different paths based on conditions. Think of them like a fork in the road — the program checks a condition, and goes left or right depending on whether it's true or false.
// Basic structure
if (condition) {
// runs if condition is true
} else if (another_condition) {
// runs if first was false, this is true
} else {
// runs if all conditions were false
}The condition inside the parentheses must evaluate to true or false. Any non-zero number is considered true in C++.
If-Else Statements
Build a grading system with if-else chains
#include <iostream>
using namespace std;
int main() {
int temperature = 28;
// Simple if statement
if (temperature > 30) {
cout << "It's hot outside! Stay hydrated." << endl;
}
// If-else statement
if (temperature > 25) {
cout << "It's warm — perfect for a walk!" << endl;
} else {
cout << "It's cool — grab a jacket." << endl;
}
// If - else if - else chain
int score = 82;
cout << "\nScore: " << score << endl;
...Nested Conditions
Create a club entry and payment system with nested logic
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 22;
bool hasID = true;
bool isMember = false;
double balance = 45.50;
// Nested if statements
cout << "=== Club Entry System ===" << endl;
if (age >= 18) {
if (hasID) {
cout << "Welcome to the club!" << endl;
if (isMember) {
cout << "Member discount: 50% off drinks!" << endl;
} else {
cout << "
...Switch Statements — Multiple Exact Matches
When you need to check a variable against many specific values, a switch statement is cleaner than a long if-else chain. It works with int, char, and enum types.
switch (variable) {
case value1:
// code for value1
break; // IMPORTANT! Prevents fall-through
case value2:
case value3: // Multiple cases can share code
// code for value2 or value3
break;
default: // Optional — handles unmatched values
// fallback code
}⚠️ Always use break after each case. Without it, execution "falls through" to the next case — which is usually a bug.
Switch Statements
Match days of the week and grade letters with switch
#include <iostream>
#include <string>
using namespace std;
int main() {
// Switch statement — great for exact value matching
int dayNumber = 3;
cout << "=== Day of the Week ===" << endl;
switch (dayNumber) {
case 1:
cout << "Monday — Start of the week!" << endl;
break;
case 2:
cout << "Tuesday — Keep going!" << endl;
break;
case 3:
cout << "Wednesday — Halfway there!" << endl;
br
...Ternary Operator
Write concise one-line conditions with the ternary operator
#include <iostream>
#include <string>
using namespace std;
int main() {
// Ternary operator: condition ? ifTrue : ifFalse
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
cout << "Age " << age << ": " << status << endl;
// Nested ternary (use sparingly!)
int score = 85;
string grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "F";
cout << "Score " << score << ": Grade " << grade << e
...Common Mistakes
⚠️ Missing braces: Without {}, only the first line after if is conditional. Always use braces.
⚠️ Forgetting break in switch: Without break, the code falls through to the next case, executing unintended code.
⚠️ Using = instead of ==: if (x = 5) assigns 5 to x and always evaluates to true. Use == for comparison.
⚠️ Unreachable code: Putting conditions in the wrong order can make some branches unreachable. Check your logic!
Pro Tips
💡 Early return pattern: Handle edge cases first with simple conditions, then process the normal case without deep nesting.
💡 Use switch for menus: Switch is perfect for processing user menu choices (1, 2, 3...) in console apps.
💡 Avoid deeply nested if: If you have 4+ levels of nesting, refactor into separate functions for readability.
📋 Quick Reference
| Concept | Syntax |
|---|---|
| If statement | if (cond) { ... } |
| If-else | if (cond) { ... } else { ... } |
| Else if chain | if (...) { } else if (...) { } else { } |
| Switch | switch (x) { case 1: ...; break; } |
| Ternary | result = (cond) ? a : b; |
Lesson Complete!
You can now write programs that make decisions! Next up: Loops — learn to repeat code efficiently with for, while, and do-while loops.
Sign up for free to track which lessons you've completed and get learning reminders.