Break
Part of the Fundamentals section of Coddy's R journey — lesson 40 of 78.
Sometimes you need to exit a loop early, before it finishes all its iterations. The break statement lets you immediately stop a loop when a specific condition is met.
for (i in 1:10) {
if (i == 5) {
break
}
print(i)
}Output:
[1] 1
[1] 2
[1] 3
[1] 4The loop was set to run from 1 to 10, but when i reached 5, the break statement stopped the loop entirely. Notice that 5 was never printed because break exits immediately.
This is especially useful with while loops when searching for something:
num <- 1
while (TRUE) {
if (num * num > 20) {
break
}
num <- num + 1
}
print(num)Output:
[1] 5Here, while (TRUE) would normally run forever, but break stops it once we find the first number whose square exceeds 20. This pattern is common when you need to search until a condition is satisfied.
Challenge
EasyRead a number limit from input. Use a for loop to iterate from 1 to limit, but stop the loop early using break when you encounter the first number that is divisible by both 3 and 7.
Print each number before checking the condition. When you find a number divisible by both 3 and 7, print that number, then break out of the loop.
After the loop ends, print "Loop ended" using print().
For example, if the input is 30, the output should be:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
[1] 11
[1] 12
[1] 13
[1] 14
[1] 15
[1] 16
[1] 17
[1] 18
[1] 19
[1] 20
[1] 21
[1] "Loop ended"The loop stops at 21 because it's the first number divisible by both 3 and 7 (21 = 3 × 7).
Cheat sheet
The break statement immediately stops a loop when a specific condition is met:
for (i in 1:10) {
if (i == 5) {
break
}
print(i)
}Output:
[1] 1
[1] 2
[1] 3
[1] 4The loop exits when i reaches 5. The value 5 is never printed because break exits immediately.
Using break with while (TRUE) for searching:
num <- 1
while (TRUE) {
if (num * num > 20) {
break
}
num <- num + 1
}
print(num)Output:
[1] 5This pattern finds the first number whose square exceeds 20, then stops the infinite loop.
Try it yourself
# Read input
con <- file("stdin", "r")
limit <- as.integer(suppressWarnings(readLines(con, n = 1)))
# TODO: Write your code below
# Use a for loop from 1 to limit
# Print each number before checking the condition
# Break when you find a number divisible by both 3 and 7
# Hint: Use %% operator to check divisibility
# Print "Loop ended" after the loop
print("Loop ended")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values