Topic 18 of 83
For Loop
Overview
For loops are used when the number of iterations is known. Range-based for loops (C++11) provide a safer, cleaner syntax for iterating over arrays and STL containers.
Syntax
cpp
// Standard for loop (Initialization; Condition; Update)
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
// Range-based for loop (C++11)
int arr[] = {10, 20, 30};
for (int val : arr) {
cout << val << " "; // Read-only iteration
}
// Range-based by reference (allows modification)
for (int& val : arr) {
val *= 2;
}Common Pitfalls
- Off-by-one errors in standard for loops (e.g., using `<=` instead of `<` when accessing array indices).
Interview Tips
- Always use range-based for loops over standard for loops when iterating over an entire container. It prevents 'off-by-one' bounds errors.
- Understand why `for (const auto& item : container)` is the most efficient and safe way to iterate over complex objects.
Real-World Example
Using range-based for loop with `auto` keyword.
example
cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> names = {"Alice", "Bob", "Charlie"};
for (const auto& name : names) {
cout << "Hello, " << name << "!\n";
}
return 0;
}