Menu
Topics Index
...
`


Array - Overview >
Siva Nookala - 11 Apr 2016
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.
int[] scores = new int[4];
scores[0] = 250;
scores[1] = 243;
scores[2] = 176;
scores[3] = 220;

System.out.println("Team 0 = " + scores[0]);
System.out.println("Team 1 = " + scores[1]);
System.out.println("Team 2 = " + scores[2]);
System.out.println("Team 3 = " + scores[3]);
int total = scores[0] + scores[1] + scores[2] + scores[3];
System.out.println("Total = " + total);
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.
Print team scores and total score
class PrintTeamScores
{
    public static void main(String arg[])
    {
        int[] scores = new int[4]; // LINE A
        scores[0] = 250;
        scores[1] = 243;
        scores[2] = 176;
        scores[3] = 220; // LINE B
        
        // LINE C
        int total = 0;
        for(int i = 0; i < scores.length; i++)
        {
            System.out.println("Team " + i + " = " + scores[i]);
            total += scores[i];
        }
        System.out.println("Total = " + total);    
    }
}
OUTPUT

Team 0 = 250
Team 1 = 243
Team 2 = 176
Team 3 = 220
Total = 889

DESCRIPTION

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 6 i.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.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.