Start learning free

LESSON 150 OF 347 · LOOPING OVER ARRAY INDICES

Break in C# Loops: Stopping a for or foreach Early

Lesson Read the full explanation

With the break statement, we can prematurely terminate a loop from inside that loop.

When C# reaches the break statement, it's going to immediately terminate the loop without checking any conditions.


Breaking a for loop:

In this example, we will terminate the loop when we find a "banana" in our array:

string[] fruits = {"kivi", "orange", "banana", "apple", "pear"};
for (string fruit : fruits) {
	Console.WriteLine(fruit);
	if(fruit == "banana") {
		break;
	}
}

The output of this code is:

kivi
orange
banana

As you can see, our program doesn't print apple and pear.

Here's what happens during this loop:

1. First iteration:
	a. fruit = "kivi"
	b. Console.WriteLine(fruit); => Output: kivi
	c. Is fruit == "banana"? No.
	
2. Second iteration:
	a. fruit = "orange"
	b. Console.WriteLine(fruit); => Output: orange
	c. Is fruit == "banana"? No.
	
3. Third iteration:
	a. fruit = "banana"
	b. Console.WriteLine(fruit); => Output: banana
	c. Is fruit == "banana"? Yes:
          break => Exit the loop immediately

Here's the same program but iterating through the array with indices instead:

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;
	}
}

The output of this code is:

Index 0: kivi
Index 1: orange
Index 2: banana

As you can see, our program doesn't print apple and pear.


Assignment
Let's print all the lessons our student finished!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    C# · LOOPING OVER ARRAY INDICES

    Break In For Loops in C#, explained

    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.

    1. Loop over the lessons. Use foreach (var lesson in lessons). The keyword var lets the compiler work out that lesson is a string, and foreach is enough because only the values matter, not the positions.
    2. Print each lesson. Inside the loop, write "Finished " followed by the lesson, joined with +.
    3. Stop after the last finished lesson. Still inside the loop, compare lesson with lastFinishedLesson. 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, break ends the innermost loop and the outer one carries on. With a double loop where the inner one breaks when j == 1, the outer loop still runs every i.
    • Break inside a switch. In a switch statement, break ends the switch, not the loop around it. A break placed in a switch inside a loop doesn't stop the loop.
    • Using break outside a loop. A break that 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 lastFinishedLesson never matches any element, the loop simply runs to the end, and every lesson is printed.

    Key takeaways

    • break ends the innermost loop immediately and continues after it.
    • It works the same way in for, foreach and while loops.
    • 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 for loop and save the index before breaking.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free