R Tutorial



R BREAK/NEXT


break and next in R

In R, break and next are special statements used inside loops to control the flow of iteration:

  • break: Immediately stops the loop and exits it.
  • next: Skips the current iteration and continues with the next iteration of the loop.

Using break

break is useful when you want to stop looping once a condition is met.

for(i in 1:10) {
  if(i == 6) {
    break  # stop the loop when i is 6
  }
  print(i)
}
  

Output: 1 2 3 4 5

Using next

next is useful when you want to skip certain iterations but keep looping.

for(i in 1:10) {
  if(i == 4) {
    next  # skip printing when i is 4
  }
  print(i)
}
  

Output: 1 2 3 5 6 7 8 9 10

Example: Combining break and next

for(i in 1:10) {
  if(i == 3) {
    next   # skip iteration when i is 3
  }
  if(i == 7) {
    break  # stop the loop when i is 7
  }
  print(i)
}
  

Output: 1 2 4 5 6

Summary

Statement Effect in Loop
break Stops the entire loop immediately.
next Skips current iteration and moves to the next one.

Practice Exercise

Write a for loop that prints all numbers from 1 to 15, but:

  • Skip printing numbers divisible by 4 using next.
  • Stop the loop completely when the number reaches 12 using break.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review