Valid XHTML 1.0! Valid CSS!

While loops

Now that you are familiar with conditions, it's time to look at another kind of loop: The while loop.

This type of loop is much more powerful than the one you've seen already. But it requires understanding conditionals. It's basic for is:

while cond
   ...
end

Where cond is a condition like the ones you saw in the last chapter.

Counting

Here is a simple example:

Let's go through this program:

  1. Set count to 0
  2. Since count < 10 we go into the loop.
  3. Inside the loop we print a message and add 1 to count. Now count is 1.
  4. Since count< 10 again we go for another loop.
  5. ...

This continues on until count is 10. So the output of this loop is:

In other words, a while loop will continue repeating the loop while the condition is true. Hence the name while.

Powers of 2

There are some things are easy to do with a while loop, but very difficult with a 'n.times'.

Suppose that we want to know the highest power of 2 which is less than 1000. This is easy with a while loop:

Think about how difficult this would be using 'n.times'.

Exercises

  1. Rewrite this last program so that the computer asks for the maximum number and the program computes the corresponding power of two.

  2. Run the program above, and type 1e10 as input. What happens?

    If you used the String#to_i method, chances are that "1e10" was converted to 1. Let's go to irb to try this out.

    You see, 1e10 is a Float. Thus, you have to use String#to_f instead.