R While Loop
🔁 R While Loop
It is useful when the number of iterations is not known in advance.
🔹 Syntax of while Loop
👉 The loop keeps running until the condition becomes FALSE.
🔹 1. Basic While Loop Example
Output:
🔹 2. While Loop with Calculation
✔ Calculates the sum of numbers from 1 to 5
🔹 3. While Loop with Logical Condition
🔹 4. Infinite While Loop ❌ (Be Careful)
❗ 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.
🔹 6. Using next in While Loop
next skips the current iteration and continues with the next one.
Output:
🔹 7. While vs For Loop
| While Loop | For Loop |
|---|---|
| Condition-based | Sequence-based |
| Iterations unknown | Iterations known |
| More flexible | More readable |
🔹 Best Practices ✔
Always update the loop variable
Avoid infinite loops
Use
forloop if range is fixedKeep conditions simple and clear
📌 Summary
whileloop repeats while condition is TRUECondition is checked before execution
breakstops the loopnextskips an iteration
