C# Break/Continue

C# Break and Continue

While a loop is running, there are times you might want to stop the loop entirely based on a specific condition, or skip the current iteration and jump straight to the next one. You can do this using break and continue.


The break Statement

We previously used break inside a switch statement to jump out of it. It can also be used to jump completely out of a loop. If the code hits a break keyword, the loop terminates immediately, and the program moves to the code below the loop.

Break Loop Example

using System;

class Program { static void Main() { for (int i = 0; i < 10; i++) { if (i == 4) { break; // Stops the loop completely when i equals 4 } Console.WriteLine(i); } } }


The continue Statement

The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop. It essentially says "skip the rest of the code in this block, and start the loop over for the next item."

Continue Loop Example

using System;

class Program { static void Main() { for (int i = 0; i < 10; i++) { if (i == 4) { continue; // Skips printing 4, but continues to 5 } Console.WriteLine(i); } } }


Break and Continue in While Loops

You can also use break and continue inside while loops!

While Loop Example

using System;

class Program { static void Main() { int i = 0; while (i < 10) { if (i == 4) { i++; continue; // Skips 4 } Console.WriteLine(i); i++; } } }


Exercise

?

Which keyword skips the current iteration and jumps to the next iteration of the loop?