R While Loop

R While Loop

Loops can heavily automate repetitive tasks, saving you hours of tedious manual coding.

The while loop executes a block of code continuously as long as a specified condition remains TRUE.


The while Syntax

You start by initializing a counter variable outside the loop.

Inside the loop's curly braces, you perform the action and increment the counter.

If you completely forget to increment the counter, the loop will run forever and crash the application!

While Loop Example:

i <- 1

while (i < 6) { print(i) i <- i + 1 # Crucial: Incrementing the counter! }


The break Statement

Sometimes you need to securely exit a loop immediately, even if the condition is still true.

Using the break statement will instantly terminate the loop and jump to the next block of code!


The next Statement

Conversely, the next statement allows you to selectively skip a single iteration.

When triggered, the loop ignores the current step and instantly jumps back to the top for the next check!


Exercise 1 of 2

?

What happens if you fail to increment your counter variable inside a while loop?

Exercise 2 of 2

?

Which statement is used to completely terminate a loop prematurely?