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

···

--
Posted via http://www.ruby-forum.com/.

Please do your own homework

···

On Feb 6, 2012, at 11:01, Viera Tarcova <faithfromslovakia@gmail.com> 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?
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

--
Posted via http://www.ruby-forum.com/\.

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

···

On Mon, Feb 6, 2012 at 14:01, Viera Tarcova <faithfromslovakia@gmail.com> 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?

--
Dave Aronson: Available Cleared Ruby on Rails Freelancer
(NoVa/DC/Remote) -- see www.DaveAronson.com, and blogs at
www.Codosaur.us, www.Dare2XL.com, www.RecruitingRants.com

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.

···

--
Posted via http://www.ruby-forum.com/.

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

···

--
Posted via http://www.ruby-forum.com/.

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)?

···

--
Posted via http://www.ruby-forum.com/.