C++ Loops
C++ loops run a block of code repeatedly. Besides while, do while and the classic for loop, modern C++ offers the range-based for loop to go through every element of a container.
while and do while
#include <iostream>
int main() {
int n = 3;
while (n > 0) {
std::cout << n << "... ";
--n;
}
std::cout << "Liftoff!\n";
int tries = 0;
do {
++tries;
} while (tries < 3);
std::cout << "Tried " << tries << " times\n";
}3... 2... 1... Liftoff! Tried 3 times
The Classic for Loop
#include <iostream>
int main() {
for (int i = 0; i < 10; i += 3) {
std::cout << i << ' ';
}
std::cout << '\n';
}0 3 6 9
Range-Based for Loop in C++
for (element : container) visits each element. Use const auto& to avoid copying, or auto& to modify elements.
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums{1, 2, 3, 4};
for (auto& n : nums) n *= 10;
for (const auto& n : nums) std::cout << n << ' ';
std::cout << '\n';
}10 20 30 40
break and continue
#include <iostream>
int main() {
for (int i = 1; i <= 10; ++i) {
if (i % 3 == 0) continue;
if (i > 8) break;
std::cout << i << ' ';
}
std::cout << '\n';
}1 2 4 5 7 8
Frequently asked questions
What is a range-based for loop in C++?
Introduced in C++11, it loops over every element of a container or array without managing an index, for example for (int x : vec).
Should I use i++ or ++i in loops?
For int they are equally fast. For iterators, ++i can avoid an unnecessary copy, so many C++ programmers use ++i by habit.
How do I loop with an index and a value in C++?
Use a classic for loop with an index, or in C++23 std::views::enumerate. In C++20 a simple counter variable alongside a range-based loop also works.