Home / General programming / JAVA / Arrays and for Loops in JAVA

Arrays and for Loops in JAVA

Arrays and for Loops in JAVA

Arrays and for loops in java have something in common. An array consists of a sequence of data, and the for loop executes a statement a number of times in sequence.
A stair represents very well this common idea. A stair consists of the sequence of steps, an array of steps, if you wish. And to advance through the stairs, you have
to repeat the same movement a number of times in sequence, like in a for loop.
Here we see an array with four integers from 0 to 3.

[ 0 , 1, 2, 3]
for (int i=0; i<4; i=i+1)

And below is the structure of a for loop that repeats a statement four times.
Now, if we want to do the same transformation to all of the values in an array, a for loop seems to be a good way to proceed.

For instance, if we apply the square operation to the integer 3, we get 9.
Now imagine we want to square all the integers in an array.

array for


How do we proceed?

A for loop helps us to visit sequentially all the values in the array and square them, from index 0 to index 3.

Another useful pattern is to reduce an array to a value by successively accumulating the data on some value.

For instance, we want to add up the values in the array, and we can accumulate these values on integer variable z, which is initially 0. We add up successively the data in the array. First 0, then 1, then 2, and finally 3 to get 6 as the final result, which is the sum of all values.

Let’s do this with a for loop.

The counter runs from 0 to 3, incrementing by 1 on each iteration. We accumulate successively the data on z.
If you want this to be right for an array of any length, not just like 4,
we should write x.length instead of 4.

To run through an array with a for loop with index 0 to the length of the array is so common that there is a special for loop for that, the enhanced for loop.

See how simple it is.

In the enhanced for statement,
we can instruct a variable elem to take successively all the elements in an array.
The meaning of this code segment is the same as the one we have seen in the slide before.

We have seen how to traverse an array with a for loop, and we have seen two common patterns, the map, and the reduce pattern.
These names are borrowed from functional programming, which we are not seeing here.

Unhandled error Team – with our love

Leave a Reply

Your email address will not be published. Required fields are marked *