C++ | Iteration
Jumps out of the nearest enclosing loop or switch statement.
// print the numbers to a file, one per linefor (const int num : num_list) { errno = 0; fprintf(file, "%d\n", num); if (errno == ENOSPC) { fprintf(stderr, "no space left on device; output will be truncated\n"); break; }}continue
Section titled “continue”Jumps to the end of the smallest enclosing loop.
int sum = 0;for (int i = 0; i < N; i++) { int x; std::cin >> x; if (x < 0) continue; sum += x; // equivalent to: if (x >= 0) sum += x;}Introduces a do-while loop.
// Gets the next non-whitespace character from standard inputchar read_char() { char c; do { c = getchar(); } while (isspace(c)); return c;}Introduces a for loop or, in C++11 and later, a range-based for loop.
// print 10 asterisksfor (int i = 0; i < 10; i++) { putchar('*');}Introduces a while loop.
int i = 0;// print 10 asteriskswhile (i < 10) { putchar('*'); i++;}range-based for loop
Section titled “range-based for loop”std::vector<int> primes = {2, 3, 5, 7, 11, 13};
for(auto prime : primes) { std::cout << prime << std::endl;}