Initializing Two Dimensional Array

Initializing Two Dimensional Array

Initializing two dimensional array is little bit confusing for the most of the students.But,it is not.Two dimensional array is a collection of one dimensional arrays taken in multiple rows.In C programming language,a two dimentional array can be declared as shown below

int std[m][n];

where int represents the datatype of the variable.’std’ is the name of the array.’m’ represents the number of rows while ‘n’ represents the number of columns of that array while initializing two dimensional array.From the previous tutorials, it is known that array is the continuous memory location of same kind of objects.Each location is also identified by pointer which will be discussed later.
Let’s take an example of two dimensional array,

[c] int std [4] [2] = {
{ 121,56},
{123,33},
{143,80},
{131,78}
};
[/c] or
[c] int std[4][2] = { 1234, 56,1212, 33,1434, 80,1312, 78};
[/c]

In the above figure,the array contains 4 rows and 2 columns.A two dimensional array can be viewed as a table containing m number of rows and n number of columns in the case of initializing two dimensional array .

Initializing two dimentional array

It is important to remember that while initializing two dimentional array, it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional.
Thus the declarations,

[c] int roll[2][3] = { 11, 35, 23, 45, 56,45};
int roll[ ][3] = { 11, 35,23,45, 56,45};
[/c]

are perfectly acceptable,
whereas,

[c] int roll2][ ] = { 11, 35, 23, 45, 56, 45};
int roll[ ][ ] = { 11, 35,23,45, 56,45};
[/c]

would never work.

Accessing of Array Element

Initializing two dimentional array is the first step.After initialization, we have to access the array elements.To retrieve the two dimensional array elements,use the loop two time.You can use any type of loop.you can either use definite loop or indefinite loop.The following code should be added in the program to aacess Two Dimensional Array

[c] for(int i=0;i<4;i++){
for(int j=0;j<2;j++){
printf(“std[%d][%d]=%d\t”,i,j,std[i][j]);
}
printf(“\n”);
}
[/c]

The output of the two dimensional array is as follows:

Initializing Two Dimensional Array
Initializing Two Dimensional Array

Click Here For Resources
Click Here For Resources

Please let me know about any issues that you have about arrays,pointers or any part of the C programming language,please feel free to contact me.

This entry was posted in Uncategorized. Bookmark the permalink.

One thought on “Initializing Two Dimensional Array

  1. Suresh Kumar Thapa says:

    Dear sir,

    I found this lesson ‘initializing two dimensional array’ very fruitful because it paved my programming skill in Array initialization and accessing the array element in easy manner.

    I am very proud from this lesson. Hopping for getting more better in next lessons.

    Sincerely
    Suresh Kumar Thapa
    Nepal

Comments are closed.