What break does
A loop normally runs until its condition fails or until foreach runs out of elements. The break statement ends it sooner. When execution reaches break, C# leaves the nearest enclosing loop at once, without checking the loop condition again, and continues with the first statement after the loop.
It is useful whenever the rest of the work would be wasted. If you are searching an array for a value, there's no point in looking at the remaining elements after you have found it. You usually put break inside an if, so the loop stops only when something specific happens.
Breaking a foreach loop
This program prints fruits until it prints a banana, then stops:
string[] fruits = {"kivi", "orange", "banana", "apple", "pear"};
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
if (fruit == "banana") {
break;
}
}
The output is:
kivi
orange
banana
On the first two passes the comparison is false, so the loop moves on. On the third pass fruit is "banana", the line is printed, and then break ends the loop. apple and pear are never visited.
In C#, a foreach loop is written foreach (string fruit in fruits), with the keyword in. Code ported from Java often uses a colon instead, which doesn't compile. Also note that == compares the contents of two strings in C#, so fruit == "banana" does what it looks like.
Breaking a for loop with indices
The same search works with an index loop. This version also reports the position:
string[] fruits = {"kivi", "orange", "banana", "apple", "pear"};
for (int i = 0; i < fruits.Length; i++) {
Console.WriteLine("Index " + i + ": " + fruits[i]);
if (fruits[i] == "banana") {
break;
}
}
Index 0: kivi
Index 1: orange
Index 2: banana
Arrays use the property Length, with a capital L and no parentheses. After the loop ends, you can't use i, because it was declared in the loop header. If you need the position afterwards, store it in a variable declared before the loop:
int[] nums = {4, 7, 1, 9};
int found = -1;
for (int i = 0; i < nums.Length; i++) {
if (nums[i] == 1) {
found = i;
break;
}
}
Console.WriteLine(found); // 2
The starting value -1 means "not found", and it stays that way if the loop finishes without ever reaching break.
The exercise, step by step
The lesson gives you an array lessons and a string lastFinishedLesson, which is "functions". The task is to print every lesson the student finished, up to and including the last finished one.
- Loop over the lessons. Use
foreach (var lesson in lessons). The keywordvarlets the compiler work out thatlessonis astring, andforeachis enough because only the values matter, not the positions. - Print each lesson. Inside the loop, write
"Finished "followed by the lesson, joined with+. - Stop after the last finished lesson. Still inside the loop, compare
lessonwithlastFinishedLesson. When they are equal,break.
string[] lessons = {"variables", "conditionals", "arrays", "functions", "loops"};
string lastFinishedLesson = "functions";
foreach (var lesson in lessons) {
Console.WriteLine("Finished " + lesson);
if (lesson == lastFinishedLesson) {
break;
}
}
The output is:
Finished variables
Finished conditionals
Finished arrays
Finished functions
The order of the two statements matters. The check comes after the print, so the last finished lesson is printed before the loop stops. If you put the if first, functions would be missing from the output, because break would leave the loop before the print line ran.
Common mistakes and gotchas
- Break only leaves one loop. In nested loops,
breakends the innermost loop and the outer one carries on. With a double loop where the inner one breaks whenj == 1, the outer loop still runs everyi. - Break inside a switch. In a
switchstatement,breakends the switch, not the loop around it. Abreakplaced in aswitchinside a loop doesn't stop the loop. - Using break outside a loop. A
breakthat isn't inside a loop or a switch is a compile-time error. - Putting the check in the wrong place. Before or after the work in the loop body changes whether the matching element is processed. Decide whether the matching item should be included.
- Comparing with the wrong name. If
lastFinishedLessonnever matches any element, the loop simply runs to the end, and every lesson is printed.
Key takeaways
breakends the innermost loop immediately and continues after it.- It works the same way in
for,foreachandwhileloops. - Put it inside an
if, so the loop stops only when a condition is met. - When you need the position of what you found, use a
forloop and save the index before breaking.