﻿ Two Dimensional Array in Data Structures || CseWorld online

Two Dimensional Array

• Two dimensional arrays are also called table or matrix, two dimensional arrays have two subscripts.
• Two dimensional array inwhich elements are stored column by column is called as column major matrix.
• Two dimensional array in which elements are stored row by row is called as row majo rmatrix.
• First subscript denotes number of rows and second subscript denotes the number of columns.
• The simplest form of the Multi Dimensionl Array is the Two Dimensionl Array. A Multi Dimensionl Array is essence a list of One Dimensionl Arrays.

Two dimensional arrays can be declared as follows :

``` int int_array[10] ;         // A normal one dimensional array
int int_array2d[10][10] ;   // A two dimensional array```

Initializing a Two Dimensional Array

A 2D array can be initialized like this :

` int array[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;`

Program

``` #include <stdio.h>
void printarr(int a[][]);
void printdetail(int a[][]);
void print_usingptr(int a[][]);
main()
{
int a[3][2]; \ A
for(int i = 0;i<3;i++)
for(int j=0;j<2 ;j++)
{
{
a[i]=i;
}
}
printdetail(a);
}
void printarr(int a[][])
{
for(int i = 0;i<3;i++)
for(int j=0;j<2;j++)
{
{
printf("value in array %d,a[i][j]);
}
}
}
void printdetail(int a[][])
{
for(int i = 0;i<3;i++)
for(int j=0;j<2;j++)
{
{
printf( "value in array %d and address is %8u, a[i][j],&a[i][j]);
}
}
}
void print_usingptr(int a[][])
{
int *b; \ B
b=a; \ C
for(int i = 0;i<6;i++) \ D
{
printf("value in array %d and address is %16lu,*b,b);
b++; // increase by 2 bytes \ E
}
}```

Explanation

1. Statement A declares a two-dimensional array of the size 3 × 2.
2. The size of the array is 3 × 2, or 6.
3. Each array element is accessed using two subscripts.
4. You can use two for loops to access the array. Since i is used for accessing a row, the outer loop prints elements row-wise, that is, for each value of i, all the column values areprinted.
5. You can access the element of the array by using a pointer.
6. Statement B assigns the base address of the array to the pointer.
7. The for loop at statement C increments the pointer and prints the value that is pointed to by the pointer. The number of iterations done by the for loop, 6, is equal to the array.
8. Using the output, you can verify that C is using row measure form for storing a twodimensional array.

Points to Remember

1. You can define a multi-dimensional array in C.
2. You have to provide multiple subscripts for accessing array elements.
3. You can access array elements by using a pointer.