Menu
Coddy logo textTech

Break

Part of the Fundamentals section of Coddy's Ruby journey — lesson 41 of 88.

Sometimes you need to exit a loop early, before it naturally finishes. The break keyword lets you immediately stop a loop and continue with the code after it.

Imagine searching for a specific number. Once you find it, there's no point in continuing to check the rest:

for i in 1..10
  if i == 5
    puts "Found it!"
    break
  end
  puts i
end
puts "Loop ended"

This outputs 1, 2, 3, 4, then "Found it!", and finally "Loop ended". When i reaches 5, the break executes and the loop stops immediately. Numbers 6 through 10 are never processed.

The break keyword works with any type of loop. Here's an example with a while loop:

count = 0
while true
  count += 1
  if count > 3
    break
  end
  puts count
end

This outputs 1, 2, 3. Even though the condition is true (which would normally loop forever), the break stops the loop when count exceeds 3.

challenge icon

Challenge

Easy

Read two integers from input:

  1. A limit representing the upper bound of a range starting from 1
  2. A target number to search for

Loop through numbers from 1 to limit. Print each number on its own line. When you reach the target, print Found! instead of the number and immediately stop the loop using break.

If the target is within the range, the loop should stop early. If the target is greater than the limit, all numbers from 1 to the limit will be printed.

For example, if the inputs are 10 and 4, the output should be:

1
2
3
Found!

If the inputs are 5 and 8, the output should be:

1
2
3
4
5

Cheat sheet

The break keyword immediately stops a loop and continues with the code after it:

for i in 1..10
  if i == 5
    puts "Found it!"
    break
  end
  puts i
end
puts "Loop ended"

This outputs 1, 2, 3, 4, "Found it!", "Loop ended". When i reaches 5, the loop stops immediately.

The break keyword works with any type of loop, including while loops:

count = 0
while true
  count += 1
  if count > 3
    break
  end
  puts count
end

This outputs 1, 2, 3 and then stops, even though the condition is true.

Try it yourself

# Read input
limit = gets.to_i
target = gets.to_i

# TODO: Write your code below
# Loop through numbers from 1 to limit
# Print each number on its own line
# When you reach the target, print "Found!" and break out of the loop
quiz iconTest yourself

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

All lessons in Fundamentals