The while loop executes the same code again and again until a stop condition is met.
Problem:
Write a while loop in R
Solution:
The simple syntax of while loop is as below:
while(condition)
{
expressions
}
The condition is usually expressed by a comparison between a control variable and a value. We can use a greater than(>), less than (<) or equal to(=) sign to evaluate the condition and the result is a logical value i.e. either TRUE or FALSE.
-
If it is True (T), the expressions or block of instructions inside the While loop is executed.
-
If it is False (F), the loop is never executed
We need to Increment or decrements the value of the control variable inside the while loop. After the value is incremented/decremented, it will again check for the condition. As long as the condition is True, the expressions inside the while loop will be executed. If the condition is False then it will exit from the while loop.
Example:
-
The control variable is i and it is assigned a value of “0” initially i.e. i = 0.
-
For the 1st iteration, i =0 i.e. i is less than 3 and thus the condition is TRUE and the value of i is printed as expected.
-
The value of i is incremented to 1
-
For the 2nd iteration, i=1 i.e. i is less than 3 and thus the condition is TRUE and the value of i is printed as expected.
-
The value of i is incremented to 2
-
For the 3rd iteration, i=2 i.e. i is less than 3 and thus the condition is TRUE and the value of i is printed as expected.
-
The value of i is incremented to 3
-
For the 4th iteration, i=3 i.e. i is equal to 3 and thus the condition is still TRUE and the value of i is printed as expected.
-
The value of i is incremented to 4
-
For the 5th iteration, i=4 i.e. i is greater than 3 and thus the condition is FALSE and the value of i is not printed as expected.
Now, if we print the value of i, it is 4.