R – while loop

While loop in R is used when the exact number of iterations of loop is not known beforehand. It executes the same code again and again until a stop condition is met.

while loop checks for the condition to be true or false n+1 times rather than n times. This is because while loop checks for the condition before entering the body of the loop.

Syntax:

while (test_expression) {
   statement
   update_expression
}

 
While-loop-in-R

How does a While loop execute?



  1. Control falls into the while loop.
  2. The flow jumps to Condition
  3. Condition is tested.
    1. If Condition yields true, the flow goes into the Body.
    2. If Condition yields false, the flow goes outside the loop
  4. The statements inside the body of the loop get executed.
  5. Updation takes place.
  6. Control flows back to Step 2.
  7. The while loop has ended and the flow has gone outside.

Important Points about while loop:

  • It seems to be that while loop will run forever but it is not true, condition is provided to stop it.
  • When the condition is tested and the result is false then loop is terminated.
  • And when the tested result is True, then loop will continue its execution.

Flowchart:
while-loop-flowchart-in-R

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate while loop
  
result <- c("Hello World")
i <- 1
  
# test expression 
while (i < 6) {
  
   print(result)
     
   # update expression 
   i = i + 1
}

chevron_right


Output:

[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"
[1] "Hello World"

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# R program to illustrate while loop
  
result <- 1
i <- 1
  
# test expression 
while (i < 6) {
  
   print(result)
     
   # update expression 
   i = i + 1
   result = result + 1
}

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.