The multidimensional array, often referred to as a rectangular array in the C++ programming language, can exist in either a two-dimensional or three-dimensional form. Information is organized in a tabular structure, following a row-column format commonly referred to as a matrix. This type of array consists of a uniform group of elements, with each individual item being retrieved using multiple indices.
Syntax of a Multidimensional Array in C++
Introduce a specific notation to demonstrate multidimensional arrays in the C++ language.
data_type array_name[size1][size2]…[sizeN];
- data_type: It specifies the type of elements (e.g., int, float, char).
- size1: Number of rows.
- size2: Number of columns.
C++ Multidimensional Arrays Example
Let's consider a basic example for initializing a multidimensional array in C++.
Example
#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
Output:
5 10 0
0 15 20
30 0 10
In this case, an integer type two-dimensional array is utilized. The array named array1 is defined with a structure of 3 rows and 3 columns, encompassing a total of 9 integer elements.
Size of C++ Multidimensional Arrays
In a singular array, the array's size is determined by multiplying the number of elements with the size of each individual element. In the case of multi-dimensional arrays, each additional dimension contributes to the overall size of the array, increasing the complexity of size calculations. The total quantity of elements is established by multiplying the sizes of all dimensions, resembling the calculation of area in two dimensions and volume in three dimensions.
Consider an example;
int array1[3][2];
- Here, the array int array13 may store the total 6 elements.
- Using the sizeof operator, we can calculate the size of array in bites.
- In this case, size in bytes= 3*8 = 24 bytes.
Code Implementation:
Let's consider an example to demonstrate the dimensions of a multidimensional array in C++.
Example
#include <iostream>
using namespace std;
int main()
{
// creating 2d and 3d array
int arr[3][2];
// using sizeof() operator to get size of arr
cout << " Total no of bytes: " << sizeof(arr);
return 0;
}
Output:
Total no of bytes: 24
2D Arrays in C++
C++ provides 2D arrays that utilize an array-of-arrays arrangement to represent data in tabular formats like matrices and tables. This structure consists of elements arranged in dimensions, identified by two specific indices.
Create a 2D Array in C++:
To define a two-dimensional array in C++, we can utilize the following syntax for initializing a 2D array.
Syntax:
It has the following syntax:
datatype arraynamerows;
- data_type: It specifies the type of elements (e.g., int, float, char).
- Rows: Number of rows.
- Columns: Number of columns.
Example: Declaring a 2D Array
Declares a 3x3 matrix named matrix of type integer.
Initialize a 2D Array:
A 2D array can be initialized in different ways:
a) Initializing at Declaration:
Values are allocated to the elements of the array during their initialization within this function.
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
Resulting Matrix:
1 2 3
4 5 6
7 8 9
Explanation:
This illustration demonstrates the creation of a 3×3 matrix and sets its values during initialization. The values are arranged in row-major order, with the initial row being {1, 2, 3}, followed by {4, 5, 6} in the second row, and {7, 8, 9} in the third row.
b) Partial Initialization
When fewer elements are provided than necessary in this function, the additional elements will be initialized to 0 automatically.
int matrix[3][3] = {
{1, 2},
{3, 4},
{5}
};
// Remaining elements will be initialized to 0
Resulting Matrix:
1 2 0
3 4 0
5 0 0
Explanation:
Only certain values are explicitly given, with the remaining ones defaulting to 0. In the initial row, there are {1, 2, 0}, in the second row {3, 4, 0}, and in the third row {5, 0, 0}.
c) Manual Initialization
An alternative method to set up a 2D array is by manually assigning values to each element separately.
int matrix[3][3];
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[1][2] = 5;
Resulting Matrix:
1 2 ?
? ? 5
? ? ?
Explanation:
Here, we are clearly assigning values to particular positions within the array. The rest of the elements remain uninitialized, holding either garbage values or 0 in the case of a global/static array.
Traversing a 2D Array:
Array traversal is a technique that allows developers to access and display every element stored in an array data structure.
Example
#include <iostream>
using namespace std;
int main() {
int arr[2][3] = { {1, 2, 3}, {4, 5, 6} };
// Traversing and printing the array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
1 2 3
4 5 6
Updating a 2D Array:
Updating elements within a 2D array necessitates the utilization of its specific index values.
int main() {
int arr[2][3] = { {1, 2, 3}, {4, 5, 6} };
arr[1][2] = 9; // Updating element at row 1, column 2
return 0;
}
Explanation:
The assignment arr1 = 9 modifies the element in the second row and third column of the array. The array's dimensions do not change, only the specific element's value is updated.
Accessing an Element in a 2D Array:
Let's consider an illustration showcasing the process of accessing an element within a 2D array in C++.
Example
#include <iostream>
using namespace std;
int main() {
int arr[2][3] = { {1, 2, 3}, {4, 5, 6} };
int value = arr[1][2]; // Accessing element at row 1, column 2
cout << "Accessed Element: " << value << endl;
return 0;
}
Output:
Accessed Element: 6
3D Arrays in C++
The C++ representation of 3D arrays extends the structures of 2D arrays by introducing an additional dimension for depth in addition to rows and columns, allowing for the organization of elements across multiple layers. This extension accommodates three-dimensional volumetric data, multi-layered objects, and three-dimensional matrices.
Create a 3D Array in C++:
The creation of a three-dimensional array relies on three consecutive array indices.
Syntax:
It has the following syntax:
data_type array_name[depth][rows][columns];
- data_type: It specifies the type of elements (e.g., int, float, char).
- Depth: Number of layers (slices).
- Rows: Number of rows in each layer.
- Columns: Number of columns in each row.
Example: Declaring a 3D Array
int cube[2][3][3];
// Creates a 2-layer 3D array with 3 rows and 3 columns in each layer
Initialize a 3D Array:
Numerous methods are available for initializing a three-dimensional array.
a) Initializing at Declaration:
In C++, values can be directly assigned to all elements when declaring them.
int cube[2][2][2] = {
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} }
};
Explanation:
The initial level { {1, 2}, {3, 4} } comprises a pair of rows. The subsequent level { {5, 6}, {7, 8} } maintains an identical format.
b) Partial Initialization:
In C++, it is possible to assign partial values to all elements when declaring them.
int cube[2][2][2] = {
{ {1}, {3, 4} },
{ {5, 6}, {7} }
};
// Remaining elements will be initialized to 0
Resulting 3D Array:
Layer 1:
1 0
3 4
Layer 2:
5 6
7 0
c. Manual Initialization:
In C++, values are assigned individually to elements in multidimensional arrays by specifying the indexes.
int cube[2][2][2];
cube[0][0][0] = 1;
cube[0][1][1] = 2;
cube[1][0][1] = 3;
Traverse a 3D Array:
Traversing through 3D arrays necessitates executing three consecutive loop operations.
Example:
Let's consider an instance to demonstrate the process of iterating through a three-dimensional array in the C++ programming language.
Example
#include <iostream>
using namespace std;
int main() {
int arr[2][2][3] = {
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};
// Traversing and printing the 3D array
for (int i = 0; i < 2; i++) { // Layers
for (int j = 0; j < 2; j++) { // Rows
for (int k = 0; k < 3; k++) { // Columns
cout << arr[i][j][k] << " ";
}
cout << endl; // New row
}
cout << endl; // Space between layers
}
return 0;
}
Output:
1 2 3
4 5 6
7 8 9
10 11 12
Update a 3D Array:
Modifying a specific element necessitates the utilization of a triplet of indices simultaneously. Individuals must implement a trio of iterations that manage levels subsequent to rows and then columns.
Example
#include <iostream>
using namespace std;
int main() {
int arr[2][2][3] = {
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};
arr[1][0][2] = 99; // Updating the element at layer 1, row 0, column 2
// print the updated element
cout << "Updated value at arr[1][0][2]: " << arr[1][0][2] << endl;
return 0;
}
Output:
Updated value at arr[1][0][2]: 99
Explanation:
The provided code declares a 3D array named arr2[3], which signifies 2 layers, 2 rows, and 3 columns. The array is assigned initial values and later modifies the element at layer 1, row 0, column 2 to 99. Modifying a particular element within a 3D array necessitates specifying three indices, and traversing through all elements generally entails utilizing three nested loops.
Accessing an Element in a 3D Array:
An item within a three-dimensional array can be retrieved by specifying its individual layer, row, and column indexes following the pattern 'arraylayer[column]'.
Example
#include <iostream>
using namespace std;
int main() {
int arr[2][2][3] = {
{ {1, 2, 3}, {4, 5, 6} },
{ {7, 8, 9}, {10, 11, 12} }
};
int value = arr[1][1][2]; // Accessing element at layer 1, row 1, column 2
cout << "Accessed Element: " << value << endl;
return 0;
}
Output:
Accessed Element: 12
C++ Multidimensional Array Example: Declaration and initialization at the same time
Let's consider a basic example of a multidimensional array that assigns values during declaration.
Example
#include <iostream>
using namespace std;
int main()
{
int test[3][3] =
{
{2, 5, 5},
{4, 0, 3},
{9, 1, 8} }; //declaration and initialization
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
Output:
2 5 5
4 0 3
9 1 8
Passing Multidimensional Array to a Function:
When passing multidimensional arrays to functions in C++, it is necessary for users to specify all array dimensions except the first. This information is crucial for the compiler to compute accurate memory offsets, facilitating efficient element retrieval.
Syntax:
It has the following syntax:
void function_name(data_type array[][columns], int rows);
The specification of columns is mandatory, whereas the specification of rows is optional.
Example: Passing a 2D Array
Example
#include <iostream>
using namespace std;
// Function to print a 2D array
void print2DArray(int arr[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
cout << "2D Array Elements:" << endl;
print2DArray(matrix, 2); // Passing a 2D array
return 0;
}
Output:
2D Array Elements:
1 2 3
4 5 6
Important Points of C++ Multidimensional Arrays
There are several main importancpp tutorials of C++ multidimensional array in C++. Some main points of C++ multidimensional are as follows:
- Initializing an Array with Multiple Dimensions: We can initialize an array with multiple dimensions, such as three dimensions (a cube) or more. Although the startup and traversal concepts remain the same, each additional dimension would require its loop.
- Getting to Elements: A multidimensional array's elements are accessed by utilizing their indices. Arri denotes the component of a two-dimensional array's i-th row and j-th column.
- Size of Multidimensional Array and Storage: The number of elements along each dimension determines the size of a multidimensional array. The sum of all the array's allocated memory is calculated using the sizes of all its dimensions. Large arrays should be used with caution because they can use up a lot of memory.
- Array of Pointers: Arrays of pointers can also be used to generate multidimensional arrays. In this instance, each row of the array serves as a pointer to another variety (the column). As a result, memory allocation options are more flexible, and working with different row lengths is now possible.
- Passing Multidimensional Arrays to Functions: We must provide the size of each dimension except the first when passing a multidimensional array to a function. It is so that the compiler can determine the memory offsets without guessing the size of these dimensions.
- Dynamic Memory Allocation: Pointers and the new operator (or malloc in C) can dynamically allocate memory for multidimensional arrays. By doing this, we can make flexible arrays whose dimensions can be changed in real-time.
- STL Containers: In order to generate dynamic multidimensional arrays in C++, utilize STL containers like std::vector. It comes pre-equipped with security, adaptability, and memory management.
Frequently Asked Questions (FAQs)
1. What is a multidimensional array in C++?
A multi-dimensional array in C++ consists of multiple dimensions, allowing it to store data in structured tabular or matrix forms. Two-dimensional arrays, also known as 2D arrays, are commonly used in C++, but the language also supports three-dimensional (3D), four-dimensional (4D), and even higher-dimensional arrays.
2. Why do we use multidimensional arrays?
- A multidimensional array supports the representation of matrices and grids such as chessboards and game boards.
- The array maintains tabular information such as student subject marks data.
- The 2D array structure serves image processing functions by maintaining pixel information.
- Multidimensional arrays find applications in scientific computing and graph-related challenges, such as adjacency matrices in graph theory.
3. What are the advantages and disadvantages of Multidimensional arrays in C++?
Advantages:
- Utilizing the array format facilitates effective data storage, particularly suited for grid layouts, tables, and matrix configurations.
- Accessing elements is expedited as direct indexing streamlines the retrieval process from both rows and columns.
Disadvantages:
- Large arrays consume significant memory space if not utilizing dynamically allocated memory.
- Errors may arise when trying to access elements with multiple indices in intricate structures.
4. How is a two-dimensional array declared in C++?
A 2D array is defined using the following syntax:
data_type array_name[rows][columns];
5. What kinds of multidimensional arrays exist within the C++ programming language?
The organization and storage layout of C++ multidimensional arrays enables classification into various groups:
2D Arrays:
The arrangement of rows and columns serves as the foundation for the majority of frequently utilized multidimensional arrays in coding.
Arrays with two dimensions are effective for storing tabular data, matrices, and grid structures.
3D Arrays:
- Three-dimensional arrays follow the structure of 2D arrays but with an additional dimension.
- Arrays with multiple dimensions are commonly used in tasks such as image processing and scientific simulations.
Arrays with dimensions higher than four are not commonly used in real-world scenarios, despite being a possibility.
Higher-order arrays are primarily utilized in complex mathematical computations and simulations.