<- 0
count while ( count < 5 ) {
cat(count, " ")
<- count + 1
count }
0 1 2 3 4
We have seen that for
loops can repeatedly execute a block of code for each element specified. We can think of another scenario where we only want to continue executing a block of code as long as a given condition is TRUE
. The basic idea is:
WHILE there is money in my account
have lunch out
update my bank statement
In while
loops the condition is checked at the beginning of each iteration and the loop continues executing as long as the condition is TRUE
. The basic syntax in R which has a similar scaffolding to an if
clause:
while (condition) {
# code to execute while condition is True
}
To ensure that the condition will eventually become FALSE
, it is common usage to increment/decrement a counter variable in the loop body:
<- 0
count while ( count < 5 ) {
cat(count, " ")
<- count + 1
count }
0 1 2 3 4
There are some extra flow control instructions in while
loops that we are not going to see here in detail but it is important to mention them. They are:
break
: exits the loop immediatelynext
: skips the rest of the current iteration and moves to the nextwhile (TRUE) {
<- readline("Enter 'q' to quit: ")
user_input if (user_input == 'q') {
break
} }