For Loops(Continued)

Subscribe to Tech With Tim!

Iteration

In the last tutorial you learned about for loops and how we can use them to loop through arrays and execute a set of code a set amount of times. Whenever we create and go execute a loop that is known as an iteration. In the last tutorial we were iterating by a condition, meaning we kept going until a condition was no longer satisfied. In this tutorial we are going to iterate by item.

Iteration by Item

I use the word collection to represent a data type that holds more than one item. An array is an example of a collection as it can store multiple items. Just be aware that there are other collection data types in Java and we can iterate through them as well.

Now it is time to introduce you to another type of for loop. This for loop makes it very easy to loop through each item within an array or collection data type (collections will be covered later). When we implement the for loop seen below we say we are iterating by item. This type of loop will run through each item in a collection (array in our case) and set a variable equal to it each loop. It will keep looping until it has seen every item in the collection.

```int[] x = {1,4,5,6};

for(int item: x){
System.out.println(item);
}

// OUTPUT
1
4
5
6
```

Note that we can accomplish this by using the previously learned for loop as well. Although it is not as elegant.

```int[] x = {1,4,5,6};

for(int i = 0; i < x.length; i++){
System.out.println(x[i]);
}

// OUTPUT
1
4
5
6
```

Example

Here is a more complex example of using for loops.

```import java.util.Scanner;

public class Main{
public static void main(String[] agrs){
int len = 4;
String[] strs = new String[len]; // Creates new string array of length 4

Scanner sc = new Scanner(System.in);

// Populate the strs array with user input
for (int x = 0; x < len; x++){
System.out.print("Input: ");
strs[x] = sc.nextLine();
}

// Print the array to the console
for (String val: strs){
System.out.println(val);
}
}
}

// This program will ask the user for 4 values and insert them into the strs array
// afterwards it will print the values back to the user.
```

If you'd like some more examples please refer to the video.