Course contentsShow
← Computer Science
Lesson 242 of 2,8726. Arrays and Basic CollectionsFree lesson

2D Array Basics and Declaration

Understand two-dimensional arrays as arrays of arrays, their declaration syntax, and memory layout in row-major order.

2D Array Basics and Declaration

What you'll learn: How two-dimensional arrays work as "arrays of arrays" and how to declare them in code.

Arrays of Arrays

You already know that an array is a collection of elements stored in consecutive memory locations. A two-dimensional (2D) array takes this one step further—it's literally an array whose elements are themselves arrays.

Think of it like a spreadsheet or a grid: rows and columns. Each row is an array, and the entire structure is an array of those rows.

Declaration Syntax

To declare a 2D array, you specify two sizes: the number of rows and the number of columns.

# Python: list of lists
grid = [[1, 2, 3],
        [4, 5, 6]]
// Java: array of arrays
int[][] grid = new int[2][3];  // 2 rows, 3 columns
// C: array of arrays
int grid[2][3];  // 2 rows, 3 columns

The first number is the row count, the second is the column count.

Memory Layout: Row-Major Order

In memory, 2D arrays are stored linearly (in a straight line), not actually as a grid. Most languages use row-major order, meaning the first row is stored completely, then the second row, and so on:

grid[0][0], grid[0][1], grid[0][2], grid[1][0], grid[1][1], grid[1][2]

Even though you think of it as rows and columns, the computer lays it out sequentially, row by row.

Accessing Elements

Use two indices: grid[row][column]. The first index selects the row (which is itself an array), and the second index selects the element within that row.

Key Takeaway: A 2D array is an array of arrays, declared with two dimensions (rows and columns), and stored in memory sequentially in row-major order.