0
0
R Programmingprogramming~5 mins

Repeat loop with break in R Programming

Choose your learning style9 modes available
Introduction

A repeat loop runs code over and over until you tell it to stop. You use break to stop the loop when you want.

When you want to keep asking a user for input until they give a valid answer.
When you want to repeat a task until a certain condition happens, like reaching a target number.
When you don't know how many times you need to repeat, but you want to stop based on a condition inside the loop.
Syntax
R Programming
repeat {
  # code to repeat
  if (condition) {
    break
  }
}

The repeat loop runs forever unless you use break inside it.

You check a condition inside the loop and use break to stop repeating.

Examples
This loop prints numbers from 1 to 5 and stops when count reaches 5.
R Programming
count <- 1
repeat {
  print(count)
  if (count == 5) {
    break
  }
  count <- count + 1
}
This loop asks the user to type something and stops only when they type 'stop'.
R Programming
repeat {
  answer <- readline(prompt = "Type 'stop' to end: ")
  if (answer == "stop") {
    break
  }
  print(paste("You typed:", answer))
}
Sample Program

This program counts from 1 to 3, printing each number, then stops the loop.

R Programming
count <- 1
repeat {
  print(paste("Count is", count))
  if (count >= 3) {
    break
  }
  count <- count + 1
}
OutputSuccess
Important Notes

Always make sure your repeat loop has a break condition, or it will run forever.

You can use break anywhere inside the loop to stop it immediately.

Summary

repeat loops run code repeatedly until break stops them.

Use break inside the loop to stop when a condition is met.

This is useful when you don't know how many times you need to repeat in advance.