Next! Even numbers divided by 2 don't equal zero


#1

Hi,

I'm a little stuck on exercise 9. I know the answer but I don't understand the code.

So it says we need to create a loop with even values up to 20, I know we need to exclude the odd values, but in order to specify what to exclude we say "next if i % 2 == 1"

However odd numbers % 2 does not equal 1, it equals a different number. So how did the reader figure that when we are talking about excluding numbers that essentially we need to add 1 to, in order to divide it by 2 to create a whole number.

code:

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

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

`


#2

@natdory

i = 20 # we create i variable with twenty as value
loop do # we make a loop
i -= 1 # we assign its new value itself minus one
next if i % 2 == 1 #if i divided by two equals one we skip to the next loop
print "#{i}" #otherwise we print i
break if i <= 0 #we stop the loop if i is smaller or equal to zero
end #we stop the loop

#3

Thanks for the reply, however my only query is regarding this: next if i % 2 == 1 #if i divided by two equals one

However odd numbers % 2 does not equal 1, it equals a different number. For example 7%2 = 3.5. So how did the reader figure that when we are talking about excluding numbers that essentially we need to add 1 to, in order to divide it by 2 to create a whole number?


#4

Hi dont forget that...

the modulo % give the remain of the division so if you do

print 7 % 2 

#Ouput

1

HOpe that could help you understand it


#5

Hey cool, got it so % is not divide is shows the remainder, thanks