Control Flow
While Loops
A while loop repeats while a condition stays true.
while loop
A `while` loop checks its condition before every pass through the loop body.
While Loops
while_loop.rb
Replay: real traced execution (multi-file project)
limit = 4
number = 1
total = 0
while number <= limit
total += number
number += 1
end
puts "limit=#{limit}"
puts "total=#{total}"
limit = 2
number = 1
total = 0
while number <= limit
total += number
number += 1
end
puts "limit=#{limit}"
puts "total=#{total}"
limit = 6
number = 1
total = 0
while number <= limit
total += number
number += 1
end
puts "limit=#{limit}"
puts "total=#{total}"
limit ← 4, number ← 1, total ← 0
1limit→ 4 = 4 #@limit=2, 62number→ 1 = 13total→ 0 = 0total ← 1, number ← 2
pass 1 of 45while number1 <= limit46 total→ 1 += number17 number→ 2 += 18endAll 4 passes — pass 1 is the card above pass totalnumber1 0 → 1 1 → 2 2 1 → 3 2 → 3 3 3 → 6 3 → 4 4 6 → 10 4 → 5 puts "limit=#{limit}"
10puts "limit=#{limit4}"11puts "total=#{total10}"outputlimit=4 total=10
limit ← 2, number ← 1, total ← 0
1limit→ 2 = 22number→ 1 = 13total→ 0 = 0total ← 1, number ← 2
pass 1 of 25while number1 <= limit26 total→ 1 += number17 number→ 2 += 18endtotal ← 3, number ← 3
pass 2 of 25while number2 <= limit26 total→ 3 += number27 number→ 3 += 18endputs "limit=#{limit}"
10puts "limit=#{limit2}"11puts "total=#{total3}"outputlimit=2 total=3
limit ← 6, number ← 1, total ← 0
1limit→ 6 = 62number→ 1 = 13total→ 0 = 0total ← 1, number ← 2
pass 1 of 65while number1 <= limit66 total→ 1 += number17 number→ 2 += 18endAll 6 passes — pass 1 is the card above pass totalnumber1 0 → 1 1 → 2 2 1 → 3 2 → 3 3 3 → 6 3 → 4 4 6 → 10 4 → 5 5 10 → 15 5 → 6 6 15 → 21 6 → 7 puts "limit=#{limit}"
10puts "limit=#{limit6}"11puts "total=#{total21}"outputlimit=6 total=21
Add Up to the Limit
limitstarts at4.numberstarts at1.- The loop adds
numberwhile it is at mostlimit. - Each pass increases
numberby1. - The total becomes
10. | Number | Running total | | --- | --- | |1|1| |2|3| |3|6| |4|10|
Exercise: while_loop.rb
Use a while loop to add numbers from 1 through a limit and print the total