Please enable JavaScript to use CodeHS

Chapter 4

Iteration

4.2 for Loops

Like while loops, for loops are a way to change the flow of control by repeating a block of code. for loops allow us to repeat code a fixed number of times.

A basic for loop is structured like this:

for (int i = 0; i < COUNT; i++) 
{  
    // Code segment that is executed COUNT times. 
} 
Plain text

Breaking Down the for Loop

A for loop can be divided into three major parts. The first part initializes the loop variable, the second part tests some condition and the third part increments or decrements the loop variable. Each part of the for loop is separated by a semicolon (;).

Let’s break down the following example into its three major parts:

Part 1: Initialize
The first part of a for loop initializes some variable. In the example above, int i = 0 initially sets the variable i equal to 0.

Part 2: Condition
The second part of a for loop tests a condition. If the condition is true, the code within the for loop executes. If the condition is false, the code within the for loop is skipped. In the example above, i < 3 compares the current value of our variable i to determine if it is less than 3. Each time i is less than 3, the value of i will be printed to the screen. This happens three times.

Part 3: Increment/Decrement
The third part of a for loop changes the variable after each time the loop runs. Remember, i++ means 1 is added to i. It is incremented. Conversely, i-- means 1 is subtracted from i. It is decremented.

Putting It All Together

When a for loop runs, each of the 3 parts runs in a particular order. The initialization step only runs one time before the boolean expression is evaluated the first time. After this, the boolean expression is evaluated and if it is true, the loop executes. After the loop execution, the increment/decrement statement executes before the is evaluated again.

What happens when you run the example for loop? What gets printed to the screen?

The first part of our for loop, int i = 0, initializes our variable. It sets our loop variable i equal to 0. Next, the condition part of the loop is evaluated. Is i< 3? Since i is currently set to 0, and 0 is indeed less than 3, the condition i < 3 is true. Thus, the code within the for loop is executed. 0 is printed to the screen. After this, i is incremented. i++ means you add 1 to i, so i is now set to 1.

Since i is now set to 1, the condition i < 3 is re-evaluated. It is still true. 1 is now printed to the screen. i is incremented again and becomes set to 2.

The condition i < 3 is re-evaluated. Since i is now set to 2, our condition is still true. 2 is printed to the screen. i is incremented again and becomes set to 3.

Finally, when the condition i < 3 is re-evaluated, our condition is false. 3 is not less than 3, so the code within the for loop is skipped. Nothing else gets printed. The for loop is done.

Thus, our output would be:

0
1
2
Plain text

for Loop

Countdown

for loops and while loops can be interchangeable. A for loop can be rewritten as a while loop and vice versa. Take a look at the countdown while loop from earlier.

int i = 100;
System.out.println("Initiating countdown:");
while(i >= 0) {
  System.out.println(i + "...");
  i--;
}
Plain text

In this countdown example, i is initially set to 100. The while loop checks the condition and insider the loop, i is decremented. The same process can happen in a for loop.

Each piece that you saw in the while loop is still present as one of the three parts of the for loop.

Count By Twos

Instead of incrementing or decrementing i by only 1, you will increment i by adding 2 in this example instead. This allows you to count up by two each time.

Off By One Errors

One thing to be cautious of is off by one errors. Off by one errors occur when your loop doesn’t start or stop at the correct place. Think about summing the numbers from 1 to 100. You may think of setting up your for loop like this:

for (int i = 1; i < 100; i++) {  ...  }
Plain text

Doing so will cause an off by one error since you are missing the 100. Since you want to include 100, you need to use a <= (less than or equal) instead of just a less than. Here is a correct loop to sum the numbers from 1 to 100.

For Loop Sum

The for loop adds the numbers 1+2+3+4+5+6+…..+98+99+100. Since this program uses global constants, you can easily change the MIN and MAX values used in our sum without having to touch the for loop at all.

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    What does the following code print?

    for (int i = 4; i < 8; i++)
    {
       System.out.print(i + ", ");
    }
    Java

Exercise: Replace while Loop with for Loop

Run this program first to see what is does. Then rewrite the program so it uses a for loop instead of a while loop.