Arrays are very useful in reducing the number of variables created and in reducing the code complexity. This is because the size of the array can be initialized dynamically and also the elements can be accessed dynamically. We could create an array of any size using run time information or we could access any value using the index.

The usability of the arrays is further enhanced when we use loops, since both arrays and loops use indices, it is very efficient to write programs on arrays using loops.

The above program prints the scores of various teams and also the total of the all teams scores. The same program can be rewritten using for loops as shown below. Unlike the above program, the printing and summing part of the below program will not change, no matter how many teams are present.

Here we created an array scores and initialized the values. In the for loop, we have iterated through every element using index i and printed the scores. Since the length of the array (scores.length), is 4, the loop is executed for the values 0, 1, 2, and 3. While iterating the for loop, we have also updated the total to add the scores. That total is printed after the for loop.

THINGS TO TRY

Add two more teams to the array and initialize them. To do this we need to increase array size from 4 to 6i.e. change LINE A to int[] scores = new int[4]; and also initialize the values scores[4] and scores[5]. See that the code below LINE C need not be changed irrespective of the number of teams.

Change the program to remove the last team, so the array size is 3 instead of 4. We also need to remove LINE B, otherwise we will get ArrayIndexOutOfBoundsException.