Full Header Image

Chapter 11: Multidimensional Arrays

This chapter expands on the knowledge discussed about arrays in Chapter 9. You will learn about multidimensional arrays, starting with two-dimensional arrays.

The arrays and ArrayLists in the previous two chapters were all one-dimensional arrays. You can think of them like a linear structure of data, where each element in the array comes directly after the element before it.

Multidimensional arrays are arrays that occupy over one dimension. The simplest multidimensional array is a two-dimensional (2D) array. You could think of this like a table, with rows and columns, instead of just one single line.

1D/2D Array Example
1D/2D Array Visualization

2D Arrays

two-dimensional array is a data structure with two dimensions. You can think of it as a table with rows and columns. Keep in mind that data structures are abstract computer concepts. Your computer does not implicitly know what part of the index represents a “row” or the “column.” How you structure your array is entirely up to you.

2D arrays are created much like 1D arrays. The difference is the amount of indices defined.

//creating a 1D array
int[] myArray = new int[6];

//creating a 2D array 6x4 (total 24 values)
int[][] myBiggerArray = new int[6][4];Code language: JavaScript (javascript)

In the example below, a 3×2 array is created. The first index can be thought of as the row in the table, where each row is a different student. The second index is the column – the first column being the student’s ID number and the second column being their grade. There are 3 rows of students in this array, and 2 columns, so it’s a 3×2 array with a total of six int values.

Student Grades Example
public static void main(String[] args) {

    //a new three by two array
    int[][] studentGrades = new int[3][2];

    //the first index for each student, the second for the different values associated with them (id and grade)
    studentGrades[0][0] = 432;
    studentGrades[0][1] = 92;
    studentGrades[1][0] = 433;
    studentGrades[1][1] = 75;
    studentGrades[2][0] = 435;
    studentGrades[2][1] = 88;

    //print out the student ids and their grades
    for(int i = 0; i < 3; i++){
        System.out.println("The student with ID number: " + studentGrades[i][0] + " has a grade of " + studentGrades[i][1] + "%");
    }

}Code language: JavaScript (javascript)
Terminal
The student with ID number: 432 has a grade of 92%
The student with ID number: 433 has a grade of 75%
The student with ID number: 435 has a grade of 88%

Extra Grades

Now, let’s examine a situation in which we want to add multiple grades to the array, rather than just one. The first column will remain the student’s id, the second their English grade, followed by their Math and Science grades.

There is no need to create a three-dimensional array. We are just adding more columns to the existing 2D array.

The same three students will be kept from the previous example. So we need to create a 3×4 array,

//a new three by four
int[][] studentGrades = new int[3][4];

//the first index can hold the student's id number, the second, their grade.
studentGrades[0][0] = 432;
studentGrades[0][1] = 92;
studentGrades[0][2] = 87;
studentGrades[0][3] = 97;
studentGrades[1][0] = 433;
studentGrades[1][1] = 75;
studentGrades[1][2] = 80;
studentGrades[1][3] = 96;
studentGrades[2][0] = 435;
studentGrades[2][1] = 88;
studentGrades[2][2] = 92;
studentGrades[2][3] = 69;

//print out the student ids and their grades
for(int i = 0; i < 3; i++){
    System.out.println("The student with ID number: " + studentGrades[i][0] + " has a grade of " + studentGrades[i][1] + "% in English, " + studentGrades[i][2] + "% in Math, " + studentGrades[i][3] + "% in Science.");
}Code language: JavaScript (javascript)
Terminal
The student with ID number: 432 has a grade of 92% in English, 87% in Math, 97% in Science.
The student with ID number: 433 has a grade of 75% in English, 80% in Math, 96% in Science.
The student with ID number: 435 has a grade of 88% in English, 92% in Math, 69% in Science.

.length

Using .length returns the static value holding the length of an array. In the above example, it will return 3, as that is the length of the first dimension of the array. To get the length of the second dimension, you need to add a blank [0] to the reference variable. In the 3×4 array, studentGrades.length returns 3, and studentGrades[0].length returns 4.

Sample Problem

Directions: Using the 3×4 array from the above extra grades section (you may just copy/paste it into a project), create an algorithm that finds each student’s average grade across all three subjects, and prints it to the screen. Do this using an outer loop which iterates through the students, and an inner loop that iterates through the grades.

Sample Output:

Student with id: 432 has an average grade of: 92.0%
Student with id: 433 has an average grade of: 83.66666666666667%
Student with id: 435 has an average grade of: 83.0%
View Solution

Shorthand Syntax

Recall that a 1D array can be declared, initialized, and populated with values using this shorthand syntax:

int[] myArray = {5, 10, 15, 20, 25};

The same can be done with 2D arrays. In this example, a 2×3 array is created using shorthand syntax.

int[][] anotherArray = {{5,10,15},{10,20,30}};

The outer part of the array {A,B} is the first dimension of the array. The inner part {{x,y,z},{x,y,z}} is the second dimension.

