home / software / tips and tricks / C Sharp/Break and Continue Statement

C Sharp/Break and Continue Statement

Updated:  04/19/2006 11:04 AM
Author:  Shiju Mathews

Status:    Resolved.


The break statement alters the flow of a loop. It immediately exits the loop based upon a certain condition. After the loop is exited it continue to the next block of instructions. Exiting a loop early can boost program performance, it avoids unnecessary loops.

Lets take a look at some real code. The code is suppose to loop ten times but will exit prematurely and only loop five times.

C# Break Example



Output:


As you can see when the if condition is evaluated to true the break statement is executed. The for loop is prematurely exited immediately and it does not execute any other code in the loop. The break statement also works for while, do/while, and switch statements.

continue statement
The continue statement jumps over the following code within a loop. In other words it skips the proceeding code in the loop and continues to the next iteration in the loop. It does not exit the loop like the break will. Just like the break to work properly the continue statement needs an if condition to let the program know that if a certain condition is true the continue statement must be executed.

When the continue and break statements are used together it can greatly increase program performance within the loop structure. In the program example below there is an algorithm that will count from 1 to 10. The program will skip the fifth iteration to prove that the continue statement actually works.



Output:

The output skipped the number 5. When the condition is true the continue statement is executed and the remaining code is skipped. That means Console.WriteLine(count); command is skipped on the fifth iteration.
Tags: C Sharp/Break and Continue Statement
Updated on: December 2024