0
0
R Programmingprogramming~10 mins

While loop in R Programming - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop
Initialize variable
Check condition
|Yes
Execute loop body
Update variable
Back to Check condition
Exit loop
Back to Check condition
The while loop starts by checking a condition. If true, it runs the loop body and updates variables, then checks again. It stops when the condition is false.
Execution Sample
R Programming
x <- 1
while (x <= 3) {
  print(x)
  x <- x + 1
}
This code prints numbers 1 to 3 by increasing x until the condition x <= 3 is false.
Execution Table
Stepx valueCondition (x <= 3)ActionOutput
11TRUEPrint 1, x <- 21
22TRUEPrint 2, x <- 32
33TRUEPrint 3, x <- 43
44FALSEExit loop
💡 x reaches 4, condition 4 <= 3 is FALSE, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
x12344
Key Moments - 2 Insights
Why does the loop stop when x is 4 even though the loop body updates x after printing?
The condition is checked before each loop iteration (see Step 4 in execution_table). When x becomes 4, the condition x <= 3 is FALSE, so the loop exits before printing or updating again.
What happens if the initial value of x is greater than 3?
The condition is FALSE at the start, so the loop body never runs (no output). This is shown by the condition check before the first iteration.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of x at Step 3?
A3
B2
C4
D1
💡 Hint
Check the 'x value' column in row for Step 3 in execution_table.
At which step does the condition become FALSE and the loop stops?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look at the 'Condition' column in execution_table to find when it is FALSE.
If we start with x <- 5, what will happen to the loop execution?
ALoop runs once and prints 5
BLoop runs infinitely
CLoop does not run at all
DLoop runs twice
💡 Hint
Refer to key_moments about initial condition check before loop body execution.
Concept Snapshot
while (condition) {
  # code to repeat
}

- Checks condition before each loop
- Runs code block if TRUE
- Stops when condition is FALSE
- Useful for repeating until a condition changes
Full Transcript
This visual trace shows how a while loop works in R. We start with x = 1. The loop checks if x is less or equal to 3. If yes, it prints x and adds 1 to x. This repeats until x becomes 4, when the condition fails and the loop stops. The variable tracker shows x changing from 1 to 4 step by step. Key moments explain why the loop stops before printing 4 and what happens if x starts bigger than 3. The quiz tests understanding of variable values and loop stopping conditions.