Easy loop question

Hello guys, this loop makes all the even numbers being divided by two
and odd numbers multiplied by three plus one.
But how would you make the loop stop when it gets to number one?
Thank you

def f n # this function calculates next number in your sequence
if n % 2 == 0 # n is even
return n / 2
else
return n * 3+1
end
end

num = gets.to_i # read in a number
while true # infinitely…
num = f(num) # find the next number
puts num # print it
sleep 1 # wait one second
end

Please do your own homework

On Mon, Feb 6, 2012 at 14:01, Viera Tarcova
[email protected] wrote:

Hello guys, this loop makes all the even numbers being divided by two
and odd numbers multiplied by three plus one.
But how would you make the loop stop when it gets to number one?

Ask yourself, why is it going forever? Change the code that makes it
go forever, to make it go until the number is one.

-Dave

Yes, I have done it now. Now I just need to make it count all the
numbers that appear on the screen until it reaches number 1 and stops.

I am not lazy… I am just incapable. I always try to spend a lot of
time with it first and when I am desperate, then I ask others. I love to
learn new things.

Yes, this is the easiest way to do it:

def f n # this function calculates next number in your sequence
if n % 2 == 0 # n is even
return n / 2
else
return n * 3+1
end
end

num = gets.to_i # read in a number
while num < 1 # infinitely…
num = f(num) # find the next number
puts num # print it
sleep 1 # wait one second
end

Does anyone know how you can make it count all the numbers in the loop
(until it reaches number 1)?

print "Give me an integer number: "
num = gets.to_i # read in a number
while num != 1
num = num % 2 == 0 ? num / 2 : num * 3 + 1
puts num # print it
sleep 1 # wait one second
end