# Loops and Control Statements in R

This is the fifth part of the series “R for Data Science”. The series is as follows:

After learning the use of operators and conditional statements, we will move to the loops in R.

Let us first understand what loops are:

## Loop

A loop is set of some instructions which are executed again and again until it reaches the certain condition. They are used to repeat the blocks of codes which we need to execute repeatedly.

R provides us with the following loops:

• For loop
• While loop
• Repeat loop

To control the loop structure there are control statements which are:

• Break
• Next

### For Loop

In for loop condition is given within the loop statement.

Syntax:  for (i in v)

{

#Statement;

}

Here i is variable which will takes the value of vector v each time the loop is executed. For example:

```> v<- c(1,2,4,8,9)

> sum<- 0

> for(i in v){

+     sum=sum+i;

+ }

> print(sum);

[1] 24

# We can also use it as below:

> sum<- 0

> for(i in 1:3){

+     sum=sum+i;

+ }

> print(sum);

[1] 6```

### While Loop

While loops are same as for loops but the difference is that they executed until the value of test expression becomes false.

Syntax:

while (test_expression){

#Statement;

#updation;

}

```> j=10;

> val=1;

> while(j!=0){

+   val=val*j

+   j=j-1

+ }

> print(val)

[1] 3628800```

test_expression could be any condition used in while loop. Updation can also be used (depends on the code).

### Repeat Loop

Repeat loop is used to repeat the statement(s) unconditionally. There is no certain condition inside the loop to come out of it, we have to use break statement accordingly otherwise loop will continue infinite times.

Syntax:

repeat {

#Statement;

}

```> m=1;

> repeat{

+   m=(m+1)*m;

+   if(m>20){

+     break

+   }

+ }

> print(m)

[1] 42```

## Control Statements

These are the statements which are used to control the execution of loops.

Break and next statements are used as control statements.

Break is use to come out of the loop completely and execute next line of code where as next is use to skip the current iteration and continue the loop from the next one.

For example:

```#break statement

> n=0

> repeat{

+   n=n+1

+   if(n==10){

+        break

+      }

+    }

> print(n)

[1] 10

#next statement

> j=10;

> val=1;

> while(j>0){

+   j=j-1;

+   if(j==3){

+     next

+   }

+   print(j)

+    }

[1] 9

[1] 8

[1] 7

[1] 6

[1] 5

[1] 4

[1] 2

[1] 1

[1] 0

```