Break vs. continue in C#

Mastering control flow in any high-level programming language is crucial to becoming an expert in that language. The continue and break statements play essential roles in controlling the execution of loops. Understanding how these two statements work in the control flow is vital to writing efficient algorithms.

In C#, continue and break keywords are used as the control flow statements within loops. They serve different purposes.

The continue statement

The continue statement allows us to skip the current iteration of a loop and move to the next one. It is used when we want to bypass a specific condition or value within a loop without ending the loop altogether.

Example

Let’s see an example of the continue statement where we want to print only the odd number.

class HelloWorld
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
continue;
System.Console.WriteLine(i);
}
}
}

Code explanation

  • Line 5: It runs for numbers 0-9.

  • Lines 7–8: It skips the number when i % 2 == 0, i.e., skipping the even numbers.

The break statement

We use the break statement when we want to terminate the loop entirely based on a certain condition. This is helpful when we want to exit the loop and skip all subsequent iterations.

Example

Let’s see an example of the break statement where we will perform linear search to find a specific number in an array, and when we find that number, we will skip the all the subsequent iterations of the loop.

class HelloWorld
{
static void Main()
{
int[] arr = { 2, 4, 3, 6, 5, 10, 12 };
int target = 5;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == target)
{
System.Console.WriteLine("Target found at index: " + i);
break;
}
}
}
}

Code explanation

  • Line 5: An array holding the data to be searched.

  • Line 6: The target value which we want to search.

  • Lines 9–13: If the target value is found, we will print the message and break the entire loop.

Comparison

Let's compare the differences between the continue and break statements.

Comparison of continue and break statements

Feature

Continue

Break

Purpose

Skips the current loop iteration and moves to the next iteration.

Exits the loop immediately by skipping all subsequent iterations.

Loop continuation

Yes

No

Common use case

When we want to skip some iterations of the loop bases on a specific condition.

When we want to terminate the entire when a specific condition is met.

Conclusion

Understanding the use of continue and break statements in C# will significantly improve the execution of the loops. By implementing these statements, we can easily manage complex conditions within the loops. The control flow statements also helps in making the code more readable which eventually helps in the debugging the code.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved