Multi-dimensional Arrays

advertisement

Multi-dimensional Arrays

Java, like most high level programming languages, supports multi-dimensional arrays. Recall that a onedimensional array is a set of contiguous memory locations that are referenced by a single variable. In the cases of multi-dimensional arrays, they are arrays of references; and each reference eventually references an array of values. The general format denoting a multi-dimensional array is: dt arr [ ][ ][ ]…..

Where dt represents the type of data that the array will store; arr, is the name of the array; and the series of square bracket pairs, denotes the dimension of the array. A single square bracket pair denotes a onedimensional array; a two square bracket pair denotes a two-dimensional array; a three square bracket pair denotes a three-dimensional array; and so forth, and so on. The most commonly used arrays are onedimensional, two-dimensional, and three-dimensional; higher dimensional arrays are less frequently used.

Two-dimensional arrays are usually represented as a table of values. Figure 8.20 shows a table of values, as structured in Mathematics. In this case the table has four rows running horizontally, and three columns running vertically, making this a 4 by 3 table.

3 columns

4 rows

10

50

3

35

5

6

20

10

9

Figure Ошибка! Текст указанного memory. They are stored as array of references, as shown in Figure 8.21. arr

Array of references

10 35 20

50

2

5

4

10

6

3 6 9

Figure Ошибка! Текст указанного стиля в документе отсутствует..2 Representing table as 2-dimensional array

Figure 8.21 on the other hand shows the array representation of this table.

In this representation, the row is represented as an array of four references; and each reference is a linear array of its respective set of values. Each value of the linear array is a representation of a column. The entire array is referred to by one name, arr.

In Mathematics, three dimensional arrays are frequently viewed as cuboids of data with rows, columns, and depth, as shown in Figure 8.22.

row s

3

5

6

10

9

15 depth columns

Figure Ошибка! Текст указанного стиля в документе отсутствует..3 Data being represented in a cuboid form

In programming they are viewed as array of references; where each reference stores another array of references; and each of these references contains a linear array of data. The entire system is by a single name.

See Figure 8.23 arr row references column references

Six linear arrays of data

Figure Ошибка! Текст указанного стиля в документе отсутствует..4

Representing a three dimensional array

Higher dimension arrays, called n-dimensional arrays, are treated as trees, with the name of the array being the root of the tree, and as the array of references grow, they fan out into limbs, and finally into leaves.

The leaves represent the data. Figure 8.24 is a partial representation of an n-dimensional array.

arr

Figure Ошибка! Текст указанного стиля в документе отсутствует..5

Representing n-dimensional arrays

Two-dimensional Arrays

As stated in the previous section, a two dimensional array is an array of references. Each reference serves as a reference to a linear array of values. Before we attempt to create the array, we must first declare it. The format for declaring a two-dimensional array satisfies any of the following three forms: data_type [ ][ ] arr; or data_type [ ] arr[ ]; or data_type arr[ ][ ];

Once the array variable has been declared, the next step is to create the array. There are two ways to create a two-dimensional array; one in which the number of columns are the same, and the other where the number of columns may vary. The second form is sometimes referred to as variable length array, or jagged array.

CreatingTwo-dimensional Arrays of Equal Columns

The general format for creating a two-dimensional of equal columns is as follows: arr = new data_type[m][n];

Where m, represents the number of references (same as rows), and n represents the number of columns for each reference.

Example Ошибка! Текст указанного стиля в документе отсутствует..1 Write the necessary Java code that will create a two-dimensional integer array of three rows and five columns.

Solution

Let us call the array, numbers. Using the format outline above, the required code is as follows: int numbers[ ][ ] = new int[3][5];

Figure 8.25 shows the organization of the array in memory. In this illustration we can see that the array is referenced by the variable, numbers. The variable, numbers, in turn references a linear array of three references; and each of these references in turn creates its respective linear array of five cells of values.

Because the array is an integer (int) array, each cell is initialized with its default value of zero (0).

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

Figure Ошибка! Текст указанного стиля в документе отсутствует..6 Default values loaded in each cell of the array

Accessing Two-dimensional Arrays

