   # Going Loopy

You'll be pleased to hear there are NO BITS at all in this lesson! We're taking a detour via loops, which are useful for repeating things things things things things things things.

Sorry, that keeps happening, I must have had too many pills again. Anyway, now you're here, I can tell you there are three types of loops. They all work in very similar ways, and although they look a bit different, the way they work is nearly identical. The first type is called a `while` loop.

 ``` class Hello { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("Hello, world!"); i++; } System.out.println("Goodbye!"); } } ```

First we'll see what the program does, and then I'll try to explain it.

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Hello, world! Hello, world! Hello, world! Hello, world! Hello, world! Goodbye! [nurmes]btg: ```

The program prints out the message five times. Try changing `i < 5` to `i < 3` and it will be printed only three times.

So what does a `while` loop do? Well, as the name suggests, it forms a loop in the program - in other words it goes back and does the same thing more than once. In this case "the same thing" is printing a message. Every program we have seen up to now has run from top to bottom once and that was it. This program repeats the part which prints the message.

Before I explain exactly how it works, we are going to change the program slightly:

 ``` class Hello { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("i = " + i); i++; } System.out.println("Goodbye!"); } } ```

Now it says:

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: ```

So let me explain. In general terms, a `while` loop consists of the keyword `while`, followed by some `( )` brackets containing a `boolean` expression, followed by a block of statements.

Can you remember what a `boolean` expression is? It's what we called a "true or false question" earlier. It could be as simple as `true` or it could be `x == 2` (since this is either true or false). It couldn't be `x * 2` as this expression will give a number and not a true or false value. In our example the `boolean` expression is `i < 5`.

Can you also remember what a block is? Technically it is zero or more statements between a pair of curly `{ }` braces. Each `while` statement must have a `boolean` expression and a block following it. I'll highlight the block belonging to our `while` statement in blue for you.

 ``` class Hello { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("i = " + i); i++; } System.out.println("Goodbye!"); } } ```

Now what happens when we reach a `while` statement in our program? Well, the `boolean` expression is evaluated. Then, if it is true, the code in the block is executed. Then the expression is evaluated again, and once again if it is true we execute the code in the block. But as soon as the expression evaluates to false, we skip over the `while` loop and its block, on to the code following it in the program.

So in our example, first the condition (the `boolean` expression) is evaluated with i=0 and found to be true. Then the block (also called the body of the loop) is executed, so we print the current value of `i` (which is 0) and add one to it. Next the condition is evaluated with i=1, and so on. The last time through the loop we print `i = 4` and add one to make the new value of `i` five. Then the condition is evaluated again, but it is false. So we execute the last line (saying goodbye).

If all that is too long-winded for you, basically a `while` loop runs a block of code while a condition is true. Let's play around with it:

 ``` class Hello { public static void main(String[] args) { int i = 0; while (i < 0) { System.out.println("i = " + i); i++; } System.out.println("Goodbye!"); } } ```

Remember that I just said that the first thing we do here is evaluate the condition, before running the loop body. The condition will be false right away, can you work out what will happen?

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Goodbye! [nurmes]btg: ```

The body of the loop is never executed, because the condition is evaluated first of all. You're probably wondering why I pointed that out. Well now we'll look at a different type of loop, and you should see.

 ``` class Hello { public static void main(String[] args) { int i = 0; do { System.out.println("i = " + i); i++; } while (i < 5); System.out.println("Goodbye!"); } } ```

This is known as a do...while loop. Notice the semicolon at the end of the line with the `while` on it.

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: ```

It all seems to be the same so far. There is one crucial difference with this type, which is that the loop is run once, before the condition is evaluated. This is why the condition is written at the end instead of the beginning.

 ``` class Hello { public static void main(String[] args) { int i = 0; do { System.out.println("i = " + i); i++; } while (i < 0); System.out.println("Goodbye!"); } } ```

So even if the condition is always false, the loop body runs once:

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 Goodbye! [nurmes]btg: ```

That's the only difference, except don't forget the semicolon after the `while`. Now for the last type of loop. You might notice that our very first example had a line to set the loop counter (`int i = 0;`) and a line to add one to it (`i++;`). This is very common when you're counting from some number to some other number. In fact it's so common there is a special type of loop for it:

 ``` class Hello { public static void main(String[] args) { for(int i = 0; i < 5; i++) { System.out.println("i = " + i); } System.out.println("Goodbye!"); } } ```

This is called a for loop. Notice that there's only one line inside the loop body this time, as the `i++` has found its way to the top. This is exactly equivalent to the `while` loop we saw to start with:

 ``` class Hello { public static void main(String[] args) { for(int i = 0; i < 5; i++) { System.out.println("i = " + i); } System.out.println("Goodbye!"); } } ``` ``` class Hello { public static void main(String[] args) { int i = 0; while(i < 5) { System.out.println("i = " + i); i++; } System.out.println("Goodbye!"); } } ```

Do you like the pretty colours? Let's remind ourselves what these programs do.

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: ```

