Break Statement in C#

Break Statement in C# with Examples

In this article, I am going to discuss Break Statement in C# Language with Examples. Please read our previous articles, where we discussed For loop in C# with Examples. Before understanding the Break Statement, in this article, first I will discuss what are Jump Statements and when and how to use Jump Statements in C# Language and then I will discuss Break statements with Examples.

What are Jump Statements in C# Language?

The Jump Statements in C# are used to transfer control from one point to another point in the program due to some specified condition while executing the program.

The Jump Statements in C# Language are used to modify the behavior of conditional and iterative (while, for, do-while) statements. The Jump Statements in C# allow us to exit a loop, and start the next iteration, or explicitly transfer the program control to a specified location in your program. C# supports the following four jump statements:

  1. break
  2. continue
  3. goto
  4. return (In the Function section we will discuss the return statement)
  5. throw (In the Exception Handling section we will discuss the throw statement)
Break Statement in C# Language:

In C#, the break is a keyword. By using the break statement, we can terminate either the loop body or the switch body. The most important point is that use of a break statement is optional but if you use then it should be placed either within the loop body or switch body.

When we know the maximum number of repetitions but some condition is there where we need to terminate the loop body then we need to use the break statement.

That means the Break Statement in C# provides a convenient way to immediately exit from a loop (For, While, Do While, Foreach), or Switch Case statement. The break statement ends the loop immediately when it is encountered. The break statement is almost always used with the if…else statement inside the loop body.

Break Statement Flowchart:

Break Statement Flowchart

How does the break statement work in C# language?

How does the break statement work in C# language?

Syntax: break;

Example to Understand Break Statement in C# Language:

In the below example, when the I value becomes 99, the if condition satisfies and the break statement is executed which terminates the for loop and the next statement i.e. Console.WriteLine(“Out of for-loop”); will be executed.

using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 100; i >= 10; i--)
            {
                Console.WriteLine($"I : {i}");
                if (i == 99)
                {
                    break;
                }
            }
            Console.WriteLine("Out of for-loop");

            Console.ReadKey();
        }
    }
}
Output:

Example to Understand Break Statement in C# Language

Note: The break statement in C# terminates the closest enclosing iteration statement (for, for each, while, or do loop) or switch statement. The break statement transfers control to the statement that follows the terminated statement if any.

C# Break Statement with Inner Loop:

In nested loops, the break statement terminates only the innermost loop that contains it, which is shown in the below example.

using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int outer = 0; outer < 5; outer++)
            {
                for (int inner = 0; inner < 5; inner++)
                {
                    if (inner > outer)
                    {
                        break;
                    }

                    Console.Write($"{inner} ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}
Output:

C# Break Statement Example with Inner Loop

Points to Remember while working with Break Statement in C#:
  1. The Break Statement interrupts the flow of control. We have seen in the switch statement that when a true case is found, the flow of control goes through every statement downward. We want that only statements of the true case should be executed and the remaining should be skipped. For this purpose, we use the “break Statement”.
  2. When the Break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
  3. If we are using Nested loops (i.e. one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the Next line of code after the block.
Break Statement with loop and switch statement in C#:

When we use the switch statement inside a loop, the break statement at the end of a switch section transfers controls only out of the switch statement, not out of the loop statement. The loop that contains the switch statement is unaffected. For a better understanding, please have a look at the following example.

using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] measurements = { 1, 20, 3, double.NaN };
            foreach (double measurement in measurements)
            {
                switch (measurement)
                {
                    case 1:
                        Console.WriteLine($"value is {measurement}; too low.");
                        break;

                    case 20:
                        Console.WriteLine($"value is {measurement}; too high.");
                        break;

                    case double.NaN:
                        Console.WriteLine("Invalid");
                        break;

                    default:
                        Console.WriteLine($"Value is {measurement}.");
                        break;
                }
            }
            Console.ReadKey();
        }
    }
}
Output:

Break Statement with loop and switch statement in C#

Note: In General, we should minimize the use of break statements in loops. The switch statement is an exception in this regard where it is necessary to use the “break statement” after every case. Otherwise, there may be a logical error. while writing loops, we should try to execute the loops with the condition test and should try to avoid the “break statement”.

Some tricky questions related to C# Break Statement:
Question1: What will be the output in the below program?
using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            while (a <= 10)
            {
                Console.Write($"{a} ");
                if (a > 3)
                    break;
                a++;
            }

            Console.ReadKey();
        }
    }
}

Output: 1 2 3 4

This is because whenever the value of a become 4 then the condition becomes true then the break statement will be executed. Whenever the break statement is executed automatically control will pass outside of the loop body.

Question2: What will be the output in the below program?
using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 2;
            while (a <= 20)
            {
                Console.Write($"{a} ");
                a += 2;
                if (a >= 8)
                    break;
            }
            Console.ReadKey();
        }
    }
}

Output: 2 4 6

Question3: What will be the output in the below program?
using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 15;
            while (a >= 3)
            {
                a -= 2;
                Console.Write($"{a} ");
                if (a <= 9)
                    break;
            }

            Console.ReadKey();
        }
    }
}

Output: 13 11 9

Question4: What will be the output in the below program?
using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 15;
            while (a >= 5)
            {
                Console.Write($"{a} ");
                if (a <= 10);
                break;
                a -= 2;
            }

            Console.ReadKey();
        }
    }
}

Output: 15

Note: When the semicolon (;) is available at the end of the line then it became a dummy condition that the break statement is placed directly outside the condition in the loop.

Question5: What will be the output in the below program?
using System;
namespace JumpStatementDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 8;
            while (a <= 80) ;
            {
                Console.Write($"{a} ");
                if (a >= 20) ;
                break;
                a += 2;
            }

            Console.ReadKey();
        }
    }
}

Output: Error CS0139 No enclosing loop out of which to break or continue

Note: When the semicolon is available at the end of the while then it becomes a dummy loop. When the dummy loop is created then the compiler will create a new body without any statements and the current body becomes outside so automatically break become outside and as we know we cannot use break outside of the loop body.

In the next article, I am going to discuss Continue Statement in C# Language with Examples. Here, in this article, I try to explain the Break Statement in C# Language with Examples. I hope you enjoy this Break Statement in C# with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.