Two Dimensional 2D
Two Dimensional 2D
Arrays
DENNIS G. CORLET
Subject Instructor
What is 2D Array?
• An array of arrays is known as 2D array. The two dimensional
(2D) array in C programming is also known as matrix.
• A matrix can be represented as a table of rows and columns.
• The simplest form of multidimensional array is the two-
dimensional array. A two-dimensional array is, in essence, a
list of one-dimensional arrays.
How to declare a 2D Array?
• To declare a two-dimensional integer array of size [x][y], you would
write something as follows −
where
• type can be any valid C data type; and
• arrayName will be a valid C identifier.
or
Following is an array with 3 rows and each row has 4 columns.
which is equivalent to
Things that you must consider while
initializing a 2D array
• In a normal array (one dimensional), you 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 exercise!
• Determine whether the following array initialization is valid or not.
Valid declaration
Invalid declaration
– you must specify second dimension
Valid declaration
Invalid declaration
– you must specify second dimension
How to store user input data into 2D
array?
• We can calculate how many elements a two dimensional array can
have by using this formula:
n1*n2 elements.
• For instance, array abc has dimensions 5 and 4. These dimensions are
known as subscripts. So this array has first subscript value as 5 and
second subscript value as 4.
• This way the order in which user enters the elements would
be abc[0][0], abc[0][1], abc[0][2]…so on.
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. For example:
• The above statement will take the 4th element from the 3rd row of
the array.
Let us check the following program where we have used a nested loop
to handle a two-dimensional array −
Example
Exercise 1
• Create a 2D array program
with dimensions of 2 and
3. Allow the user to enter
the values of the
elements. Afterwards,
display the elements in
matrix form.