Loops are used in programming to repeat a specific block of code. In this post, you will learn to create a while loop in R programming.
Use of While Loop in R Programming:
- In R programming, while loops are used to loop until a specific condition is met .
- While loop starts with Keyword while () {} , and all the Key words comes in different Colors.
- Open Braces is for Logical expressions /Conditions and curly Braces is for Body of the Loop
Let’s Take a small example:
Here the Counter Variable = 1 , While condition checks the condition is True or Not.
The Counter Value assigned is 1 , which is less than 12 so The while condition is true,
It enters into the Body of the loop 11 Times (until the counter value is less than 12 )
In any Iterative Loop statements, we should Use print statement to print the Variable value, here the counter Value is printed every time and it is incremented by 1 and Counter value for every iteration is printed in Console pane
Console Pane:
Here the Counter Value is incremented and Printed till 11.
Infinite While Loop :
In this example : the while condition is always FALSE, so it will not enter into the Body of the Loop , as soon as when You execute, the Loop Ceases and comes end of the loop and doesn’t Prints anything. In the console pane we see nothing printed.
Now lets Change the While expression/Condition to true and Execute:
Here, while condition is always TRUE, so it will enter into the Body of the Loop , as soon as when You execute, and Prints the statements Infinite times until the Condition is false. As we can see in the console Pane the Print statement printed infinite times.
Note : To stop this Infinite Loop , we should click on ESC Keyword or Click on STOP Button in red color in Console pane.