# While and Repeat Loop in R Programming

The general format of the while statement is:

while (condition) {
statement
}


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 {
print('test')
}


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.

# Calculate 10! using a while loop
i <- 10
f <- 1
while(i>1) {
f <- i*f
i <- i-1
cat(i, f, "\n")
}
f


We start with an iterator i with a value of 10. Then each time the while loop iterates, we reduce the value of i by 1. Finally, once i becomes equal to 1, the while loop ends.

The cat() function is used to concatenate values of different variables and strings. It takes the arguments, converts them into strings and then concatenates them. In our example, cat(i, f, "\n"), it takes three things - i, f and '\n'' - and prints the results - the value of i, f and then a new line break.

The results are shown below:

9 10
8 90
7 720
6 5040
5 30240
4 151200
3 604800
2 1814400
1 3628800


### Example: Repeat Loop

Let's now take a look at repeat statement.

repeat {
expressions
if(condition) break
}


The repeat loop does not contain a limit. Therefore it is necessary to include an if statement with the break command to make sure you do not have an infinite loop.

The following code shows how to calculate factorial of 10 using repeat statement.

# Calculate 10! using a repeat loop
i <- 10
f <- 1
repeat {
f <- i*f
i <- i-1
cat(i, f, "\n")
if(i<1) break
}
f


Notice the if condition inside the repeat loop. The result will be exactly the same as with while loop.

9 10
8 90
7 720
6 5040
5 30240
4 151200
3 604800
2 1814400
1 3628800
0 3628800


In the above examples we used while and repeat loops to calculate the factorial of a number. However, R also has a function that we can use to calculate the factorial. We will learn more math and statistical functions as we go along.

> factorial(10)
 3628800  