How to make a matrix using arrays?
Programming languages use arrays, specifically two-dimensional arrays, to create a matrix. A two-dimensional array is an array that contains references (the "rows" of the matrix) to other arrays (the "columns" of the matrix), as illustrated in the diagram below.
The elements of the two-dimensional array above (Array 5) aren't integers, rather they're references to the one-dimensional arrays, Array 1–4.
Creating a matrix
The code snippets below goes over how to program a two-dimensional array similar to the one in the illustration above (Array 5).
int array1[4] = {3, 5, 1, 6};int array2[4] = {1, 7, 2, 9};int array3[4] = {9, 3, 7, 2};int array4[4] = {6, 2, 4, 6};int* exampleMatrix[4] = {array1, array2, array3, array4};
Code explanation
C++
Line 1-4: We declare all the rows of our matrix.
Line 6: We assign an array containing references to above four arrays (rows of the matrix) to pointer variable
exampleMatrix.
Python
Line 1-4: We declare all the rows of our matrix.
Line 6: We create matrix
exampleMatrixcontaining references to above four arrays (rows of the matrix).
Printing a matrix
In order to print the matrix (two-dimensional array), we make use of nested for loops, as depicted in the code snippets below.
Note: The dimensions of the matrix must be known before printing it.
for (int i = 0; i < 4; i++){for (int j = 0; j < 4; j++){cout << exampleMatrix[i][j] << " ";}cout << endl;}
Code explanation
C++
Line 1-6: We print the two dimensional matrix using two nested
forloops.
Python
Line 1-6: We print the two dimensional matrix using Python's
printfunction.
Indexing a two-dimensional array
Two-dimensional arrays are most often indexed using the bracket notation, as can be seen below:
The bracket notation above will result in indexing the element that is present at the ith row and jth column of our matrix, exampleMatrix.
In order to assign a value to this element, we make use of the assignment operator. Below, the value of 8 is assigned to the element in the 2nd row and 3rd column of exampleMatrix.
exampleMatrix[2][3] = 8;// Printing the matrixfor (int i = 0; i < 4; i++){for (int j = 0; j < 4; j++){cout << exampleMatrix[i][j] << " ";}cout << endl;}
Code explanation
C++
Line 1: We assign the value
8to the element of second row and third column inexampleMatrix.Line 4-9: We print the complete matrix using nested
forloops.
Python
Line 1: We assign the value
8to the element of second row and third column inexampleMatrix.Line 5: We print the complete matrix using
printfunction.
Free Resources