R: While Loop

While loop is the type of control flow statement which is used to iterate a block of code several numbers times. It terminates when the value of the Boolean expression will be false.

In the while loop, firstly the condition will be checked, and then a set of statements will execute. It executes the same code again and again until a stop condition is met.

In the while loop, we can check for the condition to be true or false n+1 times rather than n times. It is because while loop checks for the condition before entering the loop.

Syntax

while (test_expression) {  
   statement  
} 

Flowchart

R While Loop Flowchart

Example

i<-1

while (i < 7)
{
    print(i)
    i = i + 1
}

Output:

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