In Java, we can also loop through each element of the array. For example,
The output for the above program is
In the above example, we are using the for Loop in Java to iterate through each element of the array. Notice the expression inside the loop, age.length; Here, we are using the length property of the array to get the size of the array. We can also use the for-each loop to iterate through the elements of an array. For example,
The output will be as follows
The output will be
In the above example, we have created an array of named numbers. We have used the for...each loop to access each element of the array. Inside the loop, we are calculating the sum of each element. Notice the line, int arrayLength = number.length; Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using: