What will you build

You will build a small application that will use the concept of iteration. You will see the for, for each, the while and the do-while

What You'll Learn

What will you need

Very often, a set of instructions will need to be repeated through a loop. In Java, several methods exists to create a loop of instructions:

A loop should never be infinite and always have a condition that will stop the loop.

A loop can contains other loops and is called a nested loop.

The while loop loops through a block of code as long as the specified condition is true. The boolean expression is evaluate in each iteration.

while(boolean expression){
instructions to execute
}

The aim of this method is to print a number from 0 to the number that have been passed as an argument.

As long as the variable n is smaller than the variable number, the loop loops through the block of code. When the variable n is no longer smaller than the variable number, the condition have been reach, and the result of the evaluation of the boolean condition return false, stopping the loop.

Tips: It is often that developper either forget to change the value that need to be tested in the boolean expression. The result will be an endless loop. It is also often that developper have some logical error in the boolean expression.

public class Iteration{

public void testWhile(int number){
	int n = 0;
	while(n < number){
		System.out.println(n);
		n++;
	}
}
}

As usual a class Test to test this method and this class.

public class TestIteration{

public static void main (String[] args){
	Iteration iter = new Iteration();
	iter.testWhile(10);
	}
}

The do-while is a variant of the while loop. The loops will execute the code block once, before even checking if the condition is true, then it will repeat the loop as long as the specified condition is true. In contrary of the while that if the condition is false from the beginning, with the do-while the block of code will always be executed at least one.

do{
code that will be executed
}
while(boolean expression);

The aim of this method is to double the number as long as this number is smaller than the number given as an argument, and to print it in the console.

public void testDoWhile(double number){
double d = 100;
do{
	d = d * 2;
	System.out.println(d);
	}
while(d<number);
}

Adding the test of this class in the TestIteration class. Even if the argument passed is smaller than the number it will be test against, the do-while will do the operation at least one.

public class TestIteration{

public static void main (String[] args){
	Iteration iter = new Iteration();
	iter.testWhile(10);
	iter.testDoWhile(10.0);
	
}
}

The for loop is one of the most common type of loop in Java. The loop "for" will do an initialisation before the first iteration, evaluate the condition and after each iteration calls the iteration instruction.

The syntax emphasises the pattern:

for (initialisation instruction; boolean condiion; iteration instruction) {
... 

}

The aim of this method is to list all the character ASCII until it reach the number given as an argument.

public void charAscii(int number){
	if(number>128){
		System.out.println("please enter a number between 1 and 128");
	}else{
		for (char c = 0; c<number; c++){
			System.out.println("character is number "+(int)c + "and the character is "+c);
		}
	}
}

Adding the test of the method charAscii in the TestIteration class.

public class TestIteration{

public static void main (String[] args){
	Iteration iter = new Iteration();
	iter.testWhile(10);
	iter.testDoWhile(10.0);
	iter.charAscii(58);
}
}

It is possible to have any kind of nested loop; a loop inside another loop.

The loop that is inside another loop is called inner loop and is nested inside the outer loop (the external loop).

Tips: if you start to have too many nested loops, it could be that the design of your algorithm is not good.

You can use the different techniques offered in the previous example, you can also mix them. For this example, we will have an nested "for" loop.

The aim of this little program is to draw a nice triangle with number on the console.

public class DrawShape{

	public void drawTriangle(int numberRows){
		for (int i = 0; i < numberRows; i++){
			for (int j = 0; j < numberRows - i; j++){
			System.out.print(j+" ");
			}
			System.out.println();
		}
	}
}

Again, the test of the method in the TestIteration class, however, this time we declare, instantiate and initialise a new class and invoke the method on this new class.

public class TestIteration{

public static void main (String[] args){
	Iteration iter = new Iteration();
	iter.testWhile(10);
	iter.testDoWhile(10.0);
	iter.charAscii(58);
	
	DrawShape ds = new DrawShape();
	ds.drawTriangle(10);
}
}

You can define several variables in the for instructions at the conditions that they are the same type. In this loop, two variables of type int have been defined. The variable i is initialise at 0 and j at 1. It is looping through the block of instructions as long as the i is smaller than 10 and the j is smaller than 40. The increment is +1 for the i, and the j increment from j+i.

public void doubleInstruction(){
	for(int i = 0, j = 1; i < 10 && j < 40; i++, j=j+i){
		System.out.println("i "+i + " j " +j);
	}
}

The instructions inside a loop can be controlled by the keywords break or continue.

The instruction break will break the loop without executing the rest of the loop.

The instruction continue will stop the current execution of the iteration et will start from the begining of the loop with the next iteration.

In the following example, the method will print only the number that have 0 when divide by 9. The loop will finish before it is reaching the condition inside the for, as when it is reaching 74 it is break. Each time that the number is not divisible by 9, the continue will instruct the program to start the loop again without reaching the System.out.println with a i that will have been incremented with 1.

public void continueBreak() {
	for(int i = 0; i < 100; i++) {
		if(i == 74) break;
		if(i % 9 != 0) continue;
		System.out.println("the continueBreak method "+i);
		}
	}

You can find the code for this example in https://git.cardiff.ac.uk/ASE_GROUP_2020/code_for_codelabs.git