Java Repetition Statements: for Loops
for Loops
The for loop is a used to repeat a code block a predetermined number of times. It requires a three separate expressions separated by a semi-colon called initialise, test, and increment. The general syntax is:
for (initialise; test; increment) {
statements;
}
There is no limit to the number of statements you can have within the code block and they will be repeatedly executes as long as the test expression is true. Let’s have a look at each of the expressions in more details:
- Initialise: The initialiser is a variable that will be used to keep track of how many times we will loop through the code
- Test: The test compares the initialiser to a condition to see if the loop should continue
- Increment: The increment advances the initialiser variable to the next step of the loop
Let’s have a look at a working example. Imagine you have a counter that will count from 1 up to 5. Let’s call that variable counter, and since it will count in whole numbers let’s make it an integer. Next we need to create a loop that will output the value of counter over and over, and everytime we output the value of counter we will need to increment the value of counter so that the next time the code loops we will output a new value of counter.
int counter = 0; for (int i = 0; i < 5; i++) { counter++; System.out.println("Counter: " + counter + " - i: " + i); }
From the code above, we can see that the variable counter has been defined and initialised with a value of 0. The for loop is fully formed with the initialise, test and increment expressions, let’s step through each of these in turn:
- The initialise expression defines and initialised a new variable called i that will be used but the next two expressions.
- The test expression checks to see if i is less than 5, if this is true then Java will begin to execute the code block, if it is not true (of if it is false) Java will ignore the code block and jump to after the clocking curly bracket of the code block.
- The increment expression will increment the value of i after the code block has been executed (this only happens if the test expression is true).
The code block contains two statements:
- counter++; will take the existing value of counter and increment it. So the very first time this for loop is executed the value of counter will be zero, and once the code block is executed that value will increase by one. This increment will repeat each this the code block is executed.
- System.out.println(“Counter: ” + counter + ” – i: ” + i); will output the values of both current and i at that moment in the programs execution. So the very first time this for loop is executed the value of counter will be 1 having been incremented by the line above and the value of i will be zero since it has not yet been incremented, but this will happen as soon as Java returns to the top the for loop.
So let have a look at the output:
run: Counter: 1 - i: 0 Counter: 2 - i: 1 Counter: 3 - i: 2 Counter: 4 - i: 3 Counter: 5 - i: 4 BUILD SUCCESSFUL (total time: 0 seconds)
As expected, the first output match with the expectation noted above and the values of current and i have incremented each time the for loop executes.
Omitting expressions
This structure (initialise; test; increment) is generally accepted as the standard for loop structure but there are variations that you should be aware of. The three expressions of the for loop are in fact optional, however if you choose to omit all three you will create an infinite loop can be created as follows:
for ( ; ; ) { System.out.println("Help, I'm stuck in a loop..."); }
The output is neverending:
run: Help, I'm stuck in a loop... Help, I'm stuck in a loop... Help, I'm stuck in a loop... Help, I'm stuck in a loop... Help, I'm stuck in a loop...
… and so on. We don’t want this!
So, since none of the expressions are actually required you could legally omit the test and/or increment and locate them elsewhere:
int i = 0; for ( ;i < 5 ; ) { i++; System.out.println("Phew, I'm not stuck in a loop..."); }
The output would be:
run: Phew, I'm not stuck in a loop... Phew, I'm not stuck in a loop... Phew, I'm not stuck in a loop... Phew, I'm not stuck in a loop... Phew, I'm not stuck in a loop... BUILD SUCCESSFUL (total time: 0 seconds)
So, although the for loop expressions are not required, we recommend that you do use all expressions for clarity. Later in this course we will explore alternative for loop structures that are designed specifically for arrays, known as the enhanced for loop or the for-each loop. We will discuss those in the same lesson as arrays.
Nested for Loops
Just like if statements, for loops can be nested to create more complex and powerful repetition statements. Let’s say to want write a program that will loop a code block 3 times, but for each of those loops you want to loop a seperate code block 3 times – this could be to output the contents of an array with multiple rows and columns. To achieve this we would need have both for loops working together by nesting one inside the other.
The key is the remember that a loop will simply execute whatever it sees within its code block, and if that code block contains another loop then it will happily execute that loop as many times as is required before moving onto the next statement. Let’s have a look at how this might work in practice:
for (int i = 0;i < 3 ; i++) { System.out.println("Here's the outer layer..."); for (int k = 0;k < 3 ; k++) { System.out.println("... with lots of inner layers!"); } }
Here we have two for loops:
- An outer for loop that will output the string “Here’s the outer layer…” as long as the variable i is less than 3.
- An inner for loop that will output the string “… with lots of inner layers!” as long as the variable k is less than 3.
Since the inner for loop is within the code block of the outer for loop, it will only execute when the outer for loop code block is executed, or as long as i remain less than 3. This results in the following output:
run: Here's the outer layer... ... with lots of inner layers! ... with lots of inner layers! ... with lots of inner layers! Here's the outer layer... ... with lots of inner layers! ... with lots of inner layers! ... with lots of inner layers! Here's the outer layer... ... with lots of inner layers! ... with lots of inner layers! ... with lots of inner layers! BUILD SUCCESSFUL (total time: 0 seconds)
As you can see, the outer for loop execution resulted in 3 loops, and as part of each execution the inner for loop was executed which resulted in 3 loops for each outer loop.