Mastery 26

Creation and use of matrixes in C++ (multi – dimensional arrays)

Two-Dimensional Arrays:

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. 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.

A two-dimensional array can be think as a table, which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below:

Mastery 26

Thus, every element in 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:

Multidimensioned arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row have 4 columns.

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example:

Accessing Two-Dimensional Array Elements:

An element in 2-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 4th element from the 3rd row of the array. You can verify it in the above digram.

When the above code is compiled and executed, it produces the following result:

As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

Credits:

http://www.tutorialspoint.com/cplusplus/cpp_multi_dimensional_arrays.htm

1017 26

CC BY 4.0 Mastery 26 by Mauricio Cooper is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.