break, continue and nested loops
Control a loop from the inside: stop it early with break, skip one round with continue, and put loops inside loops.
break and continue.
| Keyword | What it does |
|---|---|
break | |
continue | for, the update i++ still runs). |
break: stop when you have the answer
int[] loads = { 12, 18, 25, 40, 33 };int limit = 30;int position = -1; for (int i = 0; i < loads.Length; i++){ if (loads[i] > limit) { position = i; break; // found it: no need to check the rest }}Console.WriteLine(position >= 0 ? $"First overload at index {position}" : "All OK");First overload at index 3
break the loop would carry on to the end and position would end up as the last match, not the first.
continue: skip what you don’t need
string[] inputs = { "10", "abc", "25", "", "5" };int sum = 0; foreach (string s in inputs){ if (!int.TryParse(s, out int n)) continue; // ignore anything that isn't a number sum += n;}Console.WriteLine($"Sum of valid numbers: {sum}");Sum of valid numbers: 40
Loops inside loops
for (int row = 1; row <= 3; row++){ for (int col = 1; col <= 4; col++) { Console.Write($"{row * col,4}"); // ,4 = right-align in 4 spaces } Console.WriteLine(); // new line after each row}1 2 3 4 2 4 6 8 3 6 9 12
Patterns with nested loops
int height = 4;for (int i = 1; i <= height; i++){ for (int j = 1; j <= i; j++) Console.Write("* "); Console.WriteLine();}* * * * * * * * * *
break only leaves ONE loop
break exits only the innermost loop it is in. To stop both, use a flag variable, or put the loops in a method and return.
int[] nums = { 3, 8, 1, 6 };int target = 9;bool found = false; for (int i = 0; i < nums.Length && !found; i++){ for (int j = i + 1; j < nums.Length; j++) { if (nums[i] + nums[j] == target) { Console.WriteLine($"{nums[i]} + {nums[j]} = {target}"); found = true; break; // leaves the inner loop; the flag stops the outer one } }}3 + 6 = 9
Show a hint
i > 20 && i % 7 == 0 → break), then the skip condition (i % 3 == 0 → continue).
Show the solution
for (int i = 1; i <= 30; i++){ if (i > 20 && i % 7 == 0) break; if (i % 3 == 0) continue; Console.Write(i + " ");}1 2 4 5 7 8 10 11 13 14 16 17 19 20
Remember
breakleaves the loop now;continueskips to the next iteration.In nested loops the inner loop runs fully for every outer iteration. breakexits only the innermost loop; use a flag orreturnto leave all.In whileloops, update the counter before anycontinue.