Loops and iterators


#1

how come my code isn't working
i = 20
loop do
i -= 1

next if i % 2 == 1
print "#{i} "
break if i <= 0
end

every single time I write this it just returns "Oops, try again. It looks like your loop doesn't print out the numbers 18 to 0."


#2

First, just look at your output and you will get it:

18 16 14 12 10 8 6 4 2 0

You are excluding all the odd values.

Even if you could not see your code output, you could try going through your code and playing computer. That is, write down the initial value of i and then go through the loop changing the value and walking through each step.

i: initially 20.
Loop starts: i decremented to 19.
19 % 2 is 1, so it skips to the next iteration
i decremented to 18
18 % 2 is 0
print 18
Next iteration because i is still > 0
i decremented to 17
17 % 2 is 1, so it skips to the next iteration
i decremented to 16
16 % 2 is 0
print 16
Next iteration because i is still > 0
etc