Loops & Iterators Next


#1


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

I am trying to create a loop that skips odd numbers and prints the even.
This is my code:-
for i in 0..18
next if i % 2 > 0
print i
end

Which gives "0246810121416180..18" as the output but I get an error message:-"Oops, try again. It looks like your loop doesn't print out the numbers 18 to 0."

Can anyone help?

Thanks
Chris

for i in 0..18
  next if i % 2 > 0
  print i
end


#2

I'd avoid using a for loop right here.

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

Using a range in your for loop causes the output to 'count up'. The lesson wants you to count down.


#3

Great, thanks flight_dragons,
I hadn't realised that it wanted to count down, should have guessed from the error message!!
That all makes sense, I just to to get a better understanding of %.


#4

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