Ex 10
Ex 10
Theory-
Dimension of an array refers to a particular direction in which array elements can be varied.
An array with a single dimension is known as a one-dimensional array. An array that has a
dimension greater than one is known as a multidimensional array.
For example, an array with two dimensions is a two-dimensional array. 2D array is the
simplest form of a multidimensional array which could be referred to as an array of arrays.
The 2D array is organized as matrices which can be represented as the collection of rows and
columns.
data_type array_name[rows][columns];
int twodimen[4][3];
The following figures illustrates the difference between a one-dimensional array and a
two-dimensional array:
Initializing Two – Dimensional Array
We can initialize a two-dimensional array in C in any one of the following two ways:
This will create an array of size x * y with elements being filled in the following
manner:
From left to right, the first y elements will be on the first row. y + 1 onwards, the next
y elements, in the order of left to right, will be filled on the second row. In this
manner, all the x rows will be filled one by one.
So we will have an array of size 2 * 3 with the above initialization. Let us see how the
elements will be filled:
From left to right, the first three elements will be on the first row.
Fourth to the last element, in the order of left to right, will be filled on the
second row.
Let us see by an example how we can use nested braces to implement the above:
Each nested brace denotes a single row, with the elements from left to right being the
order of elements in the columns in our 2d array.
When a normal array is initialized during declaration, we need not to specify the size
of it. However that’s not the case with 2D array, you must always specify the second
dimension even if you are specifying elements during the declaration. Let’s
understand this with the help of few examples –
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
Let's suppose we have an array Arr of 3 rows and 3 columns of type int.
For example, if an array of Student[8][5] will store 8 row elements and 5 column
elements. To access or alter 1st value, use Student[0][0], to access or alter 2nd row
3rd column value, then use Student[1][2], and to access the 8th row 5th column, then
use Student[7][4]. Let’s see the example of a C Two Dimensional Array for better
understanding:
Exercise-