In C#, the break keyword is employed to conclude the loop, disrupting the ongoing flow of the program based on a condition specified by the user. When dealing with a nested loop, the break statement will halt the inner loop at the point where the break statement is implemented.
In simpler terms, the break statement functions as a type of jump statement in C#, particularly used to prematurely end loops and switch statements.
Syntax:
It has the following syntax.
jump-statement;
break;
// block of the code
Where,
- Jump statement: It represents a code block that directs the flow of a program (such as for, while, do while loops). It enables the manipulation of program execution by allowing for stopping, continuing, or returning to previous points during runtime.
- break: This keyword is employed to abruptly exit or terminate the execution of a loop within a program.
Flow Diagram of Break Statement
The styling for the break diagram is defined as follows:
- A linear gradient background with specific colors and border-radius is applied.
- Padding of 25px and margin of 20px from the top and bottom is set.
- The title of the diagram is centered, styled in red, with a font size of 1.2rem and font weight of 600.
- The flow elements are displayed in a column layout with centered alignment and a gap of 8px between them.
- Various types of flow nodes are defined with different background colors and text styles.
- Arrows indicating the flow direction are styled in a specific color and font size.
- Additional styling for flow splits, labels, and specific flow directions is provided.
- First, we have to initialize the value.
- Next, we go to the loop or switch statements.
- After that, we check the given break condition of the program. If the break condition of the program becomes true, it exits/terminates the program. If the break condition of the program becomes false, it executes the program smoothly as expected.
- End of the program.
- If the break condition of the program becomes true, it exits/terminates the program.
- If the break condition of the program becomes false, it executes the program smoothly as expected.
C# Break Statement Example
Basic Example of C# Break Statement
Let's consider a basic example to demonstrate the use of the break statement with a for loop in C#.
Example
using System;
class Program
{
static void Main()
{
for (int x = 1; x <= 10; x++)
{
if (x == 5)
{
break; // Exit the loop when i = 5
}
Console.WriteLine(x); // print the program
}
Console.WriteLine("Loop exited using a break statement.");
}
}
Output:
1
2
3
4
Loop exited using a break statement.
Explanation:
In this instance, we display the numerical value through a for loop. An integer variable x is defined and initialized with a value of 1. Subsequently, the program evaluates the specified conditions. When the condition x is less than or equal to 10, the program proceeds. It terminates once the condition x is equal to 5.
Working of Break Statement in C#
Here, we will discuss the usage of break statements by using the different types of loops in C#.
- Simple Loop
- Nested Loop
- Infinite Loop
- Switch-Case statement
Break Statement using Simple Loops
In C# development, the break statement can be employed within various basic loops. A few examples include:
Break Statement Using For Loop
In C#, the break statement is crucial within a for loop when you need to prematurely exit the loop based on a certain condition.
Syntax:
It has the following syntax.
for(initialization; condition; updation)
{
if(condition)
{
// block of code
break; // exit the code
}
// The remaining character is printed if not match the condition
}
C# Break Statement Example using For Loop
Let's consider a scenario to demonstrate the usage of the break statement within a for loop in C#.
Example
using System;
class Program
{
static void Main()
{
string message = "Good morning ! Welcome to C# Programming.";
for (int s = 0; s < message.Length; s++)
{
if (message[s] == '!')
{
Console.WriteLine("\n Exclamation mark found. Exit the loop.");
break;
}
Console.Write(message[s]);
}
}
}
Output:
Good morning
Exclamation mark found. Exit the loop.
Explanation:
In this instance, we've initialized string-type data and assigned corresponding values. Subsequently, a for loop is employed to iterate through the values. Following this, a break statement is utilized to terminate the program. Ultimately, the output is displayed using the Console.WriteLine method.
Break Statement Using While Loop
In C#, a break statement is crucial inside a while loop, especially when the number of iterations is uncertain and contingent on the condition.
Syntax:
It has the following syntax.
While(condition)
{
If(condition)
{
break; // exit the loop
}
}
C# Break Statement Example using While Loop
Let's consider a scenario to demonstrate the use of the break statement within a while loop in C#.
Example
using System;
class Program
{
static void Main()
{
int num, fact = 1;
Console.Write("Enter a positive number: ");
num = Convert.ToInt32(Console.ReadLine());
if (num < 0)
{
Console.WriteLine("Factorial is not defined for negative numbers!");
return; // Exit the program
}
int i = num;
while (true) // Infinite loop
{
if (i == 0 || i == 1)
{
break; // Exit the loop when i reach 0 or 1
}
fact *= i;
i--;
}
Console.WriteLine("The Factorial of " + num + " is " + fact);
}
}
Output:
Enter a positive number: 5
The Factorial of 5 is 120
Explanation:
In this instance, we calculate the factorial of integers through the utilization of a while loop. The user is requested to input a number. Should the number be negative or 1, the while loop terminates as factorials are not defined for negative numbers. For positive numbers, the script proceeds with the factorial computation. Subsequently, we employ the Console.WriteLine method to display the outcome.
Break Statement using do-while loop
In C#, the do-while loop is the part of the loop that executes at least once before checking the condition. The break statement can be used to exit the loop, regarding the condition. It is also known as the exit control loop.
Syntax:
It has the following syntax.
do
{
if(break_condition)
{
break; //break statement
}
// Execute the remaining code
}
while(condition)
C Break Statement Example using do-while loop
Let's consider an example to demonstrate the use of the break statement in a do-while loop in C#.
Example
using System;
class Program
{
static void Main()
{
int num = 3;
do
{
Console.WriteLine("Words: " + num);
if (num == 5) // break the loop
{
Console.WriteLine("Break the loop at number = " + num);
break;
}
num++; // Incrementation
}
while (num <= 7); // Check the while loop condition
Console.WriteLine("Exit the loop.");
}
}
Output:
Words: 3
Words: 4
Words: 5
Break the loop at number = 5
Exit the loop.
Explanation:
In this instance, an integer data type variable "num" is initialized with a value. The do-while loop iterates at least once prior to evaluating the condition. The termination condition is set to (num=5), signifying that when this condition is met, the program exits. Subsequently, the output is displayed using the Console.WriteLine method.
Break Statement with Nested Loop
In C#, the nested while loop is a looping construct in which one loop is contained within another loop. Within a nested loop structure, the inner loop runs to completion for every iteration of the outer loop.
Syntax:
It has the following syntax.
for(initialization; condition; updation)
{
for(initialization; condition; updation)
{
If(condition)
{
break; // exit the inner loop only
}
}
}
C# Break Statement Example using Nested Loop
Let's consider an example to demonstrate the use of the break statement within a Nested loop.
Example
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 3; i++) // Outer loop
{
for (int j = 1; j <= 5; j++) // Inner loop
{
if (j == 4)
{
break; // Exit the inner loop when j == 4
}
Console.WriteLine($"i = {i}, j = {j}");
}
}
}
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
Exaplanation:
In this instance, a while loop within another while loop was employed to display numbers. The external loop iterates from i=1 to i=3, while the internal loop ranges from j=1 to j=5. Subsequently, a break statement was implemented when j reaches 4, causing an exit from the loop at that point. Ultimately, the outcome is presented through the utilization of the Console.WriteLine method.
Break Statement Using Infinite Loop
In C#, the break statement can be employed within an infinite loop to halt the execution flow within the infinite loop.
Syntax:
It has the following syntax.
while(true)
{
If(condition)
{
break;
}
}
C# Break Statement Example using an Infinite Loop
Let's consider a scenario to demonstrate the use of the break statement within an endless loop.
Example
using System;
class Program
{
static void Main()
{
int count = 1;
while (true) // Infinite loop
{
Console.WriteLine("Number: " + count);
if (count == 4) // exit condition
{
Console.WriteLine("Breaking the loop");
break; // terminates the loop
}
count++;
}
Console.WriteLine("Exit the loop successfully.");
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Breaking the loop
Exit the loop successfully.
Foreach Loop
In C#, the foreach loop is specifically created for iterating through a collection such as an array, list, or other enumerable data types. It streamlines the task of accessing every element within the collection without requiring manual checks.
Syntax:
It has the following syntax.
foreach(datatype variable_name in collection)
{
// code to execute the foreach statement
}
C# Foreach Loop Example:
Let's consider an instance to demonstrate the foreach loop with the inclusion of a break statement in C#.
Example
using System;
class Program
{
static void Main()
{
int[] number = { 5, 10, 15, 20, 25 };
Console.WriteLine("Searching for number 15...");
foreach (int num in number)
{
if (num == 15)
{
Console.WriteLine("Number 15 found!");
break; // Exit the loop when 15 is found
}
Console.WriteLine($"Checked number: {num}");
}
Console.WriteLine("Loop finished.");
}
}
Output:
Searching for number 15...
Checked number: 5
Checked number: 10
Number 15 found!
Loop finished.
Explanation:
In this instance, we are seeking the value 15 within a collection of integers that have been predefined. Employing a loop, we sequentially examine each number. Upon encountering the specified condition, the loop is terminated, effectively ending the program. Following this, the Console.WriteLine method is utilized to display the final outcome.
Break Statement using Switch-case Statement
In C#, the switch statement serves as a decision-making tool that permits the execution of multiple code blocks depending on the condition's value. It is alternatively referred to as a Conditional statement.
The break statement within a switch case is employed to terminate the code block until the specified break condition is met. In situations where the break condition is not satisfied, the program will proceed to the subsequent case for execution.
Syntax:
It has the following syntax.
switch(expression)
{
case expression_value1;
// statement
break;
case expression_value1;
// statement
break;
case expression_value1;
// statement
break;
default:
// statement
}
Where,
- Switch(expression): The value of the expression is initialised once.
- expression_value: It checks the given expressions. If they match, the code will be executed and break the program; otherwise, it moves to the next statement.
- break;: It is used to exit the program.
- default: It is the optional part of the switch statement; if no expression matches, this
- block executes.
C# Break Statement Example using Switch Case Statement
Let's consider a scenario to demonstrate the use of the break statement within a switch case construct in C#.
Example
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number (1-3): ");
string input = Console.ReadLine();
if (int.TryParse(input, out int number))
{
switch (number)
{
case 1:
Console.WriteLine("You choose One.");
break;
case 2:
Console.WriteLine("You choose Two.");
break;
case 3:
Console.WriteLine("You choose Three.");
break;
default:
Console.WriteLine("Invalid choice. Please enter 1, 2, or 3.");
break;
}
}
else
{
Console.WriteLine("Invalid input. Please enter a number.");
}
Console.WriteLine("Switch statement complete.");
}
}
Output:
Enter a number(1-3):
You choose One.
Switch Statement complete.
Explanation:
In this instance, the user is requested to input a number ranging from 1 to 3. Subsequently, we employ the switch statement to validate the input. Ultimately, we utilize the Console.WriteLine method to display the result.
Advantages of the break Statement:
Several benefits of the break statement in C# include the following:
- Utilizing the break statement enhances program efficiency by halting unnecessary iterations.
- Clearly indicating termination points improves code readability.
Conclusion:
In C#, the break statement serves as the means to terminate the code execution when a specified condition is met. Utilizing the break statement enhances code efficiency by halting unnecessary iterations. Careful attention is needed to maintain code clarity and avoid programming ambiguities.
C# Break Statement FAQs:
1) What is the break statement?
The break statement is employed to end the execution of a loop or a switch statement.
The break statement in the C# programming language is used to terminate the current loop or switch statement and transfer control to the statement immediately following the terminated loop or switch.
The break statement is employed to end the execution of a loop (for loop, while loop, do-while loop) or switch statement.
3) What is the difference between the break and continue statements in C#?
Break: It is employed to conclude the loop, effectively ceasing the loop iteration and transitioning control outside of the loop.
The break statement is employed to halt the execution of a loop (for loop, while loop, do-while loop) or switch statement.
4) Does break work in try catch finally block?
Yes, we can employ the break statement inside the try, catch, finally block.
Syntax:
It has the following syntax.
While(true)
{
try
{
break; // break condition
}
catch
{
// handle error
}
}
5) Can the break statement be used within a foreach loop in programming languages?
Yes, a break statement is permissible within a conditional statement in a foreach loop.
Syntax:
It has the following syntax.
foreach(datatype variable_name in collection)
{
// code to execute foreach statement
}