Create an Array of Arrays in C++
To create an array of arrays also known as 2D arrays, you can follow the same approach you follow to create a normal one-dimensional array with some minor changes. Like in normal one-dimensional arrays, you define only the number of columns for the array here you will have to define an additional dimension row along with the number of columns. Here is the syntax to create an array of arrays in C++:
Syntax
data_type Arr [rows][columns];
where:
- data_type: denotes the type of data you want to store in the array.
- Arr: is the name of the array of arrays.
- rows: denotes the number of rows in your array of arrays.
- columns: denotes the number of columns in your array of arrays.
C++ Program to Create Array of Arrays
The following program demonstrates how to create array of arrays in C++
// C++ Program to demonstrate how to create array of arrays
#include <iostream>
using namespace std;
int main()
{
// Declare and initialize a 2D array
int arr[3][3]
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
// Print the elements of the array
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9
Time Complexity:O(N*M) where N denotes the number of rows and M denotes the number of columns.
Auxiliary Space:O(N*M)
How to Create Array of Arrays in C++
Arrays are basic C++ data structures that allow users to store the same data type in memory sequentially. To manage more complicated data structures, you may sometimes need to build an array of arrays, often called a 2D array or a matrix. In this article, we will learn how to create an array of arrays in C++.
Contact Us