R While Loop

🔁 R While Loop

The while loop in R is used to repeat a block of code as long as a condition is TRUE.

It is useful when the number of iterations is not known in advance.


🔹 Syntax of while Loop

while (condition) {
# code to execute
}

👉 The loop keeps running until the condition becomes FALSE.


🔹 1. Basic While Loop Example

i <- 1

while (i <= 5) {
print(i)
i <- i + 1
}

Output:

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

🔹 2. While Loop with Calculation

i <- 1
sum <- 0

while (i <= 5) {
sum <- sum + i
i <- i + 1
}

sum

✔ Calculates the sum of numbers from 1 to 5


🔹 3. While Loop with Logical Condition

x <- 10

while (x > 0) {
print(x)
x <- x - 2
}


🔹 4. Infinite While Loop ❌ (Be Careful)

while (TRUE) {
print("Hello")
}

❗ This loop never stops unless you interrupt it manually
👉 Always ensure the condition will eventually become FALSE


🔹 5. Using break in While Loop

break is used to exit the loop immediately.

i <- 1

while (i <= 10) {
if (i == 6) {
break
}
print(i)
i <- i + 1
}


🔹 6. Using next in While Loop

next skips the current iteration and continues with the next one.

i <- 0

while (i < 5) {
i <- i + 1
if (i == 3) {
next
}
print(i)
}

Output:

[1] 1
[1] 2
[1] 4
[1] 5

🔹 7. While vs For Loop

While LoopFor Loop
Condition-basedSequence-based
Iterations unknownIterations known
More flexibleMore readable

🔹 Best Practices ✔

  • Always update the loop variable

  • Avoid infinite loops

  • Use for loop if range is fixed

  • Keep conditions simple and clear


📌 Summary

  • while loop repeats while condition is TRUE

  • Condition is checked before execution

  • break stops the loop

  • next skips an iteration

You may also like...