Menu
Coddy logo textTech

Next (Continue)

Part of the Fundamentals section of Coddy's R journey — lesson 41 of 78.

While break exits a loop entirely, sometimes you only want to skip the current iteration and continue with the next one. The next statement does exactly that.

for (i in 1:5) {
  if (i == 3) {
    next
  }
  print(i)
}

Output:

[1] 1
[1] 2
[1] 4
[1] 5

When i equals 3, the next statement skips the rest of that iteration, so 3 is never printed. The loop then continues with 4 and 5 as normal.

This is useful when you want to filter out certain values without stopping the entire loop. For example, printing only even numbers:

for (num in 1:6) {
  if (num %% 2 != 0) {
    next
  }
  print(num)
}

Output:

[1] 2
[1] 4
[1] 6

Here, odd numbers are skipped using next, and only even numbers get printed. The key difference from break is that the loop keeps running - it just skips specific iterations.

challenge icon

Challenge

Easy

Read a number n from input. Use a for loop to iterate from 1 to n and print only the numbers that are not divisible by 4.

Use the next statement to skip numbers that are divisible by 4, and print all other numbers using print().

For example, if the input is 10, the output should be:

[1] 1
[1] 2
[1] 3
[1] 5
[1] 6
[1] 7
[1] 9
[1] 10

Notice that 4 and 8 are skipped because they are divisible by 4.

Cheat sheet

The next statement skips the current iteration of a loop and continues with the next one:

for (i in 1:5) {
  if (i == 3) {
    next
  }
  print(i)
}

Output:

[1] 1
[1] 2
[1] 4
[1] 5

When i equals 3, next skips the rest of that iteration, so 3 is never printed. The loop continues with the remaining values.

Example - printing only even numbers:

for (num in 1:6) {
  if (num %% 2 != 0) {
    next
  }
  print(num)
}

Output:

[1] 2
[1] 4
[1] 6

Unlike break which exits the loop entirely, next only skips specific iterations while the loop continues running.

Try it yourself

# Read input
con <- file("stdin", "r")
n <- as.integer(suppressWarnings(readLines(con, n = 1)))

# TODO: Write your code below
# Use a for loop to iterate from 1 to n
# Use the next statement to skip numbers divisible by 4
# Print all other numbers using print()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals