Next →

Output:


      

Plots:

Loops in R

Loops allow you to execute a block of code multiple times, which is useful for repetitive tasks. R has three main types of loops: for, while, and repeat.

for Loop

Iterates over a sequence of values.

for (i in 1:5) {
  print(i)
}

while Loop

Repeats code as long as a condition is TRUE.

count <- 1
while (count <= 5) {
  print(count)
  count <- count + 1
}

repeat Loop

Executes code indefinitely until a break statement is encountered.

n <- 1
repeat {
  print(n)
  n <- n + 1
  if (n > 5) {
    break
  }
}

Loops are a powerful way to automate tasks and handle repeated operations efficiently.