C++ Program to Print a 2D Array
Here we will see how to print a 2D array using a C++ program. Below are the examples:
Input: {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}}
Output: 1 2 3
4 5 6
7 8 9
Input: {{11, 12, 13},
{14, 15, 16}}
Output: 11 12 13
14 15 16
There are 2 ways to print a 2D array in C++:
- Using for loop.
- Using range-based for loop.
Let’s start discussing each of these methods in detail.
1. Using for loop
The general method to print a 2D array using for loop requires two for loops to traverse all the rows and columns of the given 2D matrix and print the elements.
- The outer loop will loop from index 0 to row_length-1.
- It traverses the 2D array row-wise, therefore the first row is printed then it goes to print the second row.
An Example array
Below is the C++ program to print a 2D array using for loop:
C++
#include <iostream>
using namespace std;
int main()
{
const int i = 3, j = 3;
int arr[i][j] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for ( int a = 0; a < 3; a++)
{
for ( int b = 0; b < 3; b++)
{
cout << arr[a][b] << " " ;
}
cout << endl;
}
return 0;
}
|
Time Complexity: O(n*m) where n and m are dimensions of the array.
Auxiliary Space: O(1)
2. Using a Range-Based for loop
Instead of using for loop, this method will use a range-based for loop. Below is the C++ program to print a 2D array using a range-based for loop:
C++
#include <iostream>
using namespace std;
int main()
{
const int i = 3, j = 3;
int matrix[i][j] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
for ( auto &row : matrix)
{
for ( auto &column : row)
{
cout << column << " " ;
}
cout << endl;
}
}
|
Time Complexity: O(n*m) where n and m are dimensions of the array.
Auxiliary Space: O(1)
Last Updated :
19 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...