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 do I use when?

Enhanced for loop - For Each vs. index for loop with Arrays
Enhanced for loops loop by value, and is arguably the easier method of traversing an array. However, with more complicated manipulation of arrays a index for loop will be needed e.g.:

While loops
Used when the number of iterations is unknown prior to entering the loop.