Initialising a 2-Dimensional Array


« Previous
Next »

Initialising a 2-Dimensional Array

Like one dimensional array, a 2-Dimensional Array are initialise in three ways :

1. Assigning value to array element
We can assign an values to all array element one by one.
  marks[1][1] = 79  ;
  marks[1][2] = 88  ;
  marks[2][1] = 70  ;
  marks[2][2] = 56  ;
  marks[3][1] = 98  ;
  marks[3][2] = 67  ;

2. Assign value to entire array
We can assign entire array at the time of decleration .
int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
}  ;
int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 }  ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 }  ;



3. Using Loop
Here is the section of code that places data into an array:
for ( i = 0; i < 4; i ++  )
{

for ( j = 0; j < 2; j ++  )
{
scanf(" %d ",   &marks[i][j] ) ;
}

}



It is important to remember that while initializing a 2-D array it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional.

Thus the following declarations are perfectly acceptable :
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;




« Previous
Next »