Select branches and traverse containers
C++ has if, else, switch, for, while and do-while. Use explicit braces and make boundary conditions testable. Range-based for loops simplify element traversal when you do not need an index.
Worked example: count passing marks
#include
#include
int main() {
std::vector marks{35, 40, 82, 19};
int passes{0};
for (int mark : marks) {
if (mark >= 40) {
++passes;
}
}
std::cout << "Passes: " << passes << '\n';
for (int& mark : marks) {
if (mark < 100) ++mark;
}
std::cout << marks[0] << '\n';
} Expected lines: Passes: 2 and 36. The first range loop copies each int into mark. The second uses a reference and changes the elements themselves. For larger read-only objects, const auto& avoids unnecessary copying.
Choose the loop for the requirement
A counted for loop exposes initialization, condition and update together. while fits input-driven repetition. do-while runs at least once, which can suit an interactive menu. break leaves the nearest loop or switch; continue starts the next loop iteration. Make sure a continue in a while loop cannot skip the only progress update.
Condition boundaries
Check invalid values before classifying them. For a score category, order thresholds from the highest to the lowest so broad conditions do not capture cases intended for narrower branches. With arrays or vectors, valid indices stop before size(); i <= size() goes one element too far.
Container mutation during traversal
Do not add elements to a vector inside a range-based loop over that same vector without understanding iterator invalidation. Reallocation can invalidate the loop's stored iterators. Collect new elements separately or use a deliberate algorithm with a clearly defined mutation rule.
Exercises
- Compute the sum of marks before the increment. Answer: 176.
- Count failures instead; expect 2.
- Change the second loop from int& to int. Why do stored marks remain unchanged? Only the local copies are incremented.
- Test thresholds at 39, 40 and 41 rather than only a comfortable value such as 82.
हिन्दी संकेत: range loop में value copy और reference का फर्क समझें। Bounds और iterator validity दोनों जरूरी हैं।