Home C# Tutorial on the break Statement in C#

Tutorial on the break Statement in C#

The break statement in C# is used to immediately exit a loop or a switch statement.

When break is encountered, control is transferred to the code following the loop or switch block, terminating the loop regardless of the condition.

This can be helpful when you want to stop the execution of a loop early, for example, if a specific condition is met.

In this tutorial, we’ll cover:

1. Using break in a for Loop

The break statement is commonly used in a for loop to exit the loop early if a specific condition is met.

using System;

class Program {
    static void Main() {
        for (int i = 1; i <= 10; i++) {
            if (i == 5) {
                Console.WriteLine("Breaking the loop at i = 5");
                break; // Exit the loop
            }
            Console.WriteLine("i = " + i);
        }
        Console.WriteLine("Loop exited.");
    }
}

Output:

i = 1
i = 2
i = 3
i = 4
Breaking the loop at i = 5
Loop exited.

In this example:

  • When i equals 5, the break statement is executed, immediately exiting the loop.

2. Using break in a while Loop

The break statement can also be used in a while loop to stop looping if a certain condition is met.

using System;

class Program {
    static void Main() {
        int i = 1;

        while (i <= 10) {
            if (i == 7) {
                Console.WriteLine("Breaking the loop at i = 7");
                break; // Exit the loop
            }
            Console.WriteLine("i = " + i);
            i++;
        }
        Console.WriteLine("Loop exited.");
    }
}

Output:

i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
Breaking the loop at i = 7
Loop exited.

In this example:

  • The break statement exits the while loop when i equals 7.

3. Using break in a do-while Loop

In a do-while loop, the break statement can be used to exit the loop immediately, even if the condition at the end of the loop would allow another iteration.

using System;

class Program {
    static void Main() {
        int i = 1;

        do {
            if (i == 4) {
                Console.WriteLine("Breaking the loop at i = 4");
                break; // Exit the loop
            }
            Console.WriteLine("i = " + i);
            i++;
        } while (i <= 10);

        Console.WriteLine("Loop exited.");
    }
}

Output:

i = 1
i = 2
i = 3
Breaking the loop at i = 4
Loop exited.

In this example:

  • The break statement exits the do-while loop when i equals 4, preventing further iterations.

4. Using break in a foreach Loop

The break statement can also be used in a foreach loop to stop iterating over a collection early.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David", "Eve" };

        foreach (string name in names) {
            if (name == "Charlie") {
                Console.WriteLine("Breaking the loop at name = Charlie");
                break; // Exit the loop
            }
            Console.WriteLine("Name: " + name);
        }
        Console.WriteLine("Loop exited.");
    }
}

Output:

Name: Alice
Name: Bob
Breaking the loop at name = Charlie
Loop exited.

In this example:

  • The break statement exits the foreach loop when the name is “Charlie”.

5. Using break in a switch Statement

In a switch statement, break is used to exit the switch block after executing a case. Without break, execution will continue into the next case, which is known as “fall-through.”

using System;

class Program {
    static void Main() {
        int day = 3;

        switch (day) {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 2:
                Console.WriteLine("Tuesday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
            case 4:
                Console.WriteLine("Thursday");
                break;
            case 5:
                Console.WriteLine("Friday");
                break;
            default:
                Console.WriteLine("Weekend");
                break;
        }
    }
}

Output:

Wednesday

In this example:

  • The break statements ensure that only the matching case is executed, preventing fall-through to the next case.

6. Practical Examples of break in Real Scenarios

Example 1: Finding a Value in a Collection

The break statement can be useful when searching for a specific value in a collection and stopping once it’s found.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        int target = 5;
        foreach (int number in numbers) {
            if (number == target) {
                Console.WriteLine("Target found: " + number);
                break;
            }
        }
        Console.WriteLine("Search completed.");
    }
}

Output:

Target found: 5
Search completed.

In this example:

  • The break statement exits the loop once the target value is found, saving time by not checking the remaining values.

Example 2: Input Validation Loop

The break statement can be used to exit a loop when a valid input is provided.

using System;

class Program {
    static void Main() {
        while (true) {
            Console.Write("Enter a positive number: ");
            int number = int.Parse(Console.ReadLine());

            if (number > 0) {
                Console.WriteLine("Thank you! You entered: " + number);
                break;
            } else {
                Console.WriteLine("Invalid input. Please try again.");
            }
        }
    }
}

Output:

Enter a positive number: -1
Invalid input. Please try again.
Enter a positive number: 10
Thank you! You entered: 10

In this example:

  • The break statement exits the while loop once a valid positive number is entered.

Example 3: Exiting Nested Loops with break

You can use break to exit only the innermost loop in nested loops. Here’s an example where break is used to exit the inner loop.

using System;

class Program {
    static void Main() {
        for (int i = 1; i <= 3; i++) {
            Console.WriteLine("Outer loop iteration: " + i);

            for (int j = 1; j <= 3; j++) {
                if (j == 2) {
                    Console.WriteLine("  Breaking inner loop at j = 2");
                    break;
                }
                Console.WriteLine("  Inner loop iteration: " + j);
            }
        }
    }
}

Output:

Outer loop iteration: 1
  Inner loop iteration: 1
  Breaking inner loop at j = 2
Outer loop iteration: 2
  Inner loop iteration: 1
  Breaking inner loop at j = 2
Outer loop iteration: 3
  Inner loop iteration: 1
  Breaking inner loop at j = 2

In this example:

  • The break statement exits only the inner for loop when j is equal to 2, but the outer loop continues.

Summary

In this tutorial, we covered the break statement in C# and demonstrated its usage in various scenarios:

  1. for loop: Exiting the loop when a specific condition is met.
  2. while loop: Stopping the loop based on a condition.
  3. do-while loop: Exiting the loop from within the body.
  4. foreach loop: Stopping iteration over a collection.
  5. switch statement: Exiting cases to avoid fall-through behavior.
  6. Practical examples: Using break for real-world tasks like searching, input validation, and nested loops.

The break statement is a powerful control flow tool in C# that helps you manage loops and conditions efficiently, allowing you to exit loops early and improve code readability and performance.

You may also like