Challenge - 5 Problems
For Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple for loop with sequence
What is the output of this R code?
result <- c()
for (i in 1:4) {
result <- c(result, i * 2)
}
print(result)R Programming
result <- c() for (i in 1:4) { result <- c(result, i * 2) } print(result)
Attempts:
2 left
💡 Hint
Remember the loop multiplies each number by 2 before adding to the result.
✗ Incorrect
The loop runs from 1 to 4, multiplying each number by 2 and adding it to the result vector. So the output is 2, 4, 6, 8.
❓ Predict Output
intermediate2:00remaining
Output of nested for loops with sum
What is the output of this R code?
total <- 0
for (i in 1:2) {
for (j in 1:3) {
total <- total + i + j
}
}
print(total)R Programming
total <- 0 for (i in 1:2) { for (j in 1:3) { total <- total + i + j } } print(total)
Attempts:
2 left
💡 Hint
Add all pairs of i and j from the loops.
✗ Incorrect
The sums are: (1+1)+(1+2)+(1+3)+(2+1)+(2+2)+(2+3) = 2+3+4+3+4+5 = 21. But the code adds i+j each iteration to total, so total is 21.
🔧 Debug
advanced2:00remaining
Identify the error in this for loop
What error does this R code produce?
for i in 1:5 {
print(i)
}R Programming
for i in 1:5 { print(i) }
Attempts:
2 left
💡 Hint
Check the syntax of the for loop header in R.
✗ Incorrect
In R, the for loop syntax requires parentheses around the loop variable and sequence: for (i in 1:5) {...}. Missing parentheses cause a syntax error at '{'.
❓ Predict Output
advanced2:00remaining
Output of for loop with conditional break
What is the output of this R code?
result <- c()
for (i in 1:10) {
if (i > 4) {
break
}
result <- c(result, i)
}
print(result)R Programming
result <- c() for (i in 1:10) { if (i > 4) { break } result <- c(result, i) } print(result)
Attempts:
2 left
💡 Hint
The loop stops when i is greater than 4.
✗ Incorrect
The loop adds numbers 1 to 4 to result. When i becomes 5, the break stops the loop, so 5 is not added.
🧠 Conceptual
expert2:00remaining
Number of iterations in a for loop with sequence and step
How many times will this R for loop run?
count <- 0
for (i in seq(2, 10, by=3)) {
count <- count + 1
}
print(count)R Programming
count <- 0 for (i in seq(2, 10, by=3)) { count <- count + 1 } print(count)
Attempts:
2 left
💡 Hint
Check the sequence generated by seq(2, 10, by=3).
✗ Incorrect
seq(2, 10, by=3) generates 2, 5, 8. So the loop runs 3 times.