The for loop is the most widely utilized iteration construct when the number of repetitions is known before entering the loop. Modern C++ supports both the classic counter-based loop and the elegant, zero-overhead Range-Based For Loop.
#include <iostream>
int main() {
// for (initialization; test condition; update)
for (int i = 1; i <= 5; ++i) {
std::cout << "Step count: " << i << "\n";
}
return 0;
}
Range-based loops eliminate index out-of-bounds errors and make code exceptionally readable across arrays, vectors, and lists:
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> frameworks = {"Qt", "Unreal Engine", "Boost", "CUDA"};
// Const reference: Maximum speed, Zero copying!
for (const auto& fw : frameworks) {
std::cout << "Framework: " << fw << "\n";
}
// In-place modification using non-const reference:
std::vector<int> scores = {10, 20, 30};
for (auto& s : scores) {
s *= 2; // Doubles each score directly
}
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Traversing 1D and 2D arrays with nested for loops.
Using range-based for loops with STL containers.
Early exit and step skips inside loops.