Theory:Iterating over arrays
When we work with elements of an array, we often need to perform some kind of algorithm. For example, we might need to sort them, find the maximum element, print only positive numbers, reverse the order, calculate the arithmetic average of a series of numbers, and so on.
# Reading an array from the standard input
We can also use a loop to read all the elements of an array from the standard input.
For example, the following input consists of two lines. The first line contains the length of the array and the second line contains all its elements.
5
101 102 504 302 881
2
Let's read these numbers using Scanner
(you can use other tools for reading) and then output all the numbers it read.
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt(); // reading a length
int[] array = new int[len]; // creating an array with the specified length
for (int i = 0; i < len; i++) {
array[i] = scanner.nextInt(); // read the next number of the array
}
System.out.println(Arrays.toString(array)); // output the array
2
3
4
5
6
7
8
9
10
The program outputs:
[101, 102, 504, 302, 881]
# Using for-each loop
Since Java 5, there has been a special form of the for-loop called for-each. It is used to iterate through each element of an array, a string, or a collection (we will learn them in the following topics) without indices.
Here's how it looks:
for (type var : array) {
//statements using var
}
2
3
The for-each loop has some limitations. First of all, you cannot use it if you want to modify an array, because the variable we use for iterations doesn't store the array element itself, only its copy. It is also impossible to obtain an element by its index since we have no index track. Finally, as is clear from the name, we cannot move through an array with more than one step per iteration: we iterate over each and every element, so we work with them one by one.
As you can see, the absence of indices makes the code more readable. The for-each loop also allows you to avoid the ArrayIndexOutOfBoundsException
. All of this makes it a popular tool for iterating over an array.
# Conclusion
Using loops is a convenient way to process an array of elements. You can perform various algorithms, iterate an array and read in from the standard input with a loop. A form of for-loop called for-each is commonly used to iterate through each element of an array, string, or collection without the elements' indices. There are some limitations to its use, but it makes the code more readable and allows us to avoid the ArrayIndexOutOfBoundsException
.