For loop in Java: counting loop that repeats the code a specific number of times


Keywords: for loop, counting loop, loops

for loop java programming

This article will look at the for loop in Java that you use when you want an operation to be repeated a specific number of times. In other words, it is a counting loop that repeats the loop through the code block a fixed number of times. We will start by looking at how the for loop works and syntax to create it, and then focus on solving some exercises together.

What is the for loop?

In Java, you use the for loop when you want to repeat an operation a specific number of times. A for loop is described as a counting loop; in other words, the loop repeats a code sequence a predetermined number of times.  Therefore, the for loop is best suited when you know the number of iterations that the loop will need to do. 

In short, the for loop:

  • A loop that repeats a sequence of operations a specific number of times.
  • Enables general and dynamic programs because you can reuse code.
  • Best suited when the number of iterations of the loop is fixed.

How the for loop in Java work? 

The for loop works in a similar way as the while loop that we described in the previous article. If we illustrate the for loop using a flow chart, we get:

For loop Java programming

Figure 1: For loop in Java

What figure 1 shows is that:

  1. The for loop starts by checking if the condition is true. In that case, the loop will execute the code block within the loop.
  2. When all operations are executed, the loop increases the initial value, also called the counter, and the program returns to the beginning of the for loop again.
  3. If the condition is still true after the initial value has been updated, the for loop executes the code block again. This procedure continues as long as the condition is true.
  4. Finally, when the condition becomes false, the program moves on. 

The for loop repeats a sequence of operations a specific number of times. 

How to create a for loop in Java

The for loop is declared with the reserved word for followed by the “head” of the for loop in parentheses ( ). The “head” consists of three components, and a semicolon, ; ,separates each component. 

  1. Initial value: indicates the value that the loop starts from, commonly occurring is int i = 0.
  2. Condition: determines the logical condition must be true to execute the loop. For example, evaluate whether a variable is less than a certain value.
  3. Change: states how the initial value should change, for example, increase or decrease.

Finally, within the curly brackets { } you specify the code block that you want to execute as long as the condition is true

Syntax: Declare for loop in Java

for (initial value; condition; change) {

      // for loop code block
}

Examples: For loop in Java

Let’s look at a few examples of how to use a for loop in Java.

Example 1: Create a for loop in Java

The following example demonstrates how it is possible to use the for loop to perform an operation a specific number of times.

public class Example{
   public static void main(String[] args) {

      for(int i = 0; i < 5; i++) {            

         System.out.println("Counter: " + i); 
      }
   }
}

Let us break down the ”head” of the for loop

  • First, you specify an initial value int i = 0, i.e. the start value from which the loop should start counting.
  • Second, it is stated that the loop should be repeated as long as i < 5, i.e. five times in this example.
  • Finally, specify how much the variable should change after each loop, in this case increasing by 1. Remember, typing i++ in Java is the same as i = i + 1

The for loop in this example repeats the operation as long as i is less than 5. Moreover, let us run the code and print the result in the terminal: 

Counter: 0 
Counter: 1 
Counter: 2 
Counter: 3 
Counter: 4

If you would like to try the code in this example in an online compiler, click the button below.

Example 2: For loop with an if statement in Java

Let’s look a similar example, where we will now use an if statement that we saw in the previous chapter. Assume we have an airplane with exactly 12 seats (it’s a small airplane). The airline wants to mark the seats are window seats and the seats that are in the corridor. Since it is a small plane, you sit either by the window or in the hallway. 

The airline has decided that odd numbers are window seats and even numbers are in the corridor. The number for the seats starts at 1. Since we know how many places there are, we can use the for loop. 

public static void main(String[] args) {

    for (int i = 1; i <= 12; i++) {

        if (i % 2 != 0) {
            System.out.println("Place " + i + " is a window seat");
        } 

        else {
            System.out.println("Place  " + i + " is in the corridor");
        }
    }
}

In this example, we will start from the initial value one and then increase the initial value until it is less than or equal to 12. Furthermore, we use the if statement to check if the seat is a place on an odd number; that is, the number is not evenly divided by 2.

Finally, in this case we get the result:

Place 1 is a window seat
Place 2 is in the corridor
Place 3 is a window seat
Place 4 is in the corridor
Place 5 is a window seat
Place 6 is in the corridor
Place 7 is a window seat
Place 8 is in the corridor
Place 9 is a window seat
Place 10 is in the corridor
Place 11 is a window seat
Place 12 is in the corridor

Example 3: For loop that is counting descending

In this final example, we are going to count from the number 25 and down, that is, going from a larger initial value and down. We will also not include every step on the road but instead, change the steps with minus 3 for each step. If we set it up in the code editor:  

public static void main(String[] args) {

    for (int i = 25; i > 0; i = i - 3 ){

        System.out.println("Number: " + i);
    }
}

What we have set up in the for loop is.

  • Our initial value is 25.
  • We will execute the for loop as long as i is greater than 0.
  • We will decrease the initial value by 3 for each time we perform the loop.

Finally, if we run the code we get the result: 

Number: 25
Number: 22
Number: 19
Number: 16
Number: 13
Number: 10
Number: 7
Number: 4
Number: 1

Why use a for loop in Java?

We use the for loop in Java to iterate over a code block as long as the condition is true. We usually use the for loop when we know in advance how many times should repeat it. For example, loop through a list or array (we will see more about in later chapters) from beginning to end. Unlike the while loop, a for loop has its limits from beginning to end. Although you can manipulate these limits, the general implementation is such that the maximum number of loops is predetermined.

Common mistakes when using the for loop in Java

Similar to the while loop, there are a couple of common mistakes. However, note that these are some common errors we have noted, there are, of course, several other mistakes you can make. 

  • Semicolon at the end of the declaration (head) of the for loop. This separates the for statement from its code. Because we use curly brackets to group code blocks, the code will only be executed once if you use a semicolon. 
  • A common situation is that we use the for loop to iterate through an array (more on array later). In Java, the array starts with index 0, so an array of 10 elements will have the elements numbered from 0 to 9. A common mistake is not to pay attention to the index starting at 0, and not 1 when initiation your loop.
  • Incorrect with one in the number of iterations, usually due to a mismatch between the state of the for loop and the initialization of the variables used in the condition. A good idea for longer loops and more extensive programs is to test the loop on a smaller scale before.

Summary: For loop in Java

The for loop in Java is a so-called counting loop that repeats a code sequence a predetermined number of times. Therefore, the for loop is best suited when you know the number of iterations that the loop will need to do.

Syntax: for loop in Java

for (initial value; condition; change) {

      // For loop code block
}

FAQ: For loop in Java

Can I use the for loop if I don’t know the number of iterations?

Yes! Java has several built-in features to help you calculate, for example, the length of a list or array. If you want to use a for loop to process an array, then you do not need to know how long the array is, Java helps you to process it, and you simply use that built-in function in your for loop conditions.

Can I use a for loop inside another for loop?

Yes, that’s okay. It is called nested for loop and is commonly used, especially when working with lists and arrays.

Can you use a for loop inside a if statement?

Yes, you can use a for loop inside the code block of an if statement. As long as the condition of the if statement are true, the condition of the for loop will then be evaluated.