BeginnerLesson 4 of 18
Loops: for, range-for and while – C++
Repeating code – over numbers and containers, with break and continue.
The classic for loop has three parts: start, condition, step. For containers, the range-based for loop (range-for) is the best choice.
#include <iostream>
#include <string>
#include <vector>
int main() {
for (int i = 0; i < 3; ++i)
std::cout << "Round " << i << '\n';
std::vector<std::string> fruechte{"Apple", "Pear", "Cherry"};
for (const std::string& f : fruechte) // const& : no copy, no modification
std::cout << f << '\n';
for (auto& f : fruechte) f += "!"; // & : modify elements
for (const auto& f : fruechte) std::cout << f << ' ';
std::cout << '\n';
}while runs as long as the condition is true; do { } while (...) checks only at the end. break ends the loop, continue jumps to the next iteration.
int n = 0;
while (true) {
++n;
if (n % 2 == 0) continue;
if (n > 7) break;
std::cout << n << ' '; // 1 3 5 7
}
std::cout << '\n';
int k = 0;
do { std::cout << k++; } while (k < 3); // 012 (at least one iteration)TipWrite
for (const auto& x : container) as your default. Copies (auto x) only for cheap types such as int. For index and value at the same time: a normal for loop with std::size_t i.Warning
for (int i = 0; i < v.size(); ++i) produces a warning (comparing int with unsigned). Use std::size_t i or range-for right away. Counting backwards with std::size_t (i >= 0) is an infinite loop, because unsigned is never negative.