0
0
R Programmingprogramming~5 mins

While loop in R Programming

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of actions as long as a condition is true. It saves time by avoiding writing the same code again and again.

When you want to keep asking a user for input until they give a valid answer.
When you want to count up or down until a certain number is reached.
When you want to repeat a task until something changes in your data.
When you don't know in advance how many times you need to repeat something.
Syntax
R Programming
while (condition) {
  # code to repeat
}

The condition is checked before each loop. If it is TRUE, the code inside runs.

If the condition never becomes FALSE, the loop will run forever (infinite loop).

Examples
This prints numbers 1 to 5 by increasing count each time.
R Programming
count <- 1
while (count <= 5) {
  print(count)
  count <- count + 1
}
This prints 10, 8, 6, 4, 2 by subtracting 2 each time.
R Programming
x <- 10
while (x > 0) {
  print(x)
  x <- x - 2
}
Sample Program

This program prints a message with the current number from 1 to 3.

R Programming
number <- 1
while (number <= 3) {
  print(paste("Number is", number))
  number <- number + 1
}
OutputSuccess
Important Notes

Make sure the condition will become FALSE at some point to avoid infinite loops.

You can use break inside the loop to stop it early if needed.

Summary

A while loop repeats code while a condition is TRUE.

It is useful when you don't know how many times to repeat in advance.

Always update something inside the loop to eventually stop it.