2D-Array:
2D array is similar to a matrix of mxn (row into column). where every element has a specific index which is usually denoted by i and j. i represent the number of rows and j represent the number of columns.Declaration of 2D Array in C++
int A[5][4]; // 5 rows and 4 columnInitialization Of Array:
An array initializer for a 2D array contains the rows of A, separated by commas and enclosed in braces. Each row, in turn, is a list of values separated by commas and enclosed in braces.int A[5][4] = {
{ 1, 2, 3, 4 },
{ -44, 65, 4, 23},
{ -45, -1, 3, 34}
{ -45, -1, 3, 34}
{ -45, -1, 3, 34}
};
There are three-dimensional, four-dimensional, and even higher-dimensional arrays, but they are not used very often in used.
2D array as a pointer:
int **ptr = new int * [row]; for(x=0;x<row;x++) *(ptr+x) = new int [col];
Implementation of 2D Array in C++:
#include<iostream>
using namespace std;
int main()
{
int row,col,x,y;
cout<<"Enter number of rows: ";
cin>>row;
cout<<"Enter number of columns: ";
cin>>col;
int **ptr = new int * [row];
for(x=0;x<row;x++)
*(ptr+x) = new int [col]; //Storing elements
for (x=0;x<row;x++)
for(y=0;y<col;y++)
{
cout<<"Enter number: ";
cin>>ptr[x][y];
}
//Displaying pointer to pointer to ptr
cout<<"You have entered:"<<endl;
for (x=0;x<row;x++)
{
for(y=0;y<col;y++)
{
cout<<ptr[x][y]<<" ";
}
cout<<endl;
}
return 0;
}
Comments
Post a Comment