0
0
R Programmingprogramming~20 mins

Next and break statements in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Next and Break Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of loop with next statement
What is the output of the following R code?
R Programming
result <- c()
for(i in 1:5) {
  if(i == 3) next
  result <- c(result, i)
}
print(result)
A[1] 1 2 4 5
B[1] 1 2 3 4 5
C[1] 1 2
D[1] 4 5
Attempts:
2 left
💡 Hint
The next statement skips the current loop iteration when i equals 3.
Predict Output
intermediate
2:00remaining
Output of loop with break statement
What is the output of this R code?
R Programming
result <- c()
for(i in 1:5) {
  if(i == 4) break
  result <- c(result, i)
}
print(result)
A[1] 1 2 3 4
B[1] 1 2 3
C[1] 4 5
D[1] 1 2 3 4 5
Attempts:
2 left
💡 Hint
The break statement stops the loop when i equals 4.
🧠 Conceptual
advanced
3:00remaining
Effect of next and break in nested loops
Consider the following R code with nested loops. What is the value of total after running it?
R Programming
total <- 0
for(i in 1:3) {
  for(j in 1:3) {
    if(j == 2) next
    if(i == 2) break
    total <- total + i * j
  }
}
total
A12
B9
C0
D16
Attempts:
2 left
💡 Hint
Remember next skips the current inner loop iteration; break stops the inner loop when i is 2.
🔧 Debug
advanced
2:00remaining
Identify error in loop with next and break
What error does this R code produce?
R Programming
for(i in 1:3) {
  if(i == 2) next
  if(i == 3) break
  print(i)
  next
}
ARuntime error: infinite loop
BSyntaxError: unexpected 'next'
CNo error, prints 1 then stops
DError: object 'i' not found
Attempts:
2 left
💡 Hint
Check how next and break work inside the loop and their placement.
Predict Output
expert
3:00remaining
Output of complex loop with next and break
What is the output of this R code?
R Programming
output <- c()
for(i in 1:6) {
  if(i %% 2 == 0) next
  if(i > 4) break
  output <- c(output, i)
}
print(output)
A[1] 1 3
B[1] 1 3 5
C[1] 1 3 5 6
D[1] 1 2 3 4
Attempts:
2 left
💡 Hint
next skips even numbers; break stops loop when i is greater than 4.