Two dimensional array in C++ | Initialization of Two dimensional array in C++
Two dimensional array is an array whose elements are represented in the form of rows and columns. The syntax for declaring a two dimensional array is:
<Type> Array_name[ROW][COL];
Type refers to data type of array like int, float, char etc.
Array_name is the name of array as defined by the programmer.
ROW specifies number of rows in the two dimensional array.
COL specifies the number of columns in the two dimensional array.
Example
int A[3][3];
Two dimensional array a has been declared as a[3][3] which specifies that this array can contain 9 elements stored in the form of rows and columns as
a[0][0], a[0][1], a[0][2],
a[1][0], a[1][1], a[1][2],
a[2][0], a[2][1], a[2][2].
Program to assign and display values in two dimensional NUM
#include<iostream> using namespace std; int main() { int NUM[2][2]; NUM[0][0]=10; NUM[0][1]=20; NUM[1][0]=30; NUM[1][1]=40; cout<<"\nNUM[0][0]="<<NUM[0][0]; cout<<"\nNUM[0][1]="<<NUM[0][1]; cout<<"\nNUM[1][0]="<<NUM[1][0]; cout<<"\nNUM[1][1]="<<NUM[1][1]; return 0; }
Output
NUM[0][0]=10 NUM[0][1]=20 NUM[1][0]=30 NUM[1][1]=40
*In the above program, we have declared a two dimensional NUM a having number of rows 2 and number of columns 2. This NUM can contain four values. First element of NUM is named as NUM[0][0], second value is named as NUM[0][1], third value is named as NUM[1][0] and fourth value is named as NUM[1][1].
Initialization of a Two dimensional array in C++
Syntax to initialize a two dimensional array is:
<Type> Array_name[ROW][COL]={LIST};
LIST is set of values stored in a two dimensional array. Values should be separated with commas.
Various ways to initialize a two dimensional array are:
int arr1[2][2]={3,4,5,6}; int arr2[3][2]={3,4, 5,6, 8,9 }; int arr3[3][3]={{6,9,8}, {2,6,8}, {4,9,3} };
Program to initialize a two dimensional array in C++.
#include<iostream> using namespace std; int main() { int i,j; int a[3][2]={3,4, 5,6, 8,9 }; int b[3][3]={ {6,9,8}, {2,6,8}, {4,9,3} }; cout<<"\nMatrix a is="; for(i=0;i<3;i++) { cout<<endl; for(j=0;j<2;j++) cout<<"\t"<<a[i][j]; } cout<<"\nMatrix b is="; for(i=0;i<3;i++) { cout<<endl; for(j=0;j<3;j++) cout<<"\t"<<b[i][j]; } return 0; }
Output
Matrix a is= 3 4 5 6 8 9 Matrix b is= 6 9 8 2 6 8 4 9 3
Program to read and display elements of a two dimensional array in C++.
#include<iostream> using namespace std; int main() { int i,j; int arr2D[3][3]; cout<<"\nEnter values in Matrix a="; for(i=0;i<3;i++) { for(j=0;j<3;j++) cin>>arr2D[i][j]; } cout<<"\nMatrix is="; for(i=0;i<3;i++) { cout<<endl; for(j=0;j<3;j++) cout<<"\t"<<arr2D[i][j]; } return 0; }
Output
Enter values in Matrix a= 3 4 5 2 3 5 1 3 8 Matrix is= 3 4 5 2 3 5 1 3 8![]()