2 / 2 = 0 ? "Next!"


#1



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


There is a mistake in this exercice description :
It's written "/" instead of "%", and we didn't even learn what is "%".

So it says :
"If the remainder of i / 2 is zero, we go to the next iteration of the loop.
Then we print the value of i. This line only prints out 1, 3, and 5 because of the previous line."

This got me very confuse.

for i in 1..5
  next if i % 2 == 0
  print i
end


#2

Hi,

It's not a mistake – and the course does briefly go over % at the beginning.

% is called modulo. It basically gives you the remainder of a division:

e.g.

  • 20 % 2 = 0 ---> Because 20 / 2 = 10. 2 goes 10 times in 20, remains 0.

  • 6 % 2 = 0 ---> Because 6 / 2 = 3. 2 goes 3 times in 6, remains 0.

  • 15 % 4 = 3 ---> Because 4 goes 3 times in 15 (to reach 12), remains 3 (15 - 12 = 3).
    How I quickly work this out is
    15 % 4 = ?
    4 x 1 = 4
    4 x 2 = 8
    4 x 3 = 12
    4 x 4 = 16 (you went above 15, therefore 4 x 3 is your only choice)
    Now that you know 4 goes 3 times in 15 (=12), your remainder (%) is 3 ! 15 - 12 = 3.

I hope this is clear, it makes sense in my head, but other people might have other math techniques to get this done.
Find the one that makes sense to you and modulo will become super easy.

Now to go back to what confuses you.

"If the remainder of i / 2 is zero we go to the next iteration of the loop.
Then we print the value of i. This line only prints out 1, 3, and 5 because of the previous line."

for i in 1..5
next if i % 2 == 0
print i
end

You count i in 1 2 3 4 5 (so at some point i is gonna be 1, then 2, then 3, then 4, then 5)
IF at some point i % 2 == 0, you skip this line, you don't print it
IN 1, 2, 3, 4, 5

2 % 2 == 0 (so you skip this line)
4 % 2 == 0 (so you skip this line)

So you end up with 1, 3 and 5.

I really hope this makes sense to you, it's my first attempt at teaching/explaining.
Feel free to get back with more questions if this didn't make enough sense.


#3

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