When processing two-dimensional arrays, it is almost unavoidable to use nested loops. In addition, of the three loop constructs, the for loop is usually the one of choice. It is most favored because the conditional expression that governs the behavior of the loop depends on the size of the array. Usually the outer loop controls the rows, and the inner loop controls the columns. In the example above, the expression: number[i].length refers to the i th reference (same as the i th row) of the two-dimensional array, number; and the expression: number[i][j] refers to the cell of the j th column in the i th row of the array.

Figure 8.26 shows values loaded in the array. number

[0] [1] [2] [3] [4]

[0]

50 10 15 20 25

[1] 3 6 9 12 15

[2]

1 0 1 0 1

Figure Ошибка! Текст указанного стиля в документе отсутствует..7 Values loaded in each cell of the array

In the figure we have singled out one cell of the array with value 12. The expression to retrieve this value is: number[1][3]

If we were to display all the values in the third row, then the code would go something like this: for (int i = 0; i < number[2].length; i++)

System.out.println(number[2][i]);

In general, if we were to display the entire contents of the array, the necessary Java code would be as follows: for (int i = 0; i < number.length; i++)

{ for (int j = 0; j < number[i].length; j++)

System.out.println(number[i][j]);

System.out.println();

}

CreatingTwo-dimensional Arrays of Unequal Columns

With respect to multi-dimensional arrays, Java makes provision for variable size arrays, sometimes called jagged arrays. Figure 8.31 shows what a two-dimensional variable size array looks like. arr

References

(rows)

Unequal size linear arrays

2 4 6 8

5

3

10

6

15 20 25 30

Figure Ошибка! Текст указанного стиля в документе отсутствует..8

Variable size (jagged) arrays

The figure shows that the first reference, arr, has three references. The first of the three references has a linear array of four cells. The second reference has an array of six cells; and the last has an array of two cells.

The expressions to determine the size and to manipulate a jagged array, are the same as an array of uniform size.

Like one-dimensional arrays, two dimensional arrays can be loaded using array initializer. The general format is a follows:

dt arr[][] = { { ………}, {………..}, {…………..}, …………………..,{………..} }; arr[0] arr[1] arr[2] arr[n-1]

In this arrangement, the outer pair of parentheses denotes the entire array, and each inner pair of curly braces represents a linear array to that reference. Hence, arr[0] refers to the fist array; arr[1], the second array; arr[2], the third array; and so forth, and so on. If there are n, number of references, then the last array would be reference by arr[n-1]. This being the case, it is not difficult to see that each reference could have an array of different number of values. With this in mind, the Java code to create an array depicted in Figure 8.31 is as follows: int arr { {2, 4, 6, 8}, {5, 10, 15, 20, 25, 30}, {3, 6} };

The following segment of codes displays the contents of each array on a separate line. for (int i = 0; i < arr.length; i++)

{ for (int j = 0; j < arr[i].length; j++)

System.out.print(arr[i][j] + "\t");

System.out.println();

}

The enhanced for loop can also be used on variable size array, as shown in the following segment of codes.

The implied conditional expression of the inner for loop looks at the length of the i th array; as such the loop is executed only that many number of times. for (int i []: arr)

{ for (int j :i)

System.out.print(j + "\t");

System.out.println();

}

Example Ошибка! Текст указанного стиля в документе отсутствует..11 QBC has a chain of stores in different states across the country. The number of stores may vary from state to state. Write a Java program that:

(a)

(b)

(c)

(d)

(e)

(f)

Reads and stores the names of the states in an array.

Create an array corresponding to the number of states that has stores in them.

Create arrays of stores per state.

Read and store the sales amount for each store in each state.

Calculate the gross sales for each state.

Tabulate the sales amount and the totals in the same array.

Solution

To make the program as general as possible, we will read the number of states, the number of stores in each state, and the number of employees in each store. With this analysis, we can implement a two dimensional array to model this situation.

As an example, let’s say that the company operates in three states ( Florida, Georgia, and Hawaii); and that there are three stores in Florida, two in Georgia, and four in Hawaii. Finally, the number of employees in each store in Florida are 120, 150, and 180; the number in Georgia 55 and 180; and the number in Hawaii 85,

250, 180, and 250.

Figure 8.32 shows the two-dimensional jagged array that models the solution to the problem.

Number of employees per store qbc states

120 150 180

55

85

180

250 180 250

Figure Ошибка! Текст указанного стиля в документе отсутствует..9

Variable size (jagged) arrays

