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

limit
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}"
  1. limit ← 4, number ← 1, total ← 0

    1limit→ 4 = 4  #@limit=2, 62number→ 1 = 13total→ 0 = 0
  2. total ← 1, number ← 2

    pass 1 of 4
    5while number1 <= limit46  total→ 1 += number17  number→ 2 += 18end
    All 4 passes — pass 1 is the card above
    passtotalnumber
    10 11 2
    21 32 3
    33 63 4
    46 104 5
  3. puts "limit=#{limit}"

    10puts "limit=#{limit4}"11puts "total=#{total10}"
    outputlimit=4
    total=10
  1. limit ← 2, number ← 1, total ← 0

    1limit→ 2 = 22number→ 1 = 13total→ 0 = 0
  2. total ← 1, number ← 2

    pass 1 of 2
    5while number1 <= limit26  total→ 1 += number17  number→ 2 += 18end
  3. total ← 3, number ← 3

    pass 2 of 2
    5while number2 <= limit26  total→ 3 += number27  number→ 3 += 18end
  4. puts "limit=#{limit}"

    10puts "limit=#{limit2}"11puts "total=#{total3}"
    outputlimit=2
    total=3
  1. limit ← 6, number ← 1, total ← 0

    1limit→ 6 = 62number→ 1 = 13total→ 0 = 0
  2. total ← 1, number ← 2

    pass 1 of 6
    5while number1 <= limit66  total→ 1 += number17  number→ 2 += 18end
    All 6 passes — pass 1 is the card above
    passtotalnumber
    10 11 2
    21 32 3
    33 63 4
    46 104 5
    510 155 6
    615 216 7
  3. puts "limit=#{limit}"

    10puts "limit=#{limit6}"11puts "total=#{total21}"
    outputlimit=6
    total=21

Add Up to the Limit

  1. limit starts at 4.
  2. number starts at 1.
  3. The loop adds number while it is at most limit.
  4. Each pass increases number by 1.
  5. 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