How do write a down program using While Loop? Please check my program.

Well, let's read it like a computer would.

def countdown

define a method names "countdown"

number = 10

create a variable named number, and set it to 10.

while number <= 10

start a while loop - while number is less than or equal to 10 do...

   puts "#{number} SECONDS(S)!"
   number -= 1

display number variable value, and the string " Seconds(s)!" and subtract 1 from number value.

end

end method.

So let's start with your first problem, your condition on your while statement.

While number is less than or equal to 10, DO put statement, and subtract 1 from number.

Variable number starts at 10, and will subtract 1 for each pass of the while loop. So 10,9,8,7,6,5,4,3,2,1,0,-1,-2....etc

Number will always be less than or equal to 10. What does this mean? It means the loop never breaks, because the condition is always true. So how can we make the condition true at start, yet false at the point we want the loop to stop? (Hint: Greater than!)

So when do we want the loop to stop running? (When number == 0 or is > -1 or >0 depending on how you write the inside of this while loop) there are multiple ways to write the while loop so that it does what it should.

Here are some steps to guide you (PM for correct answer - will only provide if an effort was made...)

1.) set correct condition on while loop.

2.) if number is above what, would English language be correct in saying "SECONDS!"

3.) if number is what would English language be correct in saying " SECOND!"

4.) either write this portion after the while loop, or inside in an if - elsif - else statement - "HAPPY NEW YEARS!" when number = 0.

So there are a lot of different ways to write this method, but ultimately it comes down to preference with minor difference in performance speed depending on how you tell the machine to perform that task.

Someone answered and basically said this, and he is completely right, and that person is not being a dick.

/r/ruby Thread Parent