Multi-dimensional Arrays .edu



Multi-dimensional ArraysJava, like most high level programming languages, supports multi-dimensional arrays. Recall that a one-dimensional 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 one-dimensional 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 one-dimensional, 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.Figure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 20 A table of values504 rows3 columns103520510369Whereas this might be a convenient way to view it, this is not how two-dimensional arrays are stored in memory. They are stored as array of references, as shown in Figure 8.21.Array of referencesFigure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 21 Representing table as 2-dimensional array50510103520246369arrFigure 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.36951015rowscolumnsdepthFigure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 22 Data being represented in a cuboid formIn 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 arrrowreferencescolumn referencesSix linear arrays of dataFigure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 23 Representing a three dimensional arrayHigher 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.Figure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 24 Representing n-dimensional arraysarrTwo-dimensional ArraysAs 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: orordata_type [ ][ ] arr;data_type [ ] arr[ ]; 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 ColumnsThe 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 STYLEREF 1 \s 8. SEQ Example \* ARABIC \s 1 8 Write the necessary Java code that will create a two-dimensional integer array of three rows and five columns.SolutionLet 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).000000000000000Figure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 25 Default values loaded in each cell of the arrayAccessing 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].lengthrefers to the ith reference (same as the ith row) of the two-dimensional array, number; and the expression: number[i][j]refers to the cell of the jth column in the ith row of the array. Figure 8.26 shows values loaded in the array.[2][0][1][4][3]1520105025912631510011Figure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 26 Values loaded in each cell of the arraynumber[1][0][2]number[1][3]In the figure we have singled out one cell of the array with value 12. The expression to retrieve this value is: 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 ColumnsWith 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.6421510563arrReferences (rows)Unequal size linear arrays3025208Figure 8. SEQ Figure \* ARABIC \s 1 31 Variable size (jagged) arraysThe 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 ith 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 STYLEREF 1 \s 8.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: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.SolutionTo 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 store1801501202501805525085qbcstates 180Figure STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 32 Variable size (jagged) arraysIn 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. public class QBCEmployment {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 stateint stores[][] = new int[no_of_states][]; // No. of employees per store per stateListing STYLEREF 1 \s 8. SEQ Listing \* ARABIC \s 1 22 Creation of arrays – The array called stores creates only referencesAs 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.for (int i = 0; i < states.length; i++) // Read and store names of statesstates[i] = GetData.getString("Enter name of state");System.out.println("States in which company operates");for (String s: states) // Display the names of the statesSystem.out.println(s + "\t");Listing STYLEREF 1 \s 8. SEQ Listing \* ARABIC \s 1 23 Load and display the names of statesThe 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.for (int i = 0; i < stores.length; i++){int x = GetData.getInt("Enter number of stores in " + states[i]);stores[i] = new int[x]; // Create array of stores in each state}for (int i = 0; i < stores.length; i++) // Display number of stores in each stateSystem.out.println("No of stores in " + states[i] + " " + stores[i].length);Listing STYLEREF 1 \s 8. SEQ Listing \* ARABIC \s 1 24 Second dimension creates arrays of varying sizesThe 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. for (int i = 0; i < states.length; i++){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 STYLEREF 1 \s 8. SEQ Listing \* ARABIC \s 1 25 Using nested loop to store number of employees per store per stateNow that the arrays have been loaded, Listing 8.26 shows the calculations, and displays the results.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 statefor (int i = 0; i < stores.length; i++)System.out.println("No of employees in " + states[i] + " is " + employees[i]);}}Listing STYLEREF 1 \s 8. SEQ Listing \* ARABIC \s 1 26 Completion of the programThat is, beginning with Line 35, the sum of the number of employees per state is calculated. In this case 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 STYLEREF 1 \s 8. SEQ Figure \* ARABIC \s 1 33 Illustrating variable size arrays, called jagged arrays ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download