C# break Statement

Introduction

The break statement in C# is used to terminate the execution of a loop or a switch statement prematurely. When a break statement is encountered inside a loop or switch case, the control is transferred immediately to the statement following the loop or switch statement. This is useful for exiting a loop when a specific condition is met or for ending a switch case once the desired case is executed.

Syntax

Inside a Loop

while (condition)
{
    if (someCondition)
    {
        break;
    }
    // Code to execute in the loop
}

Inside a switch Statement

switch (expression)
{
    case value1:
        // Code for case value1
        break;
    case value2:
        // Code for case value2
        break;
    // More cases...
    default:
        // Code for default case
        break;
}

Example: Using break in a Loop

Here’s a complete example demonstrating the use of the break statement in a for loop in C#:

using System;

namespace BreakInLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Using a for loop to print numbers from 1 to 10
            for (int i = 1; i <= 10; i++)
            {
                if (i == 5)
                {
                    break; // Exit the loop when i equals 5
                }
                Console.WriteLine("Number: " + i);
            }

            // This will always be executed
            Console.WriteLine("Loop terminated early.");
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Loop terminated early.
Program finished.

Explanation

  1. Initialization: for (int i = 1; i <= 10; i++) initializes the loop counter i to 1 and specifies the loop condition and iteration.
  2. Condition Check: if (i == 5) checks if i is equal to 5.
  3. Break Statement: break; exits the loop when i equals 5.
  4. Loop Body: Console.WriteLine("Number: " + i); prints the current value of i.

Example: Using break in a switch Statement

Here’s a complete example demonstrating the use of the break statement in a switch statement in C#:

using System;

namespace BreakInSwitchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number between 1 and 3:");
            int number = Convert.ToInt32(Console.ReadLine());

            // Using a switch statement to print messages based on the number entered
            switch (number)
            {
                case 1:
                    Console.WriteLine("You entered one.");
                    break; // Exit the switch statement
                case 2:
                    Console.WriteLine("You entered two.");
                    break; // Exit the switch statement
                case 3:
                    Console.WriteLine("You entered three.");
                    break; // Exit the switch statement
                default:
                    Console.WriteLine("Invalid number.");
                    break; // Exit the switch statement
            }

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

For an input of 2:

Enter a number between 1 and 3:
2
You entered two.
Program finished.

For an input of 5:

Enter a number between 1 and 3:
5
Invalid number.
Program finished.

Explanation

  1. User Input: int number = Convert.ToInt32(Console.ReadLine()); reads the user input and converts it to an integer.
  2. Switch Statement: switch (number) evaluates the value of number.
  3. Case Statements: Each case block contains a message to be printed and a break; statement to exit the switch statement.
  4. Default Case: The default case handles any values that do not match the specified cases.

Example: Using break in a while Loop

This example demonstrates the use of the break statement in a while loop to terminate the loop when a specific condition is met:

using System;

namespace BreakInWhileLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 1;

            // Using a while loop to print numbers until counter is 5
            while (true)
            {
                if (counter == 5)
                {
                    break; // Exit the loop when counter equals 5
                }
                Console.WriteLine("Counter: " + counter);
                counter++;
            }

            // This will always be executed
            Console.WriteLine("Loop terminated early.");
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Counter: 1
Counter: 2
Counter: 3
Counter: 4
Loop terminated early.
Program finished.

Explanation

  1. Initialization: int counter = 1; initializes the counter variable to 1.
  2. Infinite Loop: while (true) creates an infinite loop.
  3. Condition Check: if (counter == 5) checks if the counter is equal to 5.
  4. Break Statement: break; exits the loop when the counter equals 5.
  5. Loop Body: Console.WriteLine("Counter: " + counter); prints the current value of the counter. counter++; increments the counter by 1.

Conclusion

The break statement is used for controlling the flow of loops and switch statements in C#. It allows you to exit these structures prematurely when a specific condition is met. By understanding and using the break statement, you can write more flexible and efficient code in your C# programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top