A while
loop is a block of code that can be repeatedly executed given the condition needed to execute it, returns true
. Hence, the code runs in a loop as long as the condition holds.
while
loopThe first step to writing a loop is to understand the logic behind it. The illustration below shows the workings of a while
loop:
The next step is to understand the syntax of a while
loop in R. The code snippet below shows how to code a while
loop in R.
The condition_statement
is a single condition or a set of multiple conditions that return a boolean value of true
or false
.
If the returned value is true
only then will the loop execute the code inside it.
while(condition_statement){#Loop body goes here}
Now that we know how a while
loop works and its syntax, let’s look at a few examples to better understand how to use it in R.
This example shows what happens when the condition statement is false
from the start. The code inside the loop body is not executed and the program moves on to the code outside the while block.
iterator <- 10while(iterator>11){print("In while loop")iterator <- iterator + 1}print("Outside while loop")
This while
loop, in the example below, has a condition statement based on an incrementing numeric value. When the value of the iterator
exceeds 10, it should break.
iterator <- 1while(iterator<=10){print(iterator)iterator <- iterator + 1}print("Outside while loop")
This example shows how to use more than one condition in the loop. As seen on line 4 the while
loop has two conditions, one using the AND
operator and the other using the OR
operator.
Note: The
AND
condition must be fulfilled for the loop to run. However, if either of the conditions on theOR
side of the operator returnstrue
, the loop will run.
iterator <- 1second_iterator <- 10third_iterator <-1while(third_iterator <=4 && iterator<=10 || second_iterator<5){cat("First Iterator: ", iterator, "\n")cat("Second iterator: ",second_iterator, "\n")cat("Third iterator: ",third_iterator, "\n")iterator <- iterator + 1second_iterator <- second_iterator + 1third_iterator <- third_iterator + 1}print("Outside while loop")
Free Resources