You are currently viewing While Loop in R with Examples

The while loop in R is a control statement found in any programming language, used to repeatedly execute a set of statements as long as a specified condition remains TRUE. In R programming, there are three types of loops: the for loop, the while loop, and the repeat loop. This article will cover various aspects of the while loop, providing multiple examples to illustrate its usage.

1. Syntax of while Loop

Below is the syntax of the while control statement.


# while statement syntax
while ( condition ) 
{
  # one or more statements
  # to execute
}

2. Flow of while Loop

The below chart demonstrates the flow of a while loop. Here, the condition is tested at the start of the while execution, when the condition is TRUE, the control enters into the while block to execute the statement and again goes back to the condition to check, it continues this process iteratively as long as the condition is TUE. when condition FALSE, it exits the while loop.

r while loop

3. while Loop in R Example

Let’s learn the while loop concept by going through a very simple example. The following example executes the while block as long as the condition i<=n becomes false. Here, first, n is assigned a value 5 and i is assigned a value 1. within the loop we increment i value by 1 and the loop executes until i reaches n.


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

# Output
#[1] 1
#[1] 2
#[1] 3
#[1] 4
#[1] 5

4. while Break & Next Statements

The break and next statements in R are jump statements that interrupt loops. The break statement is used in a while loop to instantly terminate and exit the loop, irrespective of the loop’s condition. Here is an example:


The behavior of the next statement in other languages is equivalent to a continue statement. The next statement skips the remaining code in the current block and jumps to the condition to begin the next iteration. Here is an example:


# Using break & next
i <- 1
n <- 5
while (i <= n) {
  if(i == 4){
    break
  }
  if(i == 3){
    i = i + 1
    next
  }
  print(i)
  i = i + 1
}

5. Nested while Loop

A while loop contained within another while loop is known as a nested loop. When jump statements such as break or next are used in the inner loop, they only disrupt the inner loop and do not affect the outer loop.


# nested while loop
i=1
while (i <= 4) {
  j = 1
  while(j < 2) {
    print(i + j)
    j = j + 1
  }
  i = i + 1
}
# Output
# [1] 3
# [1] 4
# [1] 5

Conclusion

In this article, you have learned the syntax of the while loop in R and how to use it to execute the block of code until the condition becomes false. The while loop is a fundamental construct in programming for repeating a task a specified number of times. In R, there are three types of loops: the for loop, the while loop, and the repeat loop.

Related Articles

References