Programming in "C‟ | With suitable example describe how to declare and initialize two dimensional array.

A two dimensional array is an array of arrays. It consists of rows and columns. It is also called a matrix. To declare and initialize two dimensional  array with 2 rows and 2 columns: 

int arr[2][2] = {10, 20, 5, 3};

The first subscript represents the number of rows and the second represents the number of columns. The second subscript representing the number of columns is compulsory. The above declaration states that the array will contain 4 elements arranged in two rows and two columns.

Another way to declare and initialize a two dimensional array is:

int arr[2][2]={

                         {10,20},

                          {5,3}

                       };

The elements of an array can be accessed by using indices. The elements in the first row of  array will be represented by the subscripts, first element-arr[0][0], the second element arr[0][1], second row first element arr[1][0], second  element arr[1][1].  

Elements of an array can also be initialised and accessed using loop.

Eg:

#include<stdio.h>

#include<conio.h>

void main() {

int ar[2][2],i,j;

clrscr();

printf("Enter the values");

for(i = 0;i<2;i++) {

for(j=0;j<2;j++){

scanf("%d",&ar[i][j]);

}

}

for(i=0;i<2;i++){

for(j=0;j<2;j++) {

printf("%d\n",ar[i][j]);

}

}

getch();


Post a Comment

0 Comments