Loops and Iterators: Next!


#1

The question is to change a loop to read out only the odd numbers from 18 through 0. It gives me

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

saying that this will print out even numbers, since the modulo would only give a 0 if the number is even - 'cause an even number divided by two should be even as well. It says to modify it to print out odd numbers, so I modified it to print if modulo gives an answer above 0 - that would be an odd number.

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

So I enter this in and hit submit.

Oops indeed. And what's really troubling is that the original doesn't even print out the even numbers like it says it will. It comes out looking like this:

18..0

Am I missing something?


#2

It's a bit trickier to pass the lesson with a for statement. The lesson provides us with starting code:

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

The instructions are,

Add a line to your loop before your print statement. Use the next keyword so that you skip to the next iteration if the number i is odd.

So, all we really need do for this exercise is insert one line of code:

  next if i % 2 != 0

as instructed.


#3

i bitterly copied and pasted you statement and no
that doesn't work


#4

i didnt want to either but you have to copy and paste it. the != is where i needed to correct myself


#5

i tried the same, i mean what you just said but it doesnt really work. It asks me check for some infinite loops and try again.But i dont find any infinite loops in my code.Please check.Here is my code.

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


#6

next if i % 2 != 0

That should be an i not a 1.


#7

The code needs to look like this:

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


#8

it worked for me when I copied and pasted it.:slightly_smiling:


#9

When I use that, it gives me "It looks like your loop doesn't print out numbers 18 to 0.


#10

hello to me I run my code this way

i = 20
loop do
i -= 1
next if i%2==1
print i

break if i <= 0
end