Menu
CoddyTech

Break

Part of the Fundamentals section of Coddy's C# journey. Lesson 44 of 69.

The break statement stops the loop instantly when it's encountered.

For example,

for (int i = 0; i < 10; i++) { 
    if (i == 6) {
    	break;
    }
    Console.WriteLine(i);
}

In the following example the loop iterates regularly until it reaches number 6. Then the program enters the if statement and executes the break statement. This exits the loop immediately. The output is:

0
1
2
3
4
5

break is not limited to for loops: it works the same way in a while or do-while loop, and it is also used to end a case inside a switch statement. Wherever it appears, it leaves that loop (or switch) immediately.

challenge icon

Challenge

Beginner

You are given a code that prints the numbers from 1 to 20 (including).

Your task is to add if and break statements so that only the numbers from 1 to 15 will be printed, the loop will exit before printing the numbers from 16 to 20.

Try it yourself

using System;

public class Program {
    public static void Main(string[] args) {
        for (int i = 1; i <= 20; i++) {
            Console.WriteLine(i);
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online C# compiler