Until/While loops


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-XYcN1/0/4?curriculum_id=5059f8619189a5000201fbcb


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
end


#2

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


#3

:sob: Massive brain fart.


#4

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
end

The output is 0 to 10.

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

The output is 1 to 11.

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


#5

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:


#6

Right on! You're welcome.


#7

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