Friday, July 29, 2016

C Basics - Two Dimensional Array in C

Two Dimensional arrays:
A two-dimensional array is a list of one-dimensional arrays. To declare a two-dimensional array,

type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier.

A two-dimensional array a, which contains three rows and four columns can be shown as follows.
Column 0 Column 1 Column 2 Column 3
Row 0 a[0][0] a[0][1] a[0][2] a[0][3]
Row 1 a[1][0] a[1][1] a[1][2] a[1][3]
Row 2 a[2][0] a[2][1] a[2][2] a[2][3]

every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.

Initializing two dimensional arrays:
A two-dimensional array can be initialized as follows,

int x[4][5] = {  
   {0, 1, 2, 3, 4} ,   /*  row 0 */
   {5, 6, 7, 8, 9} ,   /*  row 1 */
   {10, 11, 12, 13, 14}   /*  row 2 */
   {15, 16, 17, 18, 19}   /*  row 3 */
};

It can also be initialized as,

int x[4][5] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};

Accessing two-dimensional array elements:
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array.

int value = x[1][2];

Example:


#include <stdio.h>

int main () {

   int i[2][3];
   int temp;
   
   i[0][0] = 1;
   i[1][1] = 2;
   i[2][2] = 3;
   
   temp = i[0][0];
   printf("value in i[0][0] = %d\n", temp );
   temp = i[1][1];
   printf("value in i[1][1] = %d\n", temp );
   temp = i[2][2];
   printf("value in i[2][2] = %d\n", temp );
   
   return 0;
}
Output of above program,

value in i[0][0] = 1
value in i[1][1] = 2
value in i[2][2] = 3



Related topics:
Arrays in C   |   Passing Array as Function Argument in C   |   Strings in C   |   Pointers in C   |   Returning Array from a Function in C

List of topics: C Programming

No comments:

Post a Comment