Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 8 / 68

Repeating (the while loop)

This lesson covers looping in R with a while statement, with the aim of choosing correctly between it and a for loop.

A while statement repeats for as long as its condition holds. The basic rule of thumb: a for loop when you already know the finishing condition, a while loop when you do not.

The sample code initialises with i <- 1, repeats while i <= 5, and increases the value by one inside the loop with i <- i + 1. You can watch it leave the loop the moment the condition becomes false.

A common early stumble is forgetting to update the variable the condition depends on. Leave that out and you have an infinite loop.

In professional work, while loops are used where the number of repetitions is not known in advance — repeating until some condition is met.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)