Challenge - 5 Problems
Next and Break Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The next statement skips the current loop iteration when i equals 3.
✗ Incorrect
The loop adds numbers 1 to 5 to the result vector except when i is 3. The next statement skips adding 3, so the output excludes 3.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
The break statement stops the loop when i equals 4.
✗ Incorrect
The loop adds numbers 1, 2, and 3 to the result vector. When i reaches 4, break stops the loop, so 4 and 5 are not added.
🧠 Conceptual
advanced3: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
Attempts:
2 left
💡 Hint
Remember next skips the current inner loop iteration; break stops the inner loop when i is 2.
✗ Incorrect
For i=1: j=1 adds 1*1=1, j=3 adds 1*3=3 (j=2 skipped), total=4. For i=2: break stops inner loop immediately at j=1 (no addition). For i=3: j=1 adds 3*1=3, j=3 adds 3*3=9 (j=2 skipped), total=16.
🔧 Debug
advanced2: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 }
Attempts:
2 left
💡 Hint
Check how next and break work inside the loop and their placement.
✗ Incorrect
The code prints 1, skips 2, and breaks at 3. The last next is redundant but valid. No error occurs.
❓ Predict Output
expert3: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)
Attempts:
2 left
💡 Hint
next skips even numbers; break stops loop when i is greater than 4.
✗ Incorrect
The loop adds odd numbers less than or equal to 4. When i=5, break stops the loop. So output is 1 and 3.