Chapter 6: Control Flow
Control Flow in C++: Making Your Program Think and Decide!
Hello my superstar student! π Welcome to one of the most important chapters in C++ β Control Flow! Up until now, our programs ran straight from top to bottom, line by line. Today weβre going to teach the computer how to make decisions, repeat things, and choose different paths β just like we do in real life!
Weβll cover everything in great detail:
- if, else if, else β decision making
- switch statement (including the cool C++17+ version with initializer)
- Loops: for, while, do-while, and the modern range-based for
- break, continue, and goto (and why we rarely use goto)
Weβll go step by step with tons of examples, real-life analogies, common mistakes, and best practices that professional developers actually use.
Letβs start making decisions!
1. The if, else if, else Statements β Decision Making
Real-life analogy: βIf itβs raining, take an umbrella. Else if itβs sunny, wear sunglasses. Else, just go out normally.β
Syntax:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if (condition) { // code runs only if condition is true } else if (another_condition) { // runs if the first was false, but this one is true } else { // runs if none of the above were true } |
Important:
- The condition must evaluate to bool (true or false)
- You can have as many else if as you want
- else is optional
Classic example β Grade calculator:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> int main() { int marks; std::cout << "Enter your marks (0-100): "; std::cin >> marks; if (marks >= 90) { std::cout << "Grade: A+ - Excellent!\n"; } else if (marks >= 80) { std::cout << "Grade: A - Very Good!\n"; } else if (marks >= 70) { std::cout << "Grade: B - Good!\n"; } else if (marks >= 60) { std::cout << "Grade: C - Average\n"; } else { std::cout << "Grade: F - Better luck next time!\n"; } return 0; } |
Common mistake β forgetting braces {}:
|
0 1 2 3 4 5 6 7 8 |
if (age >= 18) std::cout << "You can vote!\n"; std::cout << "You can also drive!\n"; // β This runs ALWAYS! |
Fix: Always use braces β even for one line (it prevents bugs when you add more lines later).
2. The switch Statement β Multiple Choices
Best used when you are checking one variable against many constant values.
Syntax (classic):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
switch (expression) { case value1: // code break; case value2: // code break; default: // code if no case matches } |
Very important:
- break; is required β otherwise it falls through to the next case (sometimes useful, usually a bug!)
- default: is optional
Example β Day of the week:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include <iostream> int main() { int day; std::cout << "Enter day number (1-7): "; std::cin >> day; switch (day) { case 1: std::cout << "Monday\n"; break; case 2: std::cout << "Tuesday\n"; break; case 3: std::cout << "Wednesday\n"; break; case 4: std::cout << "Thursday\n"; break; case 5: std::cout << "Friday\n"; break; case 6: std::cout << "Saturday\n"; break; case 7: std::cout << "Sunday\n"; break; default: std::cout << "Invalid day!\n"; } return 0; } |
Modern C++17+ Feature: Switch with Initializer
You can declare and initialize a variable inside the switch β very clean!
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <string> int main() { std::string input; std::cout << "Enter traffic light color (red/yellow/green): "; std::cin >> input; switch (std::string color = input; color) { // β C++17 magic! case "red": std::cout << "Stop!\n"; break; case "yellow": std::cout << "Get ready...\n"; break; case "green": std::cout << "Go!\n"; break; default: std::cout << "Invalid color!\n"; } return 0; } |
3. Loops β Repeating Code
Loops let us repeat code β very powerful!
A. for Loop β Best when you know how many times to repeat
|
0 1 2 3 4 5 6 7 8 |
for (initialization; condition; update) { // code } |
Example β Print numbers 1 to 10:
|
0 1 2 3 4 5 6 7 8 9 |
for (int i = 1; i <= 10; ++i) { std::cout << i << " "; } // Output: 1 2 3 4 5 6 7 8 9 10 |
Modern C++ style (very common):
|
0 1 2 3 4 5 6 7 8 |
for (int i = 0; i < 5; ++i) { std::cout << "Hello " << i << "\n"; } |
B. while Loop β Repeat while condition is true
|
0 1 2 3 4 5 6 7 8 |
while (condition) { // code } |
Example β Keep asking until correct password:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <string> int main() { std::string password; std::string correct = "secret123"; while (true) { std::cout << "Enter password: "; std::cin >> password; if (password == correct) { std::cout << "Access granted!\n"; break; } std::cout << "Wrong! Try again.\n"; } return 0; } |
C. do-while Loop β Run at least once
|
0 1 2 3 4 5 6 7 8 |
do { // code } while (condition); |
Example β Menu that keeps showing until user exits:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> int main() { char choice; do { std::cout << "\n=== Menu ===\n"; std::cout << "1. Play\n2. Settings\n3. Exit\n"; std::cout << "Choice: "; std::cin >> choice; if (choice == '1') std::cout << "Starting game...\n"; else if (choice == '2') std::cout << "Opening settings...\n"; } while (choice != '3'); std::cout << "Goodbye!\n"; return 0; } |
D. Range-based for Loop β Modern & Beautiful (C++11+)
Best for looping over arrays, vectors, strings, etc.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <vector> #include <string> int main() { std::vector<int> scores = {85, 92, 78, 95, 88}; for (int score : scores) { std::cout << score << " "; } std::cout << "\n"; std::string name = "Webliance"; for (char c : name) { std::cout << c << " "; } // Output: W e b l i a n c e } |
Even better (reference to avoid copying):
|
0 1 2 3 4 5 6 7 8 |
for (const auto& score : scores) { std::cout << score << " "; } |
4. break, continue, and goto
break β Jump out of the loop/switch immediately
|
0 1 2 3 4 5 6 7 8 9 |
for (int i = 1; i <= 10; ++i) { if (i == 5) break; std::cout << i << " "; // prints 1 2 3 4 } |
continue β Skip the rest of this iteration, go to next
|
0 1 2 3 4 5 6 7 8 9 |
for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) continue; // skip even numbers std::cout << i << " "; // prints 1 3 5 7 9 } |
goto β Jump to a label (almost never use!)
|
0 1 2 3 4 5 6 7 8 |
start: std::cout << "Hello\n"; goto start; // infinite loop β bad! |
Teacherβs advice: Never use goto in modern C++. It makes code hard to read and debug. Use break, continue, functions, or exceptions instead.
5. Full Mini Project β Number Guessing Game
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <cstdlib> // for rand() #include <ctime> // for time() int main() { std::srand(std::time(nullptr)); // seed random number int secret = std::rand() % 100 + 1; // 1 to 100 int guess; int attempts = 0; std::cout << "=== Number Guessing Game ===\n"; std::cout << "I'm thinking of a number between 1 and 100...\n"; do { std::cout << "Your guess: "; std::cin >> guess; ++attempts; if (guess == secret) { std::cout << "Congratulations! You got it in " << attempts << " attempts!\n"; break; } else if (guess < secret) { std::cout << "Too low! Try again.\n"; } else { std::cout << "Too high! Try again.\n"; } } while (true); return 0; } |
Your Mini Homework (Try These!)
- Write a program that asks for a number and prints whether it is:
- Positive, Negative, or Zero
- Even or Odd
- Print the multiplication table of 5 (5 Γ 1 = 5, up to 5 Γ 10 = 50) using a for loop.
- Make a program that keeps asking for numbers until the user enters 0, then prints the sum of all entered numbers.
- Use a range-based for loop to print each character of your name on a new line.
Youβre doing incredibly well! Control flow is where your programs start becoming smart and interactive.
Next lesson: Functions β how to organize code into reusable blocks!
Any questions? Confused about do-while vs while? Want more examples with switch or range-based for? Just ask β your friendly C++ teacher is right here for you! π
