Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Two dimensional array (2D array)

An array with two subscripts is called two-dimensional array.

Syntax

dataType arrayName[row_size][column_size];

dataType Tells the type of data like int, float, char, etc.
arrayName – Tells the name of an array.
row_size – Tells the number of rows present in a 2D array.
column_size – Tells the number of columns present in a 2D array.

Example of 2D array

int X[4][3];

 DataType of an array is int;
Name of an array is X;
Row size is 4;
Column size is 3;

General representation of 2D array with 5 rows & 5 columns

C Programming Language Two Dimensional or 2D ArrayAlthough we represent array in rows & columns, actually in memory, it is stored contiguously. That is one row after another row.

Example

int x[4][3]

For our understanding we represent above array X[4][3] as follow:

C Programming Language 2D Array ExampleBut in memory it is stored as shown below:

C Programming Language Array Stored in MemoryFrom this we can conclude that 2D array is an array of 1D array.

Initialization of 2D array at the time of declaration

Example no 1

#include <stdio.h>
int main()
{
    int x[4][5] = {11,12,13,14,15,21,22,23,24,25,31,32,33,34,35,41,42,43,44,45};
    int i,j;
	
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            printf(" %d ",x[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output

11  12  13  14  15
21  22  23  24  25
31  32  33  34  35
41  42  43  44  45

Elements can be grouped in rows.

Example

#include <stdio.h>
int main()
{
    int x[4][5] = {{11,12,13,14,15},
                   {21,22,23,24,25},
                   {31,32,33,34,35},
                   {41,42,43,44,45}};
    int i,j;
	
    for(i=0;i<4;i++)
    {
        for(j=0;j<5;j++)
        {
            printf(" %d ",x[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output

11  12  13  14  15
21  22  23  24  25
31  32  33  34  35
41  42  43  44  45

Initializing 2D array using scanf() in loop

Example

#include <stdio.h>
int main()
{
    int x[3][3];
    int i,j;
	
    printf("\n Enter elements of an array :: ");
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&x[i][j]);
        }
    }
    printf("\n Elements of 2D array are ::");
    printf("\n");
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            printf(" %d ",x[i][j]);
        }
        printf("\n");
    }
    return 0;
}

Output

Enter elements of an array :: 1
2
3
4
5
6
7
8
9

Elements of 2D array are ::
1  2  3
4  5  6
7  8  9

 

Leave a reply