Recall & Review
beginner
What is a while loop in R?
A while loop in R repeats a block of code as long as a given condition is TRUE. It checks the condition before each repetition.
Click to reveal answer
beginner
How do you write a basic while loop in R?
Use the syntax:<br>
while(condition) {
# code to repeat
}<br>The code inside runs while the condition is TRUE.Click to reveal answer
beginner
What happens if the condition in a while loop is FALSE at the start?
The code inside the while loop does not run at all because the condition is checked before the first iteration.
Click to reveal answer
intermediate
How can you avoid an infinite loop with a while loop?
Make sure the condition will eventually become FALSE by changing variables inside the loop. Otherwise, the loop runs forever.
Click to reveal answer
beginner
Example: What does this R code print?<br>
i <- 1
while(i <= 3) {
print(i)
i <- i + 1
}It prints:<br>1<br>2<br>3<br>Because i starts at 1 and increases by 1 each time until it is greater than 3.
Click to reveal answer
What does a while loop do in R?
✗ Incorrect
A while loop repeats the code block as long as the condition remains TRUE.
When is the condition in a while loop checked?
✗ Incorrect
The condition is checked before each time the loop runs.
What happens if the while loop condition is FALSE at the start?
✗ Incorrect
If the condition is FALSE initially, the loop body is skipped.
How can you prevent an infinite while loop?
✗ Incorrect
You must update variables so the condition becomes FALSE to stop the loop.
What will this code print?<br>i <- 2<br>while(i < 5) {<br> print(i)<br> i <- i + 2<br>}
✗ Incorrect
It prints 2 and 4 because i increases by 2 each time and stops before 5.
Explain how a while loop works in R and give a simple example.
Think about how you repeat a task until something changes.
You got /3 concepts.
What is an infinite loop and how can you avoid it when using a while loop?
Imagine a clock that never stops ticking.
You got /4 concepts.