Menu
Coddy logo textTech

While Loop

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

The for loop works great when you know exactly how many times to repeat. But what if you want to keep looping until a certain condition changes? That's where the while loop comes in.

A while loop continues running as long as its condition remains true:

count = 1
while count <= 3
  puts count
  count += 1
end

This outputs 1, 2, and 3. The loop checks the condition before each iteration. Once count becomes 4, the condition count <= 3 is false, and the loop stops.

The key difference from a for loop is that you control when the loop ends by changing a variable inside the loop. If you forget to update the variable, the loop runs forever! Here's a countdown example:

num = 5
while num > 0
  puts num
  num -= 1
end
puts "Done!"

This counts down from 5 to 1, then prints "Done!" after the loop finishes. The while loop is especially useful when you don't know in advance how many iterations you'll need.

challenge icon

Challenge

Easy

Read a number n from input. Use a while loop to print all numbers from n down to 1, each on its own line. After the countdown finishes, print Blastoff! on a new line.

The input will be a single integer representing the starting number for the countdown.

For example, if the input is 5, the output should be:

5
4
3
2
1
Blastoff!

Cheat sheet

A while loop continues running as long as its condition remains true:

count = 1
while count <= 3
  puts count
  count += 1
end

The loop checks the condition before each iteration. You must update the variable inside the loop to eventually make the condition false, otherwise the loop runs forever.

Example countdown:

num = 5
while num > 0
  puts num
  num -= 1
end
puts "Done!"

Use while loops when you don't know in advance how many iterations you'll need, or when you want to loop until a condition changes.

Try it yourself

# Read the starting number
n = gets.chomp.to_i

# TODO: Write your code below
# Use a while loop to print numbers from n down to 1
# Then print "Blastoff!"
quiz iconTest yourself

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

All lessons in Fundamentals