While Loop in R - r - learn r - r programming



  • In R programming, while loops are used to loop until a specific condition is satisfied.
  • These is similar to for loop, but the iterations are controlled by a conditional statement.
 while loop

Syntax:

while (test_expression)
{
   statement
}

Syntax Explanation

  • test_expression is evaluated and the body of the loop is entered if the condition is TRUE. This process is repeated until test_expression evaluates to FALSE, in which case, the loop exits.
 while-loop

Sample Code:

x <- 5
while(x< 10) 
{ 
    x <- x+ 1
    print(x)  
}

Code Explanation

 while loop structure
  1. x is specifying to string variable. Here x is initialized to value as 5.
  2. The test_expression is x < 10 which evaluates to TRUE since 5 is less than 10.
  3. In the next iteration, the value of incrementing x is 5 and the loop continues. This will continue until x takes the value 10. The condition 10 < 10 will give FALSE, and then loop is exits.
  4. Here print() is used to print the value, that value stored in x variable.

Output

 while loop output
  1. Here in this output, the while loop will continue to run as long as x=5 is less than (x < 10) which will increase by 1 each time the loop runs (x+1) till 10.

Related Searches to While Loop in R