← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 5 of 15

C++ Multi-dimensional Arrays

Two-Dimensional Arrays

A two-dimensional array models grid-shaped data — like a spreadsheet, a game board, or a matrix — by organizing values into rows and columns, and it's conceptually just an array where each element is itself another array. Declaring int grid[3][4] creates 3 rows, each containing 4 columns.

Example: Two-Dimensional Arrays

cpp
#include <iostream>

int main() {
	int grid[2][3];
	grid[0][0] = 1;
	std::cout << grid[0][0] << std::endl;
	return 0;
}

Initializing 2D Arrays

Nested curly braces let you initialize a 2D array row by row, like int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};, which visually mirrors the actual grid structure and makes it obvious at a glance which values belong to which row.

Example: Initializing 2D Arrays

cpp
#include <iostream>

int main() {
	int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
	std::cout << grid[1][2] << std::endl;
	return 0;
}

Accessing Elements in 2D Arrays

Reaching a specific element requires two indices in separate brackets, like grid[row][col], with both dimensions counted from zero just like a regular one-dimensional array. Mixing up the row and column order is a common bug, especially when a grid isn't square.

Example: Accessing Elements in 2D Arrays

cpp
#include <iostream>

int main() {
	int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
	std::cout << grid[0][1] << std::endl;
	return 0;
}

Modifying Elements in 2D Arrays

Updating a cell in a 2D array works exactly like a 1D array, just with two indices instead of one — grid[1][2] = 99; changes only that single coordinate, leaving every other element untouched.

Example: Modifying Elements in 2D Arrays

cpp
#include <iostream>

int main() {
	int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
	grid[1][2] = 99;
	std::cout << grid[1][2] << std::endl;
	return 0;
}

Looping Through 2D Arrays

Visiting every element of a 2D array requires nested loops: the outer loop advances through rows one at a time, and for each row, the inner loop advances through every column in that row. This nested structure directly mirrors the 2D array's own nested layout, which is why it feels like the natural way to traverse it.

Example: Looping Through 2D Arrays

cpp
#include <iostream>

int main() {
	int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
	for (int row = 0; row < 2; row++) {
		for (int col = 0; col < 3; col++) {
			std::cout << grid[row][col] << " ";
		}
	}
	std::cout << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.