//this array is functionally equivalent
int[][] anotherArray = {{5,10,15},{10,20,30}};

//to this array
int[][] anArray = new int[2][3];
anArray[0][0] = 5;
anArray[0][1] = 10;
anArray[0][2] = 15;
anArray[1][0] = 10;
anArray[1][1] = 20;
anArray[1][2] = 30;Code language: JavaScript (javascript)

Another way to format the 2D array with shorthand is to separate the first dimension of elements by line, and the second element into rows. This way may be more visually pleasing and easy to understand.

int[][] anotherArray = {
	  {5,10,15},
	  {10,20,30}
};

Table Printer Assignment

Instructions: Look at the table of Strings below. Take the information in the table cells, place them in an array, and print the table to the screen in a nicely formatted manner. Use vertical bars | to create the edges of the cells.

Define the array in the main method, then print the array using a separate method. A basic template is provided below.

To keep each column the same width, you may add spaces to the end of the strings, so each string in the column has the same width of characters.

NameFav ColorFav FoodFav Place
JackVioletTacosBeach
SammyBlackSushiNew York
JoeyGreenSteakJapan

Sample Output:

Terminal
|Name |Fav Color|Fav Food|Fav Place|
|Jack |Violet   |Tacos   |Beach    |
|Sammy|Black    |Sushi   |New York |
|Joey |Green    |Steak   |Japan    |

Starting Code

Here is some code to help you get started.

public class Main {
    public static void main(String[] args) {

        //Create the Array
        String studentData[][] = {
                //data here
        };

        tablePrinter(studentData);

    }

    /**
     * @param arr The array being printed to the screen in a nicely formatted manner
     */
    public static void tablePrinter(String[][] arr) {


    }

}Code language: JavaScript (javascript)
View Solution

3D Arrays

Adding a third dimension to an array works the same way as a 2D array. Visually, you can think of a 3D array like a cube.

In the illustration, the first index is the plane or depth of the array, the second is the row, and the third is the column.

Creating a 3D array is the same as a 1D or 2D array, with the extra brackets for the extra indices.

//a 3x4x4 array
int[][][] array = new int [3][4][4];Code language: PHP (php)

Yearly Gradebook Example

Below is a 3D array created with shorthand syntax. It contains the grades of 3 senior students, in four different subjects, across the past 4 years. So the three dimensions are year, student, and subject.

int grades[][][] = {
        //year zero
        {   //student 0   student 1       student 2
            {89,95,85,93},{99,82,95,90},{91,87,90,77}
        },
        //year one
        {   //student 0   student 1       student 2
            {90,90,88,90},{92,87,86,89},{95,95,90,87}
        },
        //year two
        {   //student 0   student 1       student 2
            {90,80,90,75},{85,81,79,81},{99,98,90,89}
        },
        //year three
        {   //student 0   student 1       student 2
            {92,82,81,78},{89,81,74,85},{97,85,89,90}
        }
};Code language: JavaScript (javascript)

The way it’s setup, the first index is the year from 0 to 3, where 0 is the current year and 3 is 3 years ago. The second index is the student, numbered 0 through 2, for a total of 3 students. The third index is the subject, 0 for Math, 1 for English, 2 Science, and 3 History. The array may be used to access the grades of any of the three students in any of the four subjects across the past four years.

System.out.println("Second student's grade in English from 3 years ago:");
System.out.println(grades[3][1][1]);

System.out.println("First student's grade in Math from this year:");
System.out.println(grades[0][0][0]);Code language: JavaScript (javascript)

Chapter Assignment: Gradebook

Instructions: Create a simple Gradebook program. The program will contain a 2D array of Strings. It will be 50×5, so 50 rows and 5 columns. Each row will correspond to the student’s ID, starting with zero (so do not create a separate column to store an arbitrary ID). Since there are 50 rows, it supports a maximum of 50 students. Column zero will be their name, 1 will be Math grade, 2 is English grade, 3 is Science grade, and 4 is History grade.

The program will have the following capabilities:

  1. List all students and their grades from the Gradebook
  2. Add a new student, with their name and grade in each subject
  3. Modify an existing student based on their ID number, updating their name and grades.
  4. Calculate the GPA of the student’s four grades, as an average.

Assumptions: When entering data, we can assume that the user always types the correct value. There is no need to do extensive error checking or “idiot proofing”. The gradeBook may use public/static variables to keep track of student grades, and the number of students in the book. These are not the best practices, but we want to get a functioning gradebook, illustrating that you understand 2D array concepts.

The grades will be stored in String format, so our grade book can contain both student names and their grades. You may convert the grades back to double format by using the following method:

The program will not save any data locally once the program terminates.

//Convert String to Double
double aDouble = Double.valueOf(STRING);Code language: JavaScript (javascript)
View Starter Code
View Sample Output
View Complete Solution
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments