Loops in Java

Loops in Java is the structure that will allow us to implement algorithms with repetitions.

In this lesson, you will learn the two different types of loops you can find in most programming languages. Also, you will see how to use them in Java.

From the lesson algorithms with repetitions, we created the following algorithm (represented with a block diagram). Let’s find out how to implement this algorithm in Java.

Remember algorithms in computing are created to solve problems. The problem we solved is “print the odd numbers that are greater than 10 and less than 1000”.

Flow diagram for a loop example

In programming, we have available two types of loops. One of them is called loop with pre-condition and the other one loop with post-condition.

As its names states, the first one, first check a condition and, if the condition is true, it will execute the block of instructions.

On the other hand, the second type will execute the block of instructions the first time without checking any condition. After the execution is finished, then it will check a condition.

In both cases, we call the condition: the stop condition. The name means that what will decide whether the algorithm stops is that condition. We must be careful to write a condition that can be met. Otherwise, we will be creating an infinite loop, something we don’t usually want.

Loops in Java: pre-condition

As the name states, this type of loop first will check if a certain condition holds, and if it holds, the block of instructions will be executed.

From the flow diagram above, we can see that the condition is checked at the beginning of the flow. Therefore, we should implement this algorithm using a loop with pre-condition.

The following is the general structure of a loop with a precondition.

while (condition){
   //block of instructions
}

See the Java example below.

public class OddNumbers {
    public static void main(String[] args) {
        int number = 11;
        while (number<100){
            if (number % 2 == 1){
                System.out.println(number);
            }
            number = number + 1;
        }
    }
}

You probably already notice that we didn’t have any need to refer to the problem. The reason behind it is that we are literally translating the algorithm into Java code. At this point, we don’t need to look at the problem statement anymore.

We created an algorithm (a generic solution, programming language agnostic) and now we can decide whether we want to implement it in Java, C# or any other programming language.

To do that, we don’t need another algorithm, we just need to know (or to find out) how to write the specific structures on the algorithm using the specific programming language.

That is why I always say it is not important to focus on learning a specific programming language. You have to focus on learning the paradigm, the way to solve problems by using a computer and a programming language.

You can read more about this in the following articles:

Loops in Java: post-condition

Another way to use loops is first to execute a block of instructions, and after the execution check for a condition. If the condition is true, then the block of instructions is executed again. This process is repeated until the condition is false.

As you can see from the flow diagram above, the algorithm we designed, check for a condition (number<100) and, if the condition is true, then the block of instructions (if the number is odd, print the number) is executed.

However, if we assign the value 11 to the variable number, there is no need to check the condition number<100 the first time, because we ensured that the condition is true the first time by assigning 11 to the variable number (11<100 is true).

Find below the code on how this is implemented in Java (and in several other languages).

public class OddNumbers {
    public static void main(String[] args) {
       for (int number=11; number<100; number++){
           if (number % 2 == 1){
               System.out.println(number);
           }
        }
    }
}

The structure we are using here is called a for-loop.

The general structure is as follows:

for (variable initialization, condition, increment){
  // block of instructions
}

Variable initialization is where we declare and assign an initial value to the loop-control variable (number in the example). That variable is called like that because is the one that controls when the loop is going to finish.

The condition states when the loop is going to finish and, the increment states how the loop-control variable will be modified on each iteration.

The steeps are executed in the following order:

  1. A variable is created and initialized  (int number = 11)
  2. The block of instructions is executed
  3. The increment is executed (number++, remember this is the same as number = number + 1)
  4. The condition is checked
  5. If the condition is false, the block of instructions is not executed.
  6. If the condition is true, step 2

Summary

In this lesson, you learned how to use loops with pre and post condition in Java.

An important part of this lesson is to understand when you can use a loop with pre-condition and when is better (or even necessary) to use post-conditions.

H@ppy coding!