Print 2D arrays (matrix) in C++
This post will discuss how to print two-dimensional arrays (i.e., matrix) in C++.
A simple solution is to iterate over each row and column of the matrix using a simple for-loop and print each element. The following C++ program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> using namespace std; int main() { const int m = 3, n = 3; int mat[m][n] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { std::cout << mat[i][j] << ' '; } std::cout << std::endl; } return 0; } |
Output:
1 2 3
4 5 6
7 8 9
Here’s an equivalent version using a range-based for-loop. This can be used starting with C++ 11.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <algorithm> using namespace std; int main() { const int m = 3, n = 3; int mat[m][n] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (auto &row: mat) { for (auto &i: row) { std::cout << i << ' '; } std::cout << std::endl; } return 0; } |
Output:
1 2 3
4 5 6
7 8 9
We can also create a template that deduces the size of the array from its declared type.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> using namespace std; template<typename T, size_t N, size_t M> void printArray(T(&mat)[N][M]) { for (int i = 0; i < N; i ++ ) { for (int j = 0; j < M; j++ ) { cout << mat[i][j] << ' '; } std::cout << std::endl; } } int main() { const int m = 3, n = 3; int mat[m][n] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; printArray(mat); return 0; } |
Output:
1 2 3
4 5 6
7 8 9
That’s all about printing two-dimensional arrays in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)