What is a Two-Dimensional Array?
A two-Dimensional Array is the simplest form of a Multi-Dimensional Array which you can consider as an array of arrays and visualize in the form of a table with rows and columns to store data. A two-Dimensional Array is also called Matrix having m number of rows and n number of columns and you can store m x n data values of the same type.
Below is an example of a Two-Dimensional Array:
How To Declare a Two-Dimensional Array?
To declare a 2D array in C++ programming language, you first need to write the data type of the array followed by the array name, and as it is 2D-array so you will need two subscripts (square brackets [ ][ ]) to define the size of the array.
syntax: data_type name_of_array[size1][size2]...[sizeN];
For example:
int arr[4][5] //Two Dimensional Array
size of arr[4][5] = 4x5 = 20 elements we can store in this array
int arr[4][5][6] //Three Dimensional Array
size of arr[4][5][6] = 4x5x6 = 120 elements we can store in this array
How To Initialize a Two-Dimensional Array?
You can initialize a 2D array just like a 1D array but here you need to take care that the position of the data value should now exceed the number of rows and columns. Let's understand this with one example:
Example of 2D Array: int arr[4][5];
In the above example, the value 4 in the first bracket is defining the number of arrays present and the second value 5 in the second bracket defines the number of elements you can store in each array.
int arr[4][5] = {{3, 4, 6, 9, 5},
{1, 2, 3, 5, 8},
{7, 0, 1, 3, 5},
{2, 4, 9, 0, 3}};
How To Traverse Two-Dimensional Array?
Traversing is a process of visiting each element of the given array at least one time and to perform this operation on Two Dimensional Array you need some basic information like the number of rows and columns. You have to run two nested loops in which the first loop is m times which is the number of rows and the second inner loop will run n times which is the number of columns.
C++ program to Traverse 2D Array:
//C++ program to traverse 2D Array #include<iostream> using namespace std; int main(){ int arr[4][5] = {{2, 3, 5, 6, 8}, {1, 2, 4, 8, 3}, {0, 4, 2, 9, 1}, {5, 4, 3, 2, 1}}; cout<<"Displaying 2D Array: "<<endl; for(int i = 0; i < 4; i++){ for(int j = 0; j < 5; j++){ cout<<arr[i][j]<<" "; } cout<<endl; } return 0; }
Displaying 2D Array:
2 3 5 6 8
1 2 4 8 3
0 4 2 9 1
5 4 3 2 1
There are several coding problems that you can solve based on 2D Array and I am sharing few of them below:
Next:
No comments:
Post a Comment