Previous chapter: Chapter 3: Operators and Expressions in C++
In the last chapter, we mastered operators to create logical expressions. This chapter uses those expressions to implement control flow, allowing your C++ programs to execute different code blocks based on conditions or to repeat a set of actions multiple times.
1. Conditional Statements: Making Decisions
Conditional statements allow your program to decide which path of code to execute.
The if Statement
The most basic decision-making structure. The code block inside the if statement executes only if the boolean expression is true.
#include <iostream>
int main() {
int temperature = 25;
if (temperature > 30) {
std::cout << "It's a hot day, stay hydrated!" << std::endl;
}
// Output is skipped if temperature is 25
return 0;
}
The if-else Statement
Provides an alternative block of code to run when the if condition is false.
int score = 75;
if (score >= 90) {
std::cout << "Grade: A";
} else {
std::cout << "Grade is B or lower";
}
The if-else if-else Chain
Used when you need to check multiple exclusive conditions sequentially.
int score = 85;
if (score >= 90) {
std::cout << "Grade: A";
} else if (score >= 80) {
std::cout << "Grade: B"; // This executes
} else {
std::cout << "Grade: C or lower";
}
2. The switch Statement
The switch statement is an alternative to a long if-else if chain when comparing a single variable against multiple discrete integer or character values.
int choice = 2;
switch (choice) {
case 1:
std::cout << "You chose option 1.";
break; // Exits the switch block
case 2:
case 3: // Grouping cases
std::cout << "You chose option 2 or 3.";
break;
default:
std::cout << "Invalid choice.";
}
// The 'break' keyword is crucial; without it, execution "falls through" to the next case.
3. Loop Constructs: Repetition in C++
Loops execute a block of code repeatedly until a certain condition is met.
The while Loop
Repeats a block of code as long as its condition remains true.
int counter = 1;
while (counter <= 5) {
std::cout << "Count: " << counter << std::endl;
counter++; // Crucial to update the condition to prevent an infinite loop
}
The for Loop
Ideal for definite iteration where you know the number of repetitions. It neatly combines initialization, condition checking, and iteration into a single line.
// Initialization; Condition; Iteration
for (int i = 0; i < 5; i++) {
std::cout << "Loop iteration: " << i << std::endl;
}
The do-while Loop
Similar to the while loop, but the code block is guaranteed to execute at least once before the condition is checked.
int input;
do {
std::cout << "Enter a positive number: ";
std::cin >> input;
} while (input <= 0); // Condition checked after first execution
4. Loop Control Keywords
The break and continue keywords give you fine-grained control over loop execution.