c-sharp
  1. c-sharp-break

C# Break Statement

Syntax

The break statement in C# has the following syntax:

break;

Example

using System;

class BreakExample
{
    static void Main()
    {
        for (int i = 1; i <= 10; i++)
        {
            if (i == 5)
            {
                break;
            }
            Console.WriteLine(i);
        }
        Console.WriteLine("End of loop");
    }
}

Output

1
2
3
4
End of loop

Explanation

The break statement in C# is used to exit a loop immediately. When the break statement is encountered inside a loop, the loop is terminated and program control jumps to the next statement after the loop.

In the above example, a for loop is used to iterate from 1 to 10. When the value of the loop variable i becomes 5, the break statement is executed and the loop is terminated. As a result, only the values from 1 to 4 are printed to the console.

Use

The break statement in C# is mostly used inside loops, such as for, while, and do-while loops, to terminate the loop prematurely depending on a certain condition.

Important Points

  • The break statement can be used only inside loops.
  • When the break statement is executed, the control jumps to the next statement after the loop.
  • The break statement can be used with labeled loops to break out of nested loops.

Summary

The break statement in C# is used to break out of a loop prematurely. It is often used when a certain condition has been met and you want to stop the execution of the loop. The break statement can be used in for, while, and do-while loops, and can also be used with labeled loops to break out of nested loops.

Published on: