# 16.6: Array Traversal

- Page ID
- 15261

Many computations can be implemented by looping through the elements of an array and performing an operation on each element. For example, the following loop squares the elements of a `double`

array:

for (int i = 0; i < a.length; i++) { a[i] = Math.pow(a[i], 2.0); }

Looping through the elements of an array is called a **traversal**. Another common pattern is a **search**, which involves traversing an array looking for a particular element. For example, the following method takes an `int`

array and an integer value, and it returns the index where the value appears:

public static int search(double[] a, double target) { for (int i = 0; i < a.length; i++) { if (a[i] == target) { return i; } } return -1; }

If we find the target value in the array, we return its index immediately. If the loop exits without finding the target, it returns `-1`

, a special value chosen to indicate a failed search.

Another common traversal is a **reduce** operation, which “reduces” an array of values down to a single value. Examples include the sum or product of the elements, the minimum, and the maximum. The following method takes a `double`

array and returns the sum of the elements:

public static double sum(double[] a) { double total = 0.0; for (int i = 0; i < a.length; i++) { total += a[i]; } return total; }

Before the loop, we initialize `total`

to zero. Each time through the loop, we update `total`

by adding one element from the array. At the end of the loop, `total`

contains the sum of the elements. A variable used this way is sometimes called an **accumulator**.