0
0
R Programmingprogramming~20 mins

While loop in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple while loop
What is the output of the following R code?
R Programming
x <- 1
while (x <= 3) {
  print(x)
  x <- x + 1
}
A
[1] 1
[1] 2
B
[1] 1
[1] 2
[1] 3
C
[1] 1
[1] 2
[1] 3
[1] 4
DError: object 'x' not found
Attempts:
2 left
💡 Hint
The loop runs while x is less than or equal to 3, printing x each time and increasing it by 1.
Predict Output
intermediate
2:00remaining
While loop with break statement
What will be printed by this R code?
R Programming
i <- 1
while (TRUE) {
  if (i > 4) break
  print(i)
  i <- i + 1
}
A
[1] 1
[1] 2
[1] 3
[1] 4
B
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
CError: object 'i' not found
D
[1] 1
[1] 2
[1] 3
Attempts:
2 left
💡 Hint
The loop runs forever until the break condition is met when i is greater than 4.
Predict Output
advanced
2:00remaining
While loop with nested if and continue logic
What is the output of this R code?
R Programming
x <- 0
while (x < 5) {
  x <- x + 1
  if (x == 3) next
  print(x)
}
A
[1] 1
[1] 2
[1] 4
[1] 5
B
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
C
[1] 1
[1] 2
[1] 3
[1] 4
DError: unexpected symbol in "if (x == 3) next"
Attempts:
2 left
💡 Hint
The 'next' statement skips the rest of the loop body when x equals 3.
🔧 Debug
advanced
2:00remaining
Identify the error in the while loop
What error does this R code produce?
R Programming
count <- 1
while (count < 5) {
  print(count)
  count <- count + 1
}
AInfinite loop printing 1 forever
BError: object 'count' not found
CError: unexpected symbol in 'count <- count + 1'
DPrints 1, 2, 3, 4 then stops
Attempts:
2 left
💡 Hint
Check the indentation and braces for the while loop body.
🧠 Conceptual
expert
2:00remaining
Number of iterations in a while loop
How many times will the loop run in this R code?
R Programming
n <- 10
sum <- 0
while (n > 0) {
  sum <- sum + n
  n <- n - 2
}
sum
A6
B10
C5
DError: object 'sum' not found
Attempts:
2 left
💡 Hint
The loop decreases n by 2 each time until n is no longer greater than 0.