Stage 2: Control Structures in C++
An overview of conditional statements and loops required to control the program flow.
Control Flow in C++
Control structures allow a program to make decisions and repeat operations. For your exam, it is crucial to understand the differences between various loops and how to construct logical conditions correctly.
1. Conditional Statements
if and else
The fundamental way to branch code. Remember the priorities of logical operators (&&, ||, !).
int x = 10;
if (x > 0 && x <= 10) {
std::cout << "X is in range (0, 10]" << std::endl;
} else {
std::cout << "X is out of range" << std::endl;
}switch
Use this when checking a single variable (integral type or char) against multiple specific values. Don't forget the break keyword!
char grade = 'A';
switch (grade) {
case 'A': std::cout << "Excellent!"; break;
case 'B': std::cout << "Good"; break;
default: std::cout << "Other grade";
}2. Loops (Iterations)
for loop
Ideal when you know in advance how many times an operation should repeat (e.g., traversing an array).
for (int i = 0; i < 5; i++) {
std::cout << "Iteration: " << i << std::endl;
}while and do-while loops
while: Checks the condition before executing the code block (may not run at all).do-while: Checks the condition after executing the block (always runs at least once).
int i = 0;
while (i < 3) {
i++;
}
do {
// Will run once even if i >= 3
} while (i < 3);Common Exam Pitfalls
- Semicolon after
iforfor:if (x > 0);will cause the statement below to always execute because theifends at the semicolon. - Assignment vs. Comparison:
if (x = 5)will always be true (as the assignment returns 5); useif (x == 5). - Off-by-one error: Make sure your loop should end at
i < nori <= n.
You might also like
Stage 11: Pointer Arithmetic in C++
Understanding how C++ operates on memory addresses. Learn why ptr++ is more than just adding one.
Stage 10: Pointers, Address-of, and Dereference Operators
Understanding the foundations of memory addressing in C++: how pointers and low-level operators work.
Stage 6: C-Style String Handling (char[])
A guide to low-level string processing as null-terminated character arrays, following exam constraints.