In: Computer Science
The following matrix is stored in an array with variable name matrixTest.
(? −?
? ?
? ? ) i. Write the code to initialize the array.
ii. Write the code to display the content of matrixTest.
*IN C++
The following matrix is stored in an array with variable name matrixTest.
(? −?
? ?
? ? )
i. Write the code to initialize the array.
Answer
Since given is a matrix we can store matrix using two dimensional arrays.Multidimensional arrays are array of arrays. Data in multidimensional arrays are stored in tabular form.
Initializing Two – Dimensional Arrays: There are two ways in which a Two-Dimensional array can be initialized.
First Method:
#include <iostream>
using namespace std;
int main()
{
    // initializing the array with given numbers which are stored in a matrix with 3 rows and 2 columns
  
      int x[3][2] = {2,-5,4,0,9,1};
    return 0;
}
Second Method or Better Method:
#include <iostream>
using namespace std;
int main()
{
    // initializing the array with given numbers which are stored in a matrix with 3 rows and 2 columns
    int matrixTest[3][2]={{2,-5}, {4,0}, {9,1}}; 
    return 0;
}
ii. Write the code to display the content of matrixTest.
Answer
#include <iostream>
using namespace std;
int main()
{
    // initializing the array with given numbers which are stored in a matrix with 3 rows and 2 columns
    int matrixTest[3][2]={{2,-5}, {4,0}, {9,1}}; 
    // Displaying content of matrixTest
    // accessing the content using the row indexes and column indexes.
    // first for loop is for accessing rows 
    for (int i = 0; i < 3; i++) 
    { 
        // second for is for accessing columns
        for (int j = 0; j < 2; j++) 
        { 
            cout << "Element at x[" << i 
                 << "][" << j << "]: "; 
            cout << matrixTest[i][j]<<endl; 
        } 
    } 
    return 0;
}
Output: