0
0
R Programmingprogramming~20 mins

For loop in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
For Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A[1] 1 2 3 4
B[1] 2 3 4 5
C[1] 4 8 12 16
D[1] 2 4 6 8
Attempts:
2 left
💡 Hint
Remember the loop multiplies each number by 2 before adding to the result.
Predict Output
intermediate
2: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)
A[1] 18
B[1] 21
C[1] 12
D[1] 15
Attempts:
2 left
💡 Hint
Add all pairs of i and j from the loops.
🔧 Debug
advanced
2: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)
}
ASyntaxError: unexpected symbol 'i'
BError: object 'i' not found
CError: unexpected '{' in "for i in 1:5 {"
DNo error, prints numbers 1 to 5
Attempts:
2 left
💡 Hint
Check the syntax of the for loop header in R.
Predict Output
advanced
2: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)
A[1] 1 2 3 4
B[1] 1 2 3 4 5
C[1] 1 2 3
D[1] 5 6 7 8 9 10
Attempts:
2 left
💡 Hint
The loop stops when i is greater than 4.
🧠 Conceptual
expert
2: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)
A3
B2
C5
D4
Attempts:
2 left
💡 Hint
Check the sequence generated by seq(2, 10, by=3).