FOR Loop:
For loop is used to iterate over a vector and its condition is tested at the end of the body of loop.
Syntax:
For (val in iter) {
Statement;
}
Here “iter” is a vector and “var” takes one element of “iter” every time the loop gets executed till all element of the vector are picked up in multiple iteration of the same cycle.
Example:
> x <- c(2:6)
> x
[1] 2 3 4 5 6
> total <- 0
> for (val in x) {
+ if (val > 3) total = total + 7
+ }
> print(total)
[1] 21
While Loop:
While loop is used to keep iterate over a vector immediately after its condition is satisfied.
Syntax:
While (expression) {
Statement
}
Example:
> i <- 30
> while(i <=40) {
+ i <- i+1
+ print(i)
+ }
[1] 31
[1] 32
[1] 33
[1] 34
[1] 35
[1] 36
[1] 37
[1] 38
[1] 39
[1] 40
[1] 41
Repeat Loop:
Repeat loop keep on executing same block of code in iteration. Explicit condition inside the repeat loop needs to be put for exiting the loop or else the loop will go to infinite loop.
Syntax:
Repeat {
Statement
}
Example:
> num <- 2
> repeat {
+ print(num)
+ num = num + 2
+ if ( num == 12 ){
+ break
+ }
+ }
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
- Break statement is used to terminate the loop abruptly.
- In case you just need to terminate the current iteration in place of the whole loop use Next statement.
>num <- 5:10
>for (value in num){
+ if (value ==8 ){
+ next
+ }
+ print(value)
+ }
[1] 5
[1] 6
[1] 7
[1] 9
[1] 10