A 2D array in C++ stores elements in rows and columns and can be traversed using nested loops.
The elements can be printed row by row using traditional for loops or range-based for loops.
- The outer loop traverses the rows, while the inner loop traverses the columns.
- Both approaches take O(n × m) time for an array with n rows and m columns.
Examples:
Input: {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output: 1 2 3
4 5 6
7 8 9Input: {{11, 12, 13},
{14, 15, 16}}
Output: 11 12 13
14 15 16
Approaches to Print a 2D Array
A 2D array can be printed using the following approaches:
Printing a 2D Array Using Nested for Loops
The traditional approach uses two nested for loops. The outer loop traverses the rows, and the inner loop traverses the elements of each row.
Steps:
- Start from the first row.
- Traverse each element in the current row.
- Print every element followed by a space.
- Move to the next line after completing a row.
- Repeat until all rows are printed.

#include <iostream>
using namespace std;
int main()
{
const int rows = 3;
const int cols = 3;
int arr[rows][cols] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << arr[i][j] << " ";
}
cout << '\n';
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9
Explanation: The outer loop selects each row, while the inner loop accesses every element in that row. After printing all elements of a row, '\n' moves the output to the next line.
Printing a 2D Array Using a Range-Based for Loop
C++ also provides range-based for loops, which allow direct traversal of the elements without explicitly managing array indices.
Steps:
- Traverse each row using the outer range-based for loop.
- Traverse each element of the current row using the inner loop.
- Print each element.
- Move to the next line after completing each row.
#include <iostream>
using namespace std;
int main()
{
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (const auto& row : matrix)
{
for (const auto& element : row)
{
cout << element << " ";
}
cout << '\n';
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9
Explanation: The outer loop iterates over each row of the 2D array, while the inner loop iterates over the elements in that row. Using const auto& avoids unnecessary copying while keeping the elements read-only during traversal.