C++ DSA Arrays
C++ DSA Arrays
Home My courses CONT_23CSH-103 :: ELEMENTARY DATA STRUCTURES USING C++ Chapter 2.2
2D Arrays
2D Arrays
CO3 - Analyse and explain the behaviour of linear data structure operations using the programming addressed in
the course.
2D array
A two-dimensional (2D) array can be thought of as a matrix with rows and column where its elements are selected
(identified) using two indices. In 2-D array, to declare and access elements of a 2-D array we use 2 subscripts instead
of 1.
In rectangular 2-dimensional arrays, m number of rows and n number of columns in the array has the same number of
array elements.
For example:
1 2 3
4 5 6
#include<iostream>
using namespace std;
int main()
{
int arr[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
int i, j;
cout<<"The Two-dimensional Array is:\n";
for(i=0; i<4; i++)
{
for(j=0; j<2; j++)
cout<<arr[i][j]<<" ";
cout<<endl;
}
cout<<endl;
return 0;
}
Get Array Elements of the Given Size from the User
Now this program allows the user to enter the dimension or size of a 2D array and then its elements of the given size to
store it in a 2D array arr[][] and print the array back on the output screen along with the index number (row and
column number starting from 0):
#include<iostream>
using namespace std;
int main()
{
int row, col, i, j, arr[10][10];
cout<<"Enter the Row and Column Size for Array: ";
cin>>row>>col;
cout<<"Enter "<<row*col<<" Array Elements: ";
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
cin>>arr[i][j];
}
cout<<"\nThe Array is:\n";
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
cout<<arr[i][j]<<" ";
cout<<endl;
}
cout<<"\nArray Elements with its Index:\n";
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
cout<<"arr["<<i<<"]["<<j<<"] = "<<arr[i][j]<<" ";
cout<<endl;
}
cout<<endl;
return 0;
}
Previous activity
Jump to...
Next activity