Java – Loops

Loops in Java

We would learn about loops in this lesson. Hence we would cover the following 5 topics.

  1. Introduction to Loops in Java
  2. while Loop
  3. for Loop
  4. do…while Loop
  5. Loop Control Statements
  6. Enhanced for Loop

 

1. Introduction to Loops in Java

You would probably need to execute a block of statements  a number of times.  This can be based on a given criteria. Loops provide a construct to achieve that.

A loop repeatedly tests a condition. As a result, it continues to execute the block of code. This is so long as the condition is true. We call the block on code the body of the loop.

A loop in java is represented as shown in Figure 1.0.

Loops in Java

Figure 1.0: Structure of Loops in Java

We would consider three types of loops in Java:

  • while loop
  • for loop
  • do…while loop

 

2. while Loop

We use the while loop to continually execute a code as long as a condition is true. Keep in mind that the number of times to repeat the execution is probably not known.

 

The syntax of while loop is:

  while(condition) {
	  //body of the loop
  }
//other statements

 

I have also provided a diagram for while loop in Figure 1.1 below.

 

While Loop in Java

Figure 1.1: While Loop in Java

The condition is an expression that results in true or false. So when the loop starts, it first checks the condition. If it is true, then it executes the codes in the body of the loop. It then checks the condition again and if, true, it executes the body of the loop again. The process continues.

If on the other hand, it’s false, then the loop terminates. Execution then continues with other statements after the loop.

 

Listing 1.0 provides a code for using a while loop to display number 1 to 10

  int i = 0; //Loop variable
  while(i < 10) {
	  System.out.println(i);
	  i++;
  }

Listing 1.0: Program to display 0 to 10 using while loop

 

3. for Loop

Next we are going to examine the for loop. You use a for loop when the you want to execute the code block a given number of times.  So the important thing is the number of times. This is known in advance.

The syntax for the for loop is given below.

  for(initialization; condition; update)
	  //body of the loop	      
   }

 

The four main parts of the for loop are:

Initialization: Here, you declare and initialize the loop variable.

condition: Here, you specify the condition that would be checked each iteration. An iteration is a single execution of the body of the loop. Therefore, this should be a boolean expression. It must evaluate to true or false. If this condition ever becomes false, then the loop terminates. As such, execution continues with the statements after the loop.

update: This is the code that adjusts the loop variable. It results in an increase or decrease to the loop variable

Body of the loop: Finally the body of the loop contains statements that are executed for each iteration of the loop

 

I provide a diagram for the for-loop in Figure 1.2.

For loop in Java

Figure 1.2: For Loop in Java

I also provide a for loop version of the previous program. The program prints number 0 to 10 using a for loop.

  for(int i = 0; i<= 10; i++) {
	  System.out.println(i);
   }

Listing 1.2: Program to display 0 to 10 using for loop

 

4. do…while Loop

The third and final type of loop we would cover is the do…while loop. It is similar to the while loop. Unlike the while loop, it is guaranteed to execute a least once.

 

The syntax for the do…while loop is:

  do {
	  //body of the loop
  } while(condition)
//other codes

 

It is noteworthy that the condition (boolean expression) is placed at the end of the loop. For this reason, the loop must execute once, before it tests the condition.

If the condition if true, then the body of the loop is executed again. I however, the condition becomes false, the loop terminates. Then other codes is executed.

I provide the diagram for the do…while loop below.

do...while loop

Figure 1.3: do…while Loop

Notice that in the do…while loop, the position of the condition and the code to execute is interchanged. You can find a program to print numbers 0 to 10 using the do…while loop.’

  int i = 0;
  do {
	  System.out.println(i);
	  i++;
  } while(i < 10);dition)

Listing 1.3: Program to display numbers 0 to 10 using do..while loop

5. Loop Control Statements

Let’s now look at loop control statements. You use loop control statement to alter the normal execution sequence of a loop. So there are two of them.

  • break Statement
  • continue Statement

 

break Statement

You use the break statement is used to end the execution of a loop. Hence, if a break statement is encountered, the loop terminates. Then the statements after the loop is executed.

Furthermore, the break statement can also be used with the switch statement. We would cover switch statements in the next lesson.

 

continue Statement

You use the continue statement to terminate the current iteration of a loop. Remember that iteration means a single execution of a loop body. So let’s assume a loop body has 5 lines (line 1 to 5). If it the program is currently executing line 3 and encounters a break statement. I would skip lines 4 and 5 and jump back to line 1.

  • In a for loop, the continue statement immediately moves control to the update  statement
  • In a while loop however, the continue statements causes the program to jump to the condition statement

 

6. Enhanced for Loop

Now this is an interesting one. We use enhanced for loop as a shorter form of the for loop. You probably would use it to loop through array elements.

I provide the syntax below:

  //Enhanced for loop
  for(declaration : expression) {
	  // body of the loop
  }

 

Declaration: This is a variable declaration. You make sure that the data type is compatible with the elements of the array we want to loop.

Expression: Specifies the array we want to loop through

 

Let’s now use the enhanced for loop to print out all the names in an array of names. You can see this in Listing 1.4. I recommend you try it yourself.

public class Tester {

   public static void main(String args[]) {
	    String names[] = {"Osoo","Adii", "Jackie", "Ottie", "Haty", "Kany","Olie", "Saffy"};
	    
	    for(String name: names) {
	    	System.out.println(name);
	    }
   } 
}

Listing 1.4: Enhanced for loop

 

I ran this program using Eclipse IDE and the output is given below in Figure 1.4:

Enhanced For Loop in Java

Figure 1.4: Enhanced For Loop in Java