Menu
Coddy logo textTech

repeat and break

Part of the Logic & Flow section of Coddy's R journey. Lesson 49 of 64.

repeat runs its body again and again until a break inside it stops the loop. It fits a loop whose exit condition is only known in the middle of the body:

n <- 1
repeat {
  n <- n * 2
  if (n > 50) break
}
print(n)

Output:

[1] 64

The Collatz sequence is an example: halve even numbers, turn odd ones into 3n + 1, and stop at 1. The number of steps is not known in advance:

n <- 6
steps <- 0
repeat {
  if (n == 1) break
  n <- if (n %% 2 == 0) n / 2 else 3 * n + 1
  steps <- steps + 1
}
print(steps)

Output:

[1] 8

next skips the rest of the current iteration and starts the next one. It works in repeat, while and for loops:

for (x in 1:8) {
  if (x %% 3 == 0) next
  cat(x, "")
}
cat("\n")

Output:

1 2 4 5 7 8 

A repeat loop without a reachable break never ends. Keep a counter as a safety limit when the exit depends on the data:

total <- 0
tries <- 0
repeat {
  tries <- tries + 1
  total <- total + tries
  if (total >= 20 || tries == 100) break
}
print(c(tries, total))

Output:

[1]  6 21
challenge icon

Challenge

Easy

Complete digital_root(n). Replace n by the sum of its digits until one digit is left, and return <result> after <steps> steps: 9875 gives 2 after 3 steps (9875, 29, 11, 2). A number that already has one digit takes 0 steps.

sum(as.numeric(strsplit(as.character(n), "")[[1]])) adds the digits of n.

The supplied code reads n and prints the returned value.

Try it yourself

digital_root <- function(n) {
  # Write your code here
  ""
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(digital_root(as.numeric(input[1])), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler