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
endThis 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
EasyRead 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!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 the exact text from the instructionsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or FalsePractice on your own: Online Ruby compiler