In the figure, we see that the array variable, qbc, references an array of three references. These references model the number of states in which the company operates. Each reference (state) in turn is a reference to an array of stores. The number of stores as we see varies from state to state; and each store, the number of employees. This model as we see is a jagged array.

Listing 8.22 shows the implementation of this model.

5.

6.

7.

8.

1.

public class QBCEmployment

2.

{

3.

4.

public static void main(String[] args)

{ int no_of_states = GetData.getInt("How many states are you operating in?");

String states[] = new String[no_of_states]; // Stores names of states int employees[] = new int[no_of_states]; // Number of employees in each state int stores[][] = new int[no_of_states][]; // No. of employees per store per state

Listing Ошибка! Текст указанного стиля в документе отсутствует..1 Creation of arrays – The array called stores creates only references

As we see Line 5 reads the number of states in which the company operates, and Line 6 creates a string array to store the names of the states. Line 7 creates a linear array to store the sum of all employees in each state. Finally, Line 8 creates a partial two-dimensional array that will store the data. We say partial array because it has created only the references for the states. Each reference will create the linear array of values.

Listing 8.23 reads and displays the names of states that are involoved.

10.

for (int i = 0; i < states.length; i++) // Read and store names of states

11.

states[i] = GetData.getString("Enter name of state");

12.

13.

System.out.println("States in which company operates");

14.

for (String s: states) // Display the names of the states

15.

System.out.println(s + "\t");

Listing Ошибка! Текст указанного стиля в документе отсутствует..2

Load and display the names of states

The for loop of Line 10 reads the names of the states and stores them in the array called states. The for loop of Line 14 simply displays the names of the states.

Figure 8.24 creates second dimension of varying sizes.

17.

for (int i = 0; i < stores.length; i++)

18.

{

19.

20.

int x = GetData.getInt("Enter number of stores in " + states[i]); stores[i] = new int[x]; // Create array of stores in each state

21.

}

22.

23.

for (int i = 0; i < stores.length; i++) // Display number of stores in each state

24.

System.out.println("No of stores in " + states[i] + " " + stores[i].length);

Listing Ошибка! Текст указанного стиля в документе отсутствует..3

Second dimension creates arrays of varying sizes

The block of statements in the for loop of Line 17 reads the integer value representing the number of stores in each state, and uses this number to create the array of stores in each state. This has the potential of creating variable sizes of linear arrays. The for loop of Line 23 displays the number of stores in each state.

Listing 8.25 reads the number of employees per store per state and stores these values in the respective array.

26.

for (int i = 0; i < states.length; i++)

27.

{

28.

29.

30.

31.

32.

33.

} for (int j = 0; j < stores[i].length; j++)

{

String s = "Enter number of employees from store " + (j+1) + " in " + states[i]; stores[i][j] = GetData.getInt(s); // Read and store number of employees

}

Listing Ошибка! Текст указанного стиля в документе отсутствует..4 Using nested loop to store number of employees per store per state

Now that the arrays have been loaded, Listing 8.26 shows the calculations, and displays the results.

43.

44.

45.

46.

47.

48.

49.

50.

35.

36.

37.

38.

39.

40.

41.

42.

51.

52.

53.

54.

55.

56.

57.

}

} for (int i = 0; i < stores.length; i++) // Sum number of employees in each state

{ int total = 0; for (int j = 0; j < stores[i].length; j++) total = total + stores[i][j]; employees[i] = total;

}

System.out.println("\nNumber of employees per store"); for (int i = 0; i < stores.length; i++)

{

System.out.print(states[i] + "\t" ); for (int j = 0; j < stores[i].length; j++)

System.out.print(stores[i][j] + "\t\t");

System.out.println();

}

System.out.println(); // Display total number of employees in each state for (int i = 0; i < stores.length; i++)

System.out.println("No of employees in " + states[i] + " is " + employees[i]);

Listing Ошибка! Текст указанного стиля в документе отсутствует..5 Completion of the outer for loop controls the states, and the inner loop controls stores per state. The result of each row is stored in the linear array called employees. The for loop of Line 45 displays the jagged array of the number of employees in each store. Finally, the total number of employees per store, per state is displayed by the for loop of Line 54.

Figure 8.33 shows the output from the program.

Figure Ошибка! Текст указанного стиля в документе отсутствует..10

Illustrating variable size arrays, called jagged arrays

Download