Tuesday 3 January 2012

Two Dimensional Arrays

Syntax: data_type array_name[row_size][column_size];
Example: int arr[3][3];
So the above example declares a 2D array of integer type. This integer array has been named arr and it can hold up to 9 elements (3 rows x 3 columns).



Example
include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
int arr[3][3]={
        {12, 45, 63},
        {89, 34, 73},
        {19, 76, 49}
        };
clrscr();
printf(":::2D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
    printf("%d\t",arr[i][j]);
    }
    printf("\n");
}
getch();
}
So in the above example we have declared a 2D array named arr which can hold 3x3 elements. We have also initialized that array with values, because we told the compiler that this array will contain 3 rows (0 to 2) so we divided elements accordingly. Elements for column have been differentiated by a comma (,). When compiler finds comma in array elements then it assumes comma as beginning of next element value. We can also define the same array in other ways, like.
int arr[3][3]={12, 45, 63, 89, 34, 73, 19, 76, 49}; or,
int arr[ ][3]={12, 45, 63, 89, 34, 73, 19, 76, 49}; But this kind of declaration is not acceptable in C language programming.
int arr[2][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49}; or,
int arr[ ][ ]={12, 45, 63, 89, 34, 73, 19, 76, 49};
To display 2D array elements we have to just point out which element value we want to display. In our example we have a arr[3][3], so the array element reference will be from arr[0][0] to arr[2][2]. We can print display any element from this range. But in our example I have used for loop for my convenience, otherwise I had to write 9 printf statements to display all elements of array. So for loop i handles row of 2D array and for loop j handles column.

No comments:

Post a Comment

host gator coupon