While and Repeat Loop in R Programming

The general format of the while statement is:

while (condition) {

Note that a while loop may never execute the statement. The statement is executed repeatedly until condition becomes false.

In contrast, a repeat loop has the general format as below:

repeat {

repeat statement will execute at least once, and continue until it is explicitly interrupted with a break statement. In fact, break will immediately exit from any loop structure.

Unlike for loop which iterates over a vector list, for using while loop you need to have an indicator variable i and change its value within each iteration. Otherwise you will have an infinite loop.

Example: While Loop

The following example shows how to calculate factorial of 10 using the while loop.

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.