As has been shown in previous chapters, computers only perform simple actions. They cannot perform an action on all the elements in our arrays. For example, a computer cannot sum all the values in an array in a single instruction. What you need to do is think of these tasks so that they can be performed for each value in the array. We can rethink out sum code, so that we think in terms of each number one at a time. With each value, we can add the number to a running total. When this has been performed for each element in the array, you have the sum of all elements in the array.
When you code this, the for loop is the perfect choice. The for loop repeats a block of code a number of times. You can think of it like a counting loop, with it counting from a first index value (0) to the last index value (size - 1). Within the body of the for loop, you can use its control variable to access the current index value. In this way the for loop steps through each of the elements in your array one at a time.
The for loop can be used to loop through the elements of an array
Example
The following code illustrates using for loops to populate and print values from arrays.