Challenge - 5 Problems
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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 }
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.
✗ Incorrect
The loop starts with x = 1 and prints it. Then x increases by 1. This repeats until x becomes 4, which breaks the loop. So it prints 1, 2, and 3.
❓ Predict Output
intermediate2: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 }
Attempts:
2 left
💡 Hint
The loop runs forever until the break condition is met when i is greater than 4.
✗ Incorrect
The loop prints i starting at 1 and increases it by 1 each time. When i becomes 5, the break stops the loop. So it prints 1 to 4.
❓ Predict Output
advanced2: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) }
Attempts:
2 left
💡 Hint
The 'next' statement skips the rest of the loop body when x equals 3.
✗ Incorrect
When x is 3, the 'next' skips the print statement, so 3 is not printed. All other values from 1 to 5 except 3 are printed.
🔧 Debug
advanced2: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 }
Attempts:
2 left
💡 Hint
Check the indentation and braces for the while loop body.
✗ Incorrect
With braces, both print and increment are inside the loop, so count increases each iteration until it reaches 5, then loop stops.
🧠 Conceptual
expert2: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
Attempts:
2 left
💡 Hint
The loop decreases n by 2 each time until n is no longer greater than 0.
✗ Incorrect
Starting at 10, n decreases by 2 each iteration: 10, 8, 6, 4, 2. After 5 iterations, n becomes 0 and loop stops.