Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN C++!!! Write a program that multiplies two 3x3 matrices of doubles, namely A

ID: 3689117 • Letter: I

Question

IN C++!!!

Write a program that multiplies two 3x3 matrices of doubles, namely A and B. (matrix is a 2D array) The values of the two matrices are read from a file “Multiply.txt”, which has 18 manually entered double values one below the other: First nine elements belong to matrix A (set of three goes to each row) and similarly, the remaining 9 elements belong to matrix B (set of three goes to each row). Store the product in a new matrix named C. Display the matrix contents of A, B and C.

To compute, C[0][0] = A[0][0]*B[0][0] + A[0][1]*B[1][0] + A[0][2]*B[2][0] = 3.1*2.8 + 4.5*6 +1*8.2 = 43.88

C[0][1] = A[0][0]*B[0][1] + A[0][1]*B[1][1] + A[0][2]*B[2][1] = 3.1*12.1 + 4.5*(-15.3) + 1*3 = -28.34

HINT: To compute C[i][j]; multiply corresponding elements of i-th row of A with j-th column of B and add them together. See examples above.

Explanation / Answer

#include <iostream>
using namespace std;

int main() {
   // your code goes here
   const char* filename = "Multiply.txt";
   ifstream inFile(filename);
  
   double a[3][3],b[3][3],c[3][3];
  
    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            inFile >> a[i][j];
  
    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            inFile >> b[i][j];
  
    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            c[i][j]=0;
          
    for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
            for(int k=0;k<3;k++)
                c[i][j] += a[i][k]*b[k][j];
              
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            cout<<a[i][j]<<' ';
        }
        cout<<' ';
    }
    cout<<' ';
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            cout<<b[i][j]<<' ';
        }
        cout<<' ';
    }
    cout<<' ';
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            cout<<c[i][j]<<' ';
        }
        cout<<' ';
    }
   return 0;
}