C++ for Loop
In this page:
Introduction to For Loops
A for loop packs initialization, a condition, and an update step into one line — for (int i = 0; i < 10; i++) — making it the natural choice whenever you already know exactly how many times you need to repeat something. Compared to a while loop, keeping all three parts together makes the loop's start, stop, and progress conditions easy to see at a glance.
Example: Introduction to For Loops
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Loop Steps
The update step isn't limited to simple +1 increments — you can add any amount, multiply, or divide the counter each pass, which changes the loop from stepping linearly to stepping geometrically. This is exactly how algorithms that repeatedly halve or double a value, like binary search, structure their loop.
Example: Loop Steps
#include <iostream>
int main() {
for (int i = 0; i < 20; i += 5) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested For Loops
Placing one for loop inside another lets the inner loop run to completion once for every single iteration of the outer loop, which is exactly the pattern behind processing a 2D grid — the outer loop walks rows while the inner loop walks columns within each row. The total number of iterations is the product of both loops' counts.
Example: Nested For Loops
#include <iostream>
int main() {
for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 2; j++) {
std::cout << i << "," << j << " ";
}
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Looping Over Arrays
Using a for loop's counter as an array index, like for (int i = 0; i < size; i++) cout << arr[i];, is one of the most common patterns in C++ for visiting every element in sequence. It gives you the index itself if you need it, unlike some alternatives that only give you the value.
Example: Looping Over Arrays
#include <iostream>
int main() {
int arr[] = {10, 20, 30};
int size = 3;
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Range-based For Loop
A range-based for loop, written for (int x : arr), iterates directly over each element's value without you managing an index at all, which removes an entire category of off-by-one bugs. It's the preferred style in modern C++ whenever you don't actually need the index, only the values themselves.
Example: Range-based For Loop
#include <iostream>
int main() {
int arr[] = {10, 20, 30};
for (int x : arr) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: