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.
break StatementWe 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.
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); } } }
continue StatementThe 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."
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); } } }
You can also use break and continue inside while loops!
using System;class Program { static void Main() { int i = 0; while (i < 10) { if (i == 4) { i++; continue; // Skips 4 } Console.WriteLine(i); i++; } } }
Which keyword skips the current iteration and jumps to the next iteration of the loop?