Because any `for` loop is equivalent to a `while` loop, we can also write a `for` loop which never executes the loop body:

 ``` class Hello { public static void main(String[] args) { for(int i = 0; i < 0; i++) { System.out.println("i = " + i); } System.out.println("Goodbye!"); } } ``` ``` class Hello { public static void main(String[] args) { int i = 0; while(i < 0) { System.out.println("i = " + i); i++; } System.out.println("Goodbye!"); } } ```

They both do the same thing (we've seen the version with the `while` loop before).

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Goodbye! [nurmes]btg: ```

And that's the three types of loops. Simple, but very useful. Now we're going to learn about how to `break` and `continue`. These can be used with any type of loop, but we'll use a `for` loop to demonstrate. If you can understand what these two do, and when to use each one, you'll be ready for anything when it comes to writing your own loopy programs!

 ``` class Hello { public static void main(String[] args) { for(int i = 0; i < 5; i++) { System.out.println("i = " + i); } System.out.println("Goodbye!"); } } ```

So we're back with our old friend who says:

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 3 i = 4 Goodbye! [nurmes]btg: ```

Now if we `continue` inside a loop, that means to skip the rest of the loop body and carry on to the `i++`. The next time around the loop will behave as normal. Let's try a `continue` to show what I mean. We'll be using an `if` statement which you should have learned about much earlier.

 ``` class Hello { public static void main(String[] args) { for(int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.println("i = " + i); } System.out.println("Goodbye!"); } } ```

In this example, we will `continue` if `i` equals two, before printing the value of `i`.

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 3 i = 4 Goodbye! [nurmes]btg: ```

Because the `continue` comes before we print the value of `i`, the line `i = 2` is not printed. So we could use a `continue` to skip all odd numbers, for example. Now what about `break`?

 ``` class Hello { public static void main(String[] args) { for(int i = 0; i < 5; i++) { if (i == 2) { break; } System.out.println("i = " + i); } System.out.println("Goodbye!"); } } ```

A `break` is rather more serious - it leaves the loop and doesn't come back. We carry on with the code after the end of the loop (which just says goodbye).

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 Goodbye! [nurmes]btg: ```

Let's try a `break` in a `while` loop.

 ``` class Hello { public static void main(String[] args) { int i = 0; while (i < 5) { if (i == 2) { break; } System.out.println("i = " + i); i++; } System.out.println("Goodbye!"); } } ```

This works just the same as the version with the `for` loop (try it yourself). Let's try changing it back to a `continue`. This will continue back to the top of the loop (the test part).

 ``` class Hello { public static void main(String[] args) { int i = 0; while (i < 5) { if (i == 2) { continue; } System.out.println("i = " + i); i++; } System.out.println("Goodbye!"); } } ```

Because the `continue` is before the `i++`, the value of `i` will stay at 2. So we keep going around the loop forever. Before you run the program, I'll move the printing line to show that this happens:

 ``` class Hello { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.println("i = " + i); if (i == 2) { continue; } i++; } System.out.println("Goodbye!"); } } ```

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 0 i = 1 i = 2 i = 2 i = 2 i = 2 i = 2 i = 2 i = 2 ... ```

And so on, and so on (you can stop the program by holding the Ctrl key and pressing C). This is a good reason to use a `for` loop when there is some value being changed with each run through the loop (like `i`); when you use `continue`, the value is still changed.

When you get around to writing your own programs using loops, it's a good idea to print out the value of the loop counter (the variable `i` in this case) each time, like I have. This makes it easier to see what is happening. Anyway, let's get on to another couple of examples:

 ``` class Hello { public static void main(String[] args) { while (true) { System.out.println("Hello!"); } } } ```

Use `while (true)` whenever you want to repeat something indefinitely. For example: reading commands from the computer keyboard until you get a QUIT command. When you get the QUIT command, use a `break` to get out of the loop.

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Hello! Hello! Hello! Hello! Hello! Hello! Hello! ... ```

Just to convince you that `for` loops can be used for something besides counting 0, 1, 2, 3, here's another example:

 ``` class Hello { public static void main(String[] args) { for(int i = 34; i >= 17; i -= 2) { System.out.println("i = " + i); } } } ```

 ```[nurmes]btg: javac Hello.java [nurmes]btg: java Hello i = 34 i = 32 i = 30 i = 28 i = 26 i = 24 i = 22 i = 20 i = 18 ```

Here we are counting down in twos from 34. Remember that `i -= 2` means "subtract two from the value of i and store it back in i".

That's enough `for` a `while`! Geddit? Well anyway this is the end of the lesson, please fill out the mini-questionnaire before you go.

 Butwhatdo youthink? This lesson was... What don't you understand? Other comments? Excellent OK Poor Your email (optional)
Hooray for Arrays!

Too patronising? Too complex? Typing error? Offended by traffic cones? Got a question or something I should add? Send an email to ben_golding@yahoo.co.uk ! visits to this site

The contents of this site are copyright of Ben Golding