> For the complete documentation index, see [llms.txt](https://ar-riyaz.gitbook.io/r-for-bioinformatics/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ar-riyaz.gitbook.io/r-for-bioinformatics/basic-concepts/loops.md).

# Loops

A loop statement allows us to execute a statement or group of statements multiple times.

### There are three types of loops in R programming:&#x20;

* For Loop
* While Loop
* Repeat Loop

## <mark style="color:red;">`for`</mark> loop in R

A <mark style="color:red;">`for`</mark> loop is used to iterate over a list, vector, or any other object of elements.

{% tabs %}
{% tab title="Syntax" %}

```r
for (value in sequence) {
  # block of code
}
```

Here, <mark style="color:red;">sequence</mark> is an object of elements and <mark style="color:red;">`value`</mark> takes in each of those elements. In each iteration, the block of code is executed.
{% endtab %}

{% tab title="Example\_1" %}

```r
numbers = c(1,2,3,4,5)

# for loop to print all elements in numbers
for (x in numbers){
  print(x)
}
```

**Output:**

```r
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
```

<mark style="color:green;">**Code Breakdown:**</mark>

In this program, we have used a <mark style="color:red;">`for`</mark> loop to iterate through a sequence of numbers called <mark style="color:red;">`numbers`</mark>. In each iteration, the variable <mark style="color:red;">`x`</mark> stores the element from the sequence and the block of code is executed.
{% endtab %}

{% tab title="Example\_2" %}
**Count the Number of Even Numbers:**

Let's use a <mark style="color:red;">`for`</mark> loop to count the number of even numbers stored inside a vector of numbers.

```r
# Vector of numbers
num = c(2,3,12,14,5,19,23,64)

# variable to store the count of even numbers
count = 0

# for loop to count even numbers
for (i in num){
  # check if i is even
  if (i %% 2 == 0){
    count = count + 1
  }
}

print(count)
```

**Output:**

```r
[1] 4
```

<mark style="color:green;">**Code Breakdown:**</mark>

In this program, we have used a <mark style="color:red;">`for`</mark> loop to count the number of even numbers in the <mark style="color:red;">`num`</mark> vector. Here is how this program works:

* We first initialized the <mark style="color:red;">`count`</mark> variable to <mark style="color:red;">`0`</mark>. We use this variable to store the count of even numbers in the <mark style="color:red;">`num`</mark> vector.
* We then use a <mark style="color:red;">`for`</mark> loop to iterate through the <mark style="color:red;">`num`</mark> vector using the variable <mark style="color:red;">`i`</mark>.
* Inside the <mark style="color:red;">`for`</mark> loop, we check if each element is divisible by **2** or not. If yes, then we increment the count by **1**.
  {% endtab %}

{% tab title="Example\_3" %} <mark style="color:red;">`for`</mark> **Loop With break Statement:**

We can use the <mark style="color:red;">`break`</mark> statement to exit from the <mark style="color:red;">`for`</mark> loop in any iteration.

For example:

```r
# vector of numbers
numbers = c(2, 3, 12, 14, 5, 19, 23, 64)

# for loop with break
for (i in numbers) {
  
  # break the loop if the number is 5
  if(i == 5){
    break
  }
  
  print(i)
}
```

**Output**:

```r
[1] 2
[1] 3
[1] 12
[1] 14
```

<mark style="color:green;">**Code Breakdown:**</mark>

Here, we have used an <mark style="color:red;">`if`</mark> statement inside the <mark style="color:red;">`for`</mark> loop. If the current element is equal to <mark style="color:red;">`5`</mark>, we break the loop using the <mark style="color:red;">`break`</mark> statement. After this, no iteration will be executed.
{% endtab %}

{% tab title="Example\_4" %} <mark style="color:red;">`for`</mark> **Loop With the&#x20;**<mark style="color:red;">**`next`**</mark>**&#x20;Statement**

Instead of terminating the loop, you can skip an iteration using the <mark style="color:red;">`next`</mark> statement.

For example:

```r
# vector of numbers
numbers = c(2, 3, 12, 14, 5, 19, 23, 64)

# for loop with next
for (i in numbers) {
  
  # use next to skip odd numbers
  if(i %% 2 != 0){
    next
  }
  
  print(i)
}
```

**Output:**

```r
[1] 2
[1] 12
[1] 14
[1] 64
```

<mark style="color:green;">**Code Breakdown:**</mark>

Here, we have used an <mark style="color:red;">`if`</mark> statement inside the <mark style="color:red;">`for`</mark> loop to check for odd numbers. If the number is odd, we skip the iteration using the <mark style="color:red;">`next`</mark> statement and print only even numbers.
{% endtab %}
{% endtabs %}

## <mark style="color:red;">`while`</mark> loop in R

A <mark style="color:red;">`while`</mark> loop in R is a type of loop that executes a block of code repeatedly while a certain condition is met.

{% tabs %}
{% tab title="First Tab" %}
The basic structure of a while loop in R is as follows:

```r
while (condition) {
  # Code to be executed
}
```

In this structure, the `condition` is evaluated at the beginning of each iteration of the loop. If the condition is `TRUE`, the code inside the loop is executed, and the process is repeated. If the condition is `FALSE`, the loop terminates and control is returned to the rest of the program.
{% endtab %}

{% tab title="Example" %}
Here is a simple example of how you can use a while loop in R to count the number of positive integers less than a specified value:

```r
# Input the upper limit
limit <- 45

# Initialize the counter
count <- 0

# Start the loop
while (count < limit) {
  count <- count + 1
  print(count)
}

```

In this example, the value for the upper limit will be stored in the <mark style="color:red;">`limit`</mark> variable. The <mark style="color:red;">`count`</mark> variable is initialized to 0, and the <mark style="color:red;">`while`</mark> loop is started. The loop increments the <mark style="color:red;">`count`</mark> variable by 1 on each iteration and prints the current value of `count`. The loop continues to execute as long as <mark style="color:red;">`count`</mark> is less than <mark style="color:red;">`limit`</mark>. When `count` becomes equal to or greater than <mark style="color:red;">`limit`</mark>, the loop terminates.

{% hint style="info" %}
Note that it's important to include a way to update the condition inside the loop, otherwise, the loop will never end and will run indefinitely, which is called an infinite loop. In this example, the condition is updated on each iteration by incrementing the <mark style="color:red;">`count`</mark> variable.
{% endhint %}
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
While loops can be very useful in R, but it's important to be careful with their usage to avoid infinite loops and slow performance. Whenever possible, it's recommended to use a <mark style="color:red;">`for`</mark> loop or a <mark style="color:red;">`repeat`</mark> loop instead of a while loop, as they provide a more concise and straightforward way to handle looping in R.
{% endhint %}

### <mark style="color:red;">`while`</mark> loop with <mark style="color:red;">`break`</mark> Statement in R

A <mark style="color:red;">`break`</mark> statement can be used in a while loop to prematurely terminate the loop and exit the rest of the program.

{% tabs %}
{% tab title="Syntax" %}
The basic structure of a while loop in R with a <mark style="color:red;">`break`</mark> statement is as follows:

```r
while (condition) {
  # Code to be executed

  if (exit_condition) {
    break
  }
} 
```

In this structure, the <mark style="color:red;">`condition`</mark> is evaluated at the beginning of each iteration of the loop. If the condition is <mark style="color:red;">`TRUE`</mark>, the code inside the loop is executed. If the <mark style="color:red;">`exit_condition`</mark> is <mark style="color:red;">`TRUE`</mark>, the <mark style="color:red;">`break`</mark> statement is executed, and the loop terminates. If the <mark style="color:red;">`exit_condition`</mark> is <mark style="color:red;">`FALSE`</mark>, the loop continues.
{% endtab %}

{% tab title="Example" %}
Here is a simple example of how you can use a while loop in R with a <mark style="color:red;">`break`</mark> statement to find the first positive integer that is divisible by 3 and 5:

```r
# Initialize the counter
count <- 0

# Start the loop
while (TRUE) {
  count <- count + 1
  
  if (count %% 3 == 0 && count %% 5 == 0) {
    print(sprintf("The first positive integer divisible by 3 and 5 is %d", count))
    break
  }
}

```

In this example, the <mark style="color:red;">`count`</mark> variable is initialized to 0, and the while loop is started with a <mark style="color:red;">`condition`</mark> of `TRUE`. This means that the loop will execute indefinitely until the <mark style="color:red;">`break`</mark> statement is executed. The loop increments the <mark style="color:red;">`count`</mark> variable by 1 on each iteration, and checks if <mark style="color:red;">`count`</mark> is divisible by both 3 and 5 using the <mark style="color:red;">`%%`</mark> operator. If <mark style="color:red;">`count`</mark> is divisible by both 3 and 5, the <mark style="color:red;">`break`</mark> statement is executed, and the loop terminates. The value of <mark style="color:red;">`count`</mark> is then printed as the first positive integer that is divisible by 3 and 5.

Here, <mark style="color:red;">`sprintf`</mark> is used to create a string with the message "**The first positive integer divisible by 3 and 5 is %d**". The <mark style="color:red;">`%d`</mark> placeholder is used to represent a decimal number, which is the value of the <mark style="color:red;">`count`</mark> variable. The <mark style="color:red;">`sprintf`</mark> function returns the formatted string, which is then passed as an argument to the <mark style="color:red;">`print`</mark> function to be displayed on the console.
{% endtab %}
{% endtabs %}

### <mark style="color:red;">`while`</mark> loop with <mark style="color:red;">`next`</mark> Statement in R

Here's an example of a `while` loop in R that uses the `next` statement:

```r
# Initialize a counter
i <- 1

# Start the while loop
while (i <= 10) {
  # Check if the current value of i is odd
  if (i %% 2 != 0) {
    # If i is odd, go to the next iteration of the loop
    i <- i + 1
    next
  }
  
  # If i is even, print its value
  print(i)
  
  # Increment the counter
  i <- i + 1
}

```

In this example, the <mark style="color:red;">`while`</mark> loop will run as long as <mark style="color:red;">`i`</mark> is less than or equal to 10. At each iteration of the loop, the current value of <mark style="color:red;">`i`</mark> is checked to see if it is odd. If `i` is odd, the <mark style="color:red;">`next`</mark> statement is executed, which causes the loop to go to the next iteration without executing the rest of the loop body. If <mark style="color:red;">`i`</mark> is even, its value is printed to the console. The counter <mark style="color:red;">`i`</mark> is incremented at the end of each iteration, which eventually causes the loop to terminate when <mark style="color:red;">`i`</mark> becomes greater than 10.

**Output:**

```r
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
```

## <mark style="color:red;">`repeat`</mark> loop in R

We use the R <mark style="color:red;">`repeat`</mark> loop to execute a code block multiple times.

* However, the repeat loop doesn't have any condition to terminate the loop.
* You need to put an <mark style="color:blue;">**exit condition**</mark> implicitly with a <mark style="color:red;">`break`</mark> statement inside the loop.

{% tabs %}
{% tab title="Syntax" %}

```r
repeat {
      # statements
      if(stop_condition) {
          break
      }
  }
```

Here, we have used the <mark style="color:red;">`repeat`</mark> keyword to create a <mark style="color:red;">`repeat`</mark> loop. It is different from the <mark style="color:red;">`for`</mark> and <mark style="color:red;">`while`</mark> loop because <mark style="color:blue;">**it does not use a predefined condition**</mark> to **exit** from the loop.
{% endtab %}

{% tab title="Example\_1" %}
Let's see an example that will print numbers using a <mark style="color:red;">`repeat`</mark> loop and will execute until the <mark style="color:red;">`break`</mark> statement is executed.

```r
x = 5

# Repeat loop
repeat {
  
  print(x)
  
  # Break statement to terminate if x > 40
  if (x > 40) {
    break
  } 
  
  # Increment x by 10
  x = x + 10
  
}
```

**Output:**

```r
[1] 5
[1] 15
[1] 25
[1] 35
[1] 45
```

Here, we have used a `repeat` loop to print numbers from <mark style="color:red;">`5`</mark> to <mark style="color:red;">`45`</mark>. We have used an <mark style="color:red;">`if`</mark> statement to provide a breaking condition that breaks the loop if the value of `x` is greater than <mark style="color:red;">`40`</mark>.
{% endtab %}

{% tab title="Example\_2" %}
**Infinite repeat Loop**

If you fail to put a <mark style="color:red;">`break`</mark> statement inside a <mark style="color:red;">`repeat`</mark> loop, it will lead to an infinite loop. For example:

```r
x = 1
sum = 0

# Repeat loop
repeat {
  
  # Calculate sum
  sum = sum + x
  
  # Print sum
  print(sum)
  
  # Increment x by 1
  x = x + 1
  
}
```

**Output:**

```
[1] 1
[1] 3
[1] 6
[1] 10
.
.
.
```

In the above program, **since** **we have not included** any <mark style="color:red;">`break`</mark> statement with an exit condition, the program prints the sum of numbers infinitely.
{% endtab %}

{% tab title="Example\_3" %}
**`repeat` Loop with `next` Statement**

You can also use a <mark style="color:red;">`next`</mark> statement inside a <mark style="color:red;">`repeat`</mark> loop to skip an iteration.

For example:

```r
x = 1

repeat {
  # Break if x = 5
  if (x == 5) {
    break
  }
  
  # Skip if x == 2
  if (x == 2) {
    # Increment x by 1 and skip
    x = x + 1
    next
  }
  
  # Print x and increment x by 1
  print(x)
  x = x + 1
}
```

**Output:**

```r
[1] 1
[1] 3
[1] 4
```

Here, we have a <mark style="color:red;">`repeat`</mark> loop where we break the loop if <mark style="color:red;">`x`</mark> is equal to <mark style="color:red;">`5`</mark>. We skip the iteration where <mark style="color:red;">`x`</mark> becomes equal to <mark style="color:red;">`2`</mark>.
{% endtab %}
{% endtabs %}

## Sources:

Sources of contents on this page:

1. [R for Loop | Programiz](https://www.programiz.com/r/for-loop)
2. [R while Loop | Programiz](https://www.programiz.com/r/while-loop)
3. [R repeat Loop | Programiz](https://www.programiz.com/r/repeat-loop)
