i

R Programming Complete Tutorial

R while loop

The while loop in R programming is used to repeat a block of statements for a given number of times until the specified condition is False.

While loop starts with the test condition, and if the condition is true, the statements inside the while loop will be executed; otherwise, it will stop and exit.

Syntax:

Flow Diagram:

A code initially come through expression and meet the test condition. If it is true, it will go to the loop body and execute the statements and return to the test condition. It will continue this until it returns FALSE and exit.

Example:

In this example, we will do the same addition of 1 to 100 using while loop.

First, we initialize 0 to sum and 1 to i.

Now in the while loop, it will check whether the condition is true or not. Indeed, i is less than 100, and it will go to the loop body and execute the statements.  In the first iteration sum=0, i=1, after the addition, the sum will be updated to 1, and i will be updated to 2. The second iteration, sum 1, i=2, the sum will store 3. In the next iteration, sum 3, i=3, the sum will be updated with 6. It will continue until i is 100.