0
0
R Programmingprogramming~5 mins

While loop in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ARepeats code a fixed number of times
BRepeats code while a condition is TRUE
CRuns code once regardless of condition
DStops the program immediately
When is the condition in a while loop checked?
AOnly once at the start
BAfter each repetition
CBefore each repetition
DNever
What happens if the while loop condition is FALSE at the start?
AThe loop code does not run
BThe loop runs once
CThe loop runs infinitely
DThe program crashes
How can you prevent an infinite while loop?
AUse a for loop instead
BDo nothing; infinite loops are normal
CAdd a break statement outside the loop
DChange variables inside the loop to eventually make the condition FALSE
What will this code print?<br>i <- 2<br>while(i < 5) {<br> print(i)<br> i <- i + 2<br>}
A2 and 4
B2, 3, 4
C2, 4, 6
DNothing
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.