While Loops
The next loop we will explore is the while
loop. This type of
loop will continue to execute as long as the specified condition remains
TRUE
. Once the condition evaluates to FALSE
,
the loop terminates. Here is how we can construct it:
while (condition) {
# run code
}
Similar to the for
loop, the while
loop
commences with the reserved keyword while
. However, instead
of iterating over a defined range of values, it operates based on a
specified condition. The loop continues to execute its block of code
as long as the condition evaluates to TRUE
.
It is akin to an if
statement, but with repeated evaluations
as long as the condition remains true. Therefore, it is essential to
update a value within the while
loop to ensure it
eventually exits; failing to do so can result in an infinite loop!
This makes the while
loop potentially more hazardous
compared to the for
loop and as such
should be used with caution.
Let's now see this type of loop in action, we will replicate the
for (i in 1:5)
loop from the previous lesson
using a while
loop.
In this structure, we first define a starting value with
i = 1
, which will be used to meet the condition set
in the while
loop. As the loop runs, it will print the
current value of i. However, one crucial distinction
from the for
loop is that i does not increment
automatically; we must explicitly increment it within the loop
using i = i + 1
.
You might be wondering about the practical utility of while
loops when for
loops are available. After all, from this
demonstration they are longer to write and more prone to errors.
The while
loops shine in situations where we wish to perform
iterations but the exact number of iterations required is unknown upfront.
They offer flexibility, allowing the loop to run as long as a specific
condition holds true.
Let's see such a scenario in the following example. We set a variable called coffee_beans initially to 100 and then randomly select 1, 2, or 3 and add this to coffee_beans until it reaches a threshold value of 110 while printing out the total sum at each iteration.
Feel free to run the code editor a couple of times to see
that the while
loop will end at different times due
to the randomness in the sampling.
Just like with for
loops, we can use the statements
next
and break
to skip anything past
the former and exit early with the latter.