R — Loops with next and break
An R for loop visits successive values in a vector. next skips to the next value and break ends the loop.
A simple example
Print the numbers 1 to 3
- Start with Start at 1
- Do this Visit 1, 2, 3
- Result 1 → 2 → 3
for (n in 1:3) {
cat(n, "\n", sep = "")
}
1 2 3
Stop at the end of a batch
next skips the rest of one iteration. break leaves the loop entirely. Assignment with the left arrow updates the running total in the current scope.
A scanner sends 4, then an invalid reading of −1, then the batch marker 0. Add 4, skip the invalid reading and stop at the marker. The later 7 belongs to the next batch.
Run the example
R 4. Run these commands from the directory containing the example.
Rscript Lesson.R
total <- 0L
for (reading in c(4L, -1L, 0L, 7L)) {
if (reading == 0L) break
if (reading < 0L) next
total <- total + reading
}
cat(total, "\n", sep = "")
4
Start the total at zero. Add 4, skip −1, and stop at 0. The final 7 belongs to a different batch, so the result is 4.
Try it yourself
What changes if the input is 4, −1, 7, 0?
Check your answer
Both positive readings arrive before the sentinel. Their sum is 11. An empty sequence yields 0.