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.
1# Calculate 10! using a while loop
2i <- 10
3f <- 1
4while(i>1) {
5 f <- i*f
6 i <- i-1
7 cat(i, f, "\n")
8}
9f
10
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:
19 10
28 90
37 720
46 5040
55 30240
64 151200
73 604800
82 1814400
91 3628800
10
Example: Repeat Loop
Let's now take a look at repeat
statement.
1repeat {
2 expressions
3 if(condition) break
4}
5
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.
1# Calculate 10! using a repeat loop
2i <- 10
3f <- 1
4repeat {
5 f <- i*f
6 i <- i-1
7 cat(i, f, "\n")
8 if(i<1) break
9}
10f
11
Notice the if
condition inside the repeat loop. The result will be exactly the same as with while
loop.
19 10
28 90
37 720
46 5040
55 30240
64 151200
73 604800
82 1814400
91 3628800
100 3628800
11
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.
1> factorial(10)
2[1] 3628800
3