break, continue & Nested Loops
break
Exits the innermost loop (or switch) immediately.
for (int x : data) {
if (x == target) { found = true; break; }
}
continue
Skips the rest of the current iteration and goes to the next one.
for (double amount : expenses) {
if (amount <= 0) continue; // ignore invalid entries
total += amount;
}
Nested loops
A loop inside a loop: the inner loop runs completely for each outer iteration.
for (int row = 1; row <= 3; ++row)
for (int col = 1; col <= 4; ++col)
... // runs 3 × 4 = 12 times
Used for tables, grids, matrices, comparing every pair, patterns.
Breaking out of nested loops
break only exits one level. Options:
- A flag variable checked by the outer loop
- Put the loops in a function and
return✅ (cleanest) goto(legal, but generally avoided)
Complexity reminder
Two nested loops over n items = about n² operations: 1,000 items → 1,000,000 steps. Keep that in mind for large data.
Classic pattern exercises
* 1 *****
** 12 ***
*** 123 *
Approach: outer loop = rows, inner loop(s) = what to print on each row (spaces, then symbols).
Loop + validation pattern
while (true) {
read input;
if (valid) break;
print error;
}
Example
#include <iostream>
#include <vector>
bool find_pair(const std::vector<int>& v, int target, int& a, int& b) {
for (std::size_t i = 0; i < v.size(); ++i)
for (std::size_t j = i + 1; j < v.size(); ++j)
if (v[i] + v[j] == target) { a = v[i]; b = v[j]; return true; } // exits both loops
return false;
}
int main() {
std::vector<double> expenses = { 500, -20, 1200, 0, 300 };
double total = 0;
for (double e : expenses) {
if (e <= 0) continue; // skip invalid entries
total += e;
}
std::cout << "Valid total: " << total << '\n';
std::vector<int> ids = { 7, 13, 42, 99, 42 };
int position = -1;
for (int i = 0; i < static_cast<int>(ids.size()); ++i)
if (ids[i] == 42) { position = i; break; } // stop at the first match
std::cout << "First 42 at index " << position << '\n';
int a, b;
if (find_pair({ 300, 1200, 450, 750 }, 1200, a, b))
std::cout << a << " + " << b << " = 1200\n";
// multiplication table 1-4
for (int r = 1; r <= 4; ++r) {
for (int c = 1; c <= 4; ++c) std::cout << r * c << '\t';
std::cout << '\n';
}
// pyramid pattern
int rows = 4;
for (int r = 1; r <= rows; ++r) {
for (int s = 0; s < rows - r; ++s) std::cout << ' ';
for (int k = 0; k < 2 * r - 1; ++k) std::cout << '*';
std::cout << '\n';
}
return 0;
}
/* Output:
Valid total: 2000
First 42 at index 2
450 + 750 = 1200
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
*
***
*****
*******
*/