2 -Dimensional Arrays C

The previous arrays were like a list of elements. Consider the following table

2 -Dimensional Arrays
It has 4 rows and 3 columns. It can be represented as a 2 – dimensional array. Row is one dimension and column is second dimension. Each element of the array is referred to by using two subscripts. If ‘tda’ is the name of the array, then array is defined as

Storage-class data – type array-name [no. of rows] [no. of columns]

E.g.

int tda [4] [3];

tda[1] gives the first element of the array, tda[1][1] the second element and so on. Generally 2- D array is referred to row-by-row. Hence 2-D array can be considered one-dimensional arrays placed one below the other .2-D array can be referred to column-by-column. 2-D array is also called a matrix.

The following program shows how the elements of a two dimensional array are accessed.

Example:

/ * Program to demonstrate 2-dimensional arrays * /

The program puts data elements in the 2-D array row-by-row. In for loop ‘i’ which represents row runs from 0 to 3 and j which represent the column runs from 0 to 2. It means, for the 0th row all the column are filled. When i = 1, again j runs from 0 to 2 i.e. for the first row all columns are filled and so on.

If we want to obtain element from the array, the following for – loop can be added to the end of the program.

2-D array can be initialized as follows.

tda [4] [3] = { { 2, 4, 6},{10, 12, 15},{18, 20, 24} };
OR tda [4] [3] = {2, 4, 6, 10, 12, 13, 12, 14, 15, 18, 20, 34};

If there are too few values within a pair of braces, the remaining elements of that row will be assigned zeros. The number of values within each pair of braces cannot exceed the defined row size. While initializing a 2-D array, the first dimension is optional whereas the second dimension is compulsory.

int tda [] [3] = { } is ok

2-D arrays can be passed to functions but care must be taken to ensure that the declaration of formal array argument must contain explicit size for second dimension and must match with the definition of array in calling function.


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics