Until/While loops



I got the exercise (and the one right before this one) correct, but I fail to understand why the console only printed out the numbers till 10. Since 10 is still < 11, wouldn't it loop one last time, making the console spit out 10+1 = 11?

counter = 1
while counter < 11
  puts counter
  counter += 1


yes, 10 is less than 11, so yes, another iteration happens
and it prints 10 for that iteration, look at what your code prints


:sob: Massive brain fart.


Study the order of execution: puts, increment, puts, increment...

10 is the last value to print under the constraints.

It's interesting that you bring this up, since it is a concept around which many learners have some difficulty.

The reason is that we have two concepts overlapping, range and inequality as it pertains to looping. That we want some outputs is notwithstanding.

What if counter had no value, meaning, 0, under the same constraints:

c = 0
while c < 11
  puts c
  c += 1

The output is 0 to 10.

c = 0
while c < 11
  c += 1
  puts c

The output is 1 to 11.

I could go on but it will get boring. "Ten is less than eleven, puts eleven."


I figured out that was where my confusion stemmed from, i.e. the order of the instructions, and you just confirmed it. Thank you :smile:


Right on! You're welcome.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.