CSA Blog

Ian Wu

Unit 8 - 2D Arrays Traversing

Intro Declaring, Initializing Accessing, Updating Traversing Algorithms

Traversing 2D Arrays

  • When traversing through, or looping through 1D arrays, we only need to use one loop to access every element in the array.
  • This is different in 2D arrays, where we need to use a loop inside of a loop, otherwise known as a for loop
  • Java for loop structure review: ```java for(first execution; condition; executed after every loop) { //Action }

ex. for(i = 0; i < 5; i++) { System.out.println(i); }

Prints out 0 1 2 3 4

(Remember base 0)


- How can we use these to traverse through 1D arrays?


Lets say we have an array, Array1...


```java
// Set variable i to 0, while i is less than the length of Array1, print the value of Array1[i], add 1 to i
int[] Array1 = {1, 2, 3};
for(int i = 0; i < Array1.length; i++){
    System.out.println(myArray[i]);
}
  • What about 2D arrays?
    // Create an array of integers with 2 rows, 3 columns
    int[][] Array1 = {
      {1,2,3},
      {4,5,6}
    };
    // Set variable i to 0, while i is less than the length of Array1, proceed to the next for loop, add 1 to i
    for(int i = 0; i < Array1.length; i++){
    // Set variable i1 to 0, while i is less than the length of the array within Array1 at Array1[i], print the value of Array1[i][i1], add 1 to i1
      for(int i1 = 0; i1 < Array1[i].length; i1++){
          System.out.println(Array1[i][i1]);
      }
    }
    

Put in simpler terms?

For every row, loop through the row x number of times, x being the length of the array, print each individual value. So this code, without the loops, would be:

System.out.println(Array1[0][0])
System.out.println(Array1[0][1])
System.out.println(Array1[0][2])
// Keeping in mind base 0 system, and that Array1 has 3 columns for each row
// Move on to the next row
System.out.println(Array1[1][0])
System.out.println(Array1[1][1])
System.out.println(Array1[1][2])
// Again, keeping in mind that Array1 has 2 rows, and base 0 system, so "1st row" is actually 2nd put in plain english

Lets try!

public class Main {
    public static void main(String[] args) {
        int[][] Array1 = {
            {1,2,3},
            {4,5,6}
        };
        // Set variable i to 0, while i is less than the length of Array1, proceed to the next for loop, add 1 to i
        for(int i = 0; i < Array1.length; i++){
        System.out.println("Row " + (i+1) + ", or " + i);
        // Set variable i1 to 0, while i is less than the length of the array within Array1 at Array1[i], print the value of Array1[i][i1], add 1 to i1
            for(int i1 = 0; i1 < Array1[i].length; i1++){
                System.out.println(Array1[i][i1]);
            }
        }
    }
}


Main.main(null)

Row 1, or 0
1
2
3
Row 2, or 1
4
5
6

Popcorn Hack

Let’s say you have an array Numbers[][] defined as:

int Numbers[][] = {
    {1,2,3},
    {4,5,6},
    {7,8,9},
};

Loop through it until you reached a certain number of your choice, then print the value and position

int[][] numbers = {
    {1,2,3},
    {4,5,6},
    {7,8,9}
};
    
for (int[] list : numbers) {
    for (int number : list) {
        if ((number ^ 5) == 0) {
            System.out.println(number);
        }
    }
}

5

Example output: 9 is at row 3 column 3

What if you want to go column-first?

Introducing: Column Major Order, as an alternative to Row Major Order

Put simply, all you have to do is reverse the order of the loops, and keep the insides intact, and use the length of a row for the number of times to loop instead of the length of a column.

Why/how does this work?

Now instead of looping once for every row by taking the number of elements in the array, which defines how many rows there, we instead loop once for every element in each element in the array, (ex. an array with an element {1, 2, 3} would loop 3 times) which defines how many columns there are. Then, we print out the value from the chosen column, represented by i1, and then increment the row value, i, to finish out the rest of the column. Then, i1, the column value, is incremented, and the value repeats. We reverse the order of the loops so that the column is prioritized, and make the changes accordingly.

public class Main {
    public static void main(String[] args) {
        int[][] Array1 = {
            {1,2,3},
            {4,5,6}
        };
        // Set variable i to 0, while i is less than the length of Array1, proceed to the next for loop, add 1 to i
        for(int i1 = 0; i1 < Array1[0].length; i1++){
            System.out.println("Column " + (i1+1));
            for(int i = 0; i < Array1.length; i++){
                System.out.println(Array1[i][i1]);
            }
        }
    }
}


Main.main(null)
Column 1
1
4
Column 2
2
5
Column 3
3
6

Unit 8 - 2D Arrays Intro - P1

Intro Declaring, Initializing Accessing, Updating Traversing Algorithms

Learning Objectives

The objective of this lesson is to…

  • Learn about 2D arrays, their use cases, and how to create them.

Essential Knowledge

College Board wants you to know…

  • How to declare/initialize 2D arrays.
  • How to determine their size.
  • How to access and update the values of a 2D array.
  • How to traverse/access elements of a 2D array using nested iteration statements.
  • How nested iteration statements can be used to traverse 2D arrays in “row-major order” vs “column-major order.”
  • How to create algorithms that require the use of 2D array traversals.

Warm Up

Answer the following questions as a group or individually. Write down your answers in your hacks notebook.

  • What are 2D arrays?

2D Arrays are arrays with an extra dimension. They are data structures in Java.

  • How are 2D arrays organized?

2D arrays are organized into rows and columns in a matrix format. There are two indices, one for rows and one for columns.

  • What are some real-world examples of 2D arrays?

Some real-world examples of 2D arrays can be spreadsheets or maybe image processing.

The Basics/Recap

2D arrays, and higher dimension arrays overall, can be thought of as just an array that’s made up of other arrays or an array of arrays. One way of looking at 2D arrays is by thinking of them as a chess board. They have rows and columns, and every element is identified via row or column number or index.

Below is an illustration of a 2D array: 2D Array Image

Warmup (Review)

  • For the following three code cells categorize data + organization
    • Data Bank: Homogenous Data, Heterogeneous Data, Type of Data, Heterogeneous Dimensions, Non-Square
    • Note: Datatypes can be reused