We use cookies to give you a better experience, if that’s ok you can close this message and carry on browsing. For more info read our cookies policy.
4.5

# Using loops

There are some tasks that we need to do over and over again for a given number of times or until a condition is satisfied.

Imagine a long queue at a bus stop. In order to clear the queue, a number of tasks have to be repeated until the queue is cleared: each person will have to get on the bus, be greeted by the driver, buy a ticket, find a seat, and so on. If the queue is particularly long, some of the passengers might even have to wait for the next bus.

‘bus queue’ by brapps from https://www.flickr.com/photos/brapps/233148352/in/photostream/ used under the CC BY-NC 2.0 licence

In programming, code can be entered that allows for tasks to be repeated automatically. In the above example, the code would perform the same tasks (boarding, being greeted, paying, etc) for each passenger boarding the bus until the queue had been cleared. Let’s look at the example of adding values to an array that we covered in the Using arrays step.

Each element of the array has to have a value assigned to it. We call this initializing the element. In Java a construct, called a loop, can be used to repeat this step automatically until all of the elements are initialized (instead of having to do each one separately).

There are several different types of loop, and they each behave in different ways:

## While loop

while (expression) {
statement(s);
}


In a while loop the statements within the block (which are indicated by the curly brackets {}) are executed while the expression remains true.

Example 1:

int myVariable = 0;
while (myVariable <1) {
myVariable = myVariable +1;
}


In this piece of code the variable,myVariable, is declared. This has a value of 0.

The while loop expression states that the loop should run while the value of myVariable is less than one.

However, the statement in the loop adds 1 to the value of myVariable each time it runs.

This means that after the loop has run once, the value of myVariable will be 1 and the expression, ‘myVariable is less than 1’, is no longer true - so the loop will not run again.

If you were to change the expression to myVariable<10, the code in the loop would run 10 times before stopping.

So if we created a loop like this:

while (2 == 2) {
statement(s);
}


…the loop would continue forever, because the expression (2==2) is always true and there is nothing in the statement that changes these values. It is equivalent to:

while (true) {
statement(s);
}


Example 2:

// declares an array of integers
int[] myArray;
// allocates memory for 3 integers
myArray = new int[3];

int myIndex = 0;
while (myIndex <3){
/*assign values to each array element*/
myArray[myIndex] = 0;
// increment array index
myIndex = myIndex + 1;
}


Now look at the execution in detail:

After declaring the array and defining the number of elements in the array, the line int myIndex = 0; is executed, which sets the value of myIndex to 0. myIndex is a variable that will add the values to the array.

myIndex = 0

myArray

 0 1 2

Next, the while loop is executed. Because the condition is true (myIndex is 0, which is less than 3), execution proceeds to next line. As the value of myIndex is 0 the code can be read as myArray[0] = 0, which assigns 0 to the first element of the array.

When the next line executes 1 is added to myIndex, giving it a new value of 1.

Now the variables in the program look like this: myIndex = 1

myArray

 0 0 1 2

Because this is a loop, the program will cycle through again until the condition (myIndex <3) is met. At this point myIndex is 1, which is less than 3, So the code inside the while loop is executed.

Because myIndex is now 1, the next statement can be read as myArray[1] = 0;.This assigns a 0 to second element of the array and proceeds to the next statement where 1 is added to myIndex.

Now the variables in the program look like this:

myIndex = 2

myArray

 0 0 1 0 2

The program will then run the loop again. The expression is still true as myIndex is now 2, which is less than 3 so the code in the block will be executed again.

As myIndex is now 2, the next statement can be read as myArray[2] = 0; the third index in the array has been assigned a value of 0.

After this assignment 1 is added to myIndex and the variables in the program looks like this:

myIndex = 3

myArray

 0 0 1 0 2 0

Control flows back to the while statement and condition gets evaluated. However this time, because myIndex is equal to 3, the condition fails and execution reaches the end of the code.

How does this happen?

The program trying to run the while loop again checks the condition. This time, because myIndex = 3, the expression is no longer true. This means that the condition of the while loop is not met and the code inside the block is not executed.

## Do–while loop

do {
statement(s);
} while (expression);


Do–while is another looping construct available in Java. A do-while loop checks the condition after the first execution of the statement block, whereas a while loop checks the condition first. This means that statements in a do-while block are executed at least once. Can you try to write the piece of code to initialize the array using a do-while loop?

Now compare yours with the code below.

// declares an array of integers
int[] myArray;
// allocates memory for 3 integers
myArray = new int[3];

int myIndex = 0;
do {
myArray[myIndex] = 0; /* assign values to each array element*/
myIndex = myIndex + 1;// increment array index
} while (myIndex <3);



## For loop

A for loop allows us to combine a number of conditions, creating more complex functions without having to write lots of code. For loops are structured in a particular way:

for (initialization; termination; increment) {
statement(s);
}


A for loop runs until the termination expression evaluates to false.

Look at same example written using the ‘for’ statement.

// declares an array of integers
int[] myArray;
// allocates memory for 3 integers
myArray = new int[3];
// assign values to each array element
for (int myIndex = 0; myIndex < 3 ; myIndex++) {
myArray[myIndex] = 0;

}


Here you can see that the code is compacted because initialization (int myIndex = 0), condition check (myIndex < 3) and the looping variable increment (myIndex ++, which is equivalent to having myIndex = myIndex + 1) are all achieved in a single line of code.

Can you draw the diagrams and explain the step by step execution of this program as we did in the while loop?

In this article we have covered repetition in programming and how it can be implemented in Java using different language constructs. We explored the while loop, do-while loop and for loop and looked at how these constructs can be used to perform a repetitive task. Great work!