1.1-Introductie-Programmeren

Theory Loops 3

Competence: I can use both the index-based for-loop and the enhanced for-loop. I know when to use which loop

Specific learning goals:

The exercises can be found in the different submodules.

Summary

index-based (iteration) for Loop

Index-based loops are used to iterate a part of the program a fixed number of times.

for(start; condition; step){
    //Code
}

Example iteration for loop

for(int i = 0; i < 10; i++) { 
    //Code
}

Does the exact same as:

int i=0;

while(i<10){
    //Code
    i++;
}

Looping through ArrayLists

To loop through an arrayList by pointer/position you need to know the number of elements in the array. Assuming I have an ArrayList called arrLst, to get the number of elements (size):

arrLst.size();

Enhanced for Loop
You can also loop through each item in the arrayList (Or arrays, covered later), by using a For Each loop. To print using this method:

for (String item: arrLst) {
    SaxionApp.printLine(item);
}

In the above example item would be the first item in the arrLst on the 1st iteration, then become the second etc… until it reached the end of the ArrayList.

Index for loop
I could use an index-based for loop to start at position 0 (Start of arrayList and loop till the end). Below is an example to print out each value in the arrayList using the pointer.

for(int i = 0; i < arrLst.size(); i++) {
    String item = arrLst.get(i);
    SaxionApp.printLine(item);
}

Which Loop Should You Use, and When?

An overview of the four loop types in Java, with a focus on when you do or do not need the index.

Overview

Loop When to Use Example Situation Index Available? Short Example
while The number of iterations is unknown. You continue until a condition becomes true. Continue until the user types stop or until the input is valid. No, unless you provide one externally if needed. while (!input.equals("stop")) { ... }
enhanced for You iterate through all elements, and their position in the collection is not important. Printing every name in a list. No. for (String name : names) { ... }
index-based for The number of iterations is known, or you need the index, or you want to traverse the collection in a different way. Displaying positions, stepping by 2, iterating backwards, or traversing two arrays in parallel. Yes. for (int i = 0; i < names.length; i++) { ... }
do-while (less common) Similar to while, but the body must execute at least once. Asking for input first and only then checking whether it is valid. No, unless you provide one externally if needed. do { ... } while (!valid);

The Index as the Deciding Factor

The difference between the enhanced for loop and the index-based for loop is entirely about the index.

The enhanced for loop is about convenience: each element is provided to you automatically, and you do not have to manage a counter. However, you do not know which position you are currently at.

The index-based for loop is about control: you have access to i, allowing you to do things that are not possible with an enhanced for loop.

A useful rule of thumb for students is: use an enhanced for loop unless you need to do something with the position. In that case, an index-based for loop is the right choice.

A while loop does not have an index by itself. In principle, it therefore has no notion of position, and if you need one, you must provide it yourself with a separate counter. The same applies to the do-while loop.

In addition, while and do-while loops are used when you do not know ahead of time how many times something needs to be repeated.

Code Examples

Enhanced for (no index needed)

for (String name : names) {
    SaxionApp.printLine(name);
}

Index-based for, using the index (showing the position)

for (int i = 0; i < names.length; i++) {
    SaxionApp.printLine(i + ": " + names[i]);
}

Index-based for, stepping by 2

for (int i = 0; i < names.length; i += 2) {
    SaxionApp.printLine(names[i]);
}

Index-based for, iterating backwards

for (int i = names.length - 1; i >= 0; i--) {
    SaxionApp.printLine(names[i]);
}

Index-based for, traversing two arrays in parallel using the same index

for (int i = 0; i < names.length; i++) {
    SaxionApp.printLine(names[i] + " is " + ages[i] + " years old");
}

The last four examples are exactly the situations where an enhanced for loop is not sufficient. They are excellent examples for demonstrating why you sometimes need access to the index.