Menu
Coddy logo textTech

Common 2D Array Patterns

Part of the Logic & Flow section of Coddy's Java journey — lesson 8 of 59.

Certain patterns often appear when working with 2D arrays. Recognizing these patterns can help you solve problems more efficiently. Here are a few common patterns:

Diagonal Traversal

Accessing elements where the row index equals the column index (matrix[i][i]) gives you the main diagonal. For the anti-diagonal, the sum of the row and column indices equals the size of the array minus 1 (matrix[i][size - 1 - i]).

For example:

1  2  3
4  5  6
7  8  9

Traverse through main diagonal (matrix[i][i]): 1, 5, 9
Traverse through anti-diagonal (matrix[i][size - 1 - i]): 3, 5, 7

Border Traversal

To traverse the border elements, you keep one index constant (0 or size - 1) while iterating over the other.

To access the top border, you iterate over columns with the row index fixed at 0.

For example:

1  2  3  4
5  6  7  8
9 10 11 12

border elements: 1, 2, 3, 4, 8, 12, 11, 10, 9, 5 (all except 6 and 7)

challenge icon

Challenge

Easy

Create a method named printPatterns that takes a square 2D array of integers (matrix) as input and prints the following patterns:

  1. Main Diagonal: Print all elements where the row index equals the column index.
  2. Anti-Diagonal: Print all elements where the sum of the row and column indices equals the size of the matrix minus 1.
  3. Borders: Print the elements of the top, bottom, left, and right borders of the matrix.

The output should look like this:

Main Diagonal: 1 6 11 16 
Anti-Diagonal: 4 7 10 13 
Top Border: 1 2 3 4 
Bottom Border: 13 14 15 16 
Left Border: 1 5 9 13 
Right Border: 4 8 12 16

Cheat sheet

Common 2D array traversal patterns:

Diagonal Traversal

Main diagonal: matrix[i][i] (row index equals column index)

Anti-diagonal: matrix[i][size - 1 - i] (sum of row and column indices equals size - 1)

1  2  3
4  5  6
7  8  9

Main diagonal: 1, 5, 9
Anti-diagonal: 3, 5, 7

Border Traversal

Keep one index constant (0 or size - 1) while iterating over the other:

  • Top border: row = 0, iterate columns
  • Bottom border: row = size - 1, iterate columns
  • Left border: column = 0, iterate rows
  • Right border: column = size - 1, iterate rows

Try it yourself

// Write your code only inside the class. Do not write main() or any code outside this class.
class PrintPatterns {
    public static void printPatterns(int[][] matrix) {
        // Write your code here
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow