How to Use Arrays to Make Matrices in C++
Two-dimensional arrays are a perfect way to represent matrices in C++ without undue difficulty. An array is a type of C++ data structure that stores a series of values in order, in one or more dimensions. You can use a two-dimensional array to store values as a matrix, in rows and columns. You have to define the maximum size of the matrix in the variable declarations, but it is possible to design the program to only use a part of the defined space, effectively allowing you to create matrices of any size up to the pre-defined maximum.
Instructions
-
-
1
Declare a two-dimensional array using the same syntax as a regular variable declaration, but with two sets of brackets after the variable name containing the number of rows and columns, respectively. To create a 4-by-5 matrix of integers, for example, type:
int mymatrix[4][5];
-
2
Assign values to each element of the matrix. Refer to a given element by following the matrix's variable name with two pairs of brackets that hold the desired element's row and column coordinates, respectively. The first element is stored with the coordinates (0, 0) and the last is stored in (n - 1, m - 1) where n and m represent the number of rows and columns in the matrix. To assign the value 3 to the fifth item in the first row, for example, type:
mymatrix[0][4] = 3;
-
-
3
Retrieve values from the matrix by referring to them in the same way, using bracketed subscripts to access the desired element. For example, to display the value of the element in the fourth row and seventh column, type:
cout << mymatrix[3][6];
-
1
Tips & Warnings
You can efficiently allow a user to input all the values in a matrix by using nested "for" loops.
If the fact that the first element is (0, 0) confuses you, you can declare a matrix with one more row and column than you need and simply ignore row zero and column zero, allowing you to refer to, for example, the element at (3, 5) as mymatrix[3][5] instead of mymatrix[2][4].
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images