← Back to R Course | Chapter 4: Control Flow | Lesson 6 of 6

break and next

break ends a loop completely, while next skips only the current turn and continues with the following one. It is like leaving a game versus passing on one round.

In this page:

  1. break and next
Syntax
r
for (item in vector_name) {
  if (skip_condition) next
  if (stop_condition) break
  # body
}

break and next

break immediately exits the nearest enclosing loop, while next skips the rest of the current iteration and moves to the next one -- R's equivalent of continue in other languages.

Both work inside for, while, and repeat loops. They give finer control over loop execution beyond the loop's own condition.

Note: R uses next where many other languages use continue -- remember this naming difference.

Example: break and next

markup
for (i in 1:10) {
  if (i %% 2 == 0) {
    next  # skip even numbers
  }
  if (i > 7) {
    break  # stop once past 7
  }
  cat(i, "\n")
}
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
  1. Using next outside a loop, which gives an error.
  2. Expecting break to leave all nested loops, when it only exits the innermost one.
  3. Placing next after code that should not run, so the statements before it still execute.
Chapter Summary
  • if, else, and ifelse() choose between alternatives.
  • for, while, and repeat loops repeat code.
  • break and next control loop flow.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.