break and continue
break stops a loop completely, like leaving a game, while continue skips just the current turn and moves on. Both give you control over a repeating task.
In this page:
Syntax
break; // exit the nearest loop or switch
continue; // skip to the next iteration
break and continue
break immediately exits the nearest enclosing loop or switch, while continue skips the rest of the current iteration and jumps to the next one.
Both give you finer control inside loops beyond what the loop condition alone provides. Overusing them can make control flow harder to follow, so use them sparingly.
Note:
Use
continue to skip invalid items early instead of nesting the rest of the loop body in an if.Example: break and continue
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue; // skip even numbers
if (i > 7)
break; // stop once we pass 7
Console.WriteLine(i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
breakand expecting it to exit both loops in a nested loop, when it exits only the innermost. - Placing
continuebefore the increment in awhileloop, causing an infinite loop. - Using
breakoutside a loop or switch, which is a compile error.
Chapter Summary
if/elseandswitchchoose which code runs.for,while,do-while, andforeachloops repeat code.breakandcontinuecontrol loop flow.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: