Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,


\begin{lstlisting}
class Main {
public static void main(String[] args) {
\par
/...
... 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}
\end{lstlisting}

The output for the above program is


\begin{lstlisting}
Using for Loop:
12
4
5
\end{lstlisting}

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,


\begin{lstlisting}
class Main {
public static void main(String[] args) {
\par
/...
...h Loop:'');
for(int a : age) {
System.out.println(a);
}
}
}
\end{lstlisting}

The output will be as follows


\begin{lstlisting}
Using for-each Loop:
12
4
5
\end{lstlisting}


\begin{lstlisting}
class Main {
public static void main(String[] args) {
\par
i...
... '' + sum);
System.out.println(''Average = '' + average);
}
}
\end{lstlisting}

The output will be


\begin{lstlisting}
Sum = 36
Average = 3.6
\end{lstlisting}

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:


\begin{lstlisting}
average = ((double)sum / (double)arrayLength);
\end{lstlisting}