1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;
const int MAX_ROWS = 10;
const int MAX_COLUMNS = 10;
void Data(ifstream&, int [][MAX_COLUMNS], int, int, ifstream&, int [][MAX_COLUMNS], int, int);
void multiplyMatrices(int [][MAX_COLUMNS], int [][MAX_COLUMNS], int [][MAX_COLUMNS], int, int, int, int);
void display(int [][MAX_COLUMNS], int, int);
int main(int argc, char **argv)
{
if (argc != 3)
{
cout << "Error, must provide exactly two arguments!" << endl;
return 0;
}
ifstream infile1(argv[1]); ifstream infile2(argv[2]);
int firstMatrix[MAX_ROWS][MAX_COLUMNS], secondMatrix[MAX_ROWS][MAX_COLUMNS];
int rowFirst = 0, columnFirst = 0, rowSecond = 0, columnSecond = 0;
if (!infile1)
{
cout << "Error, file could not be opened!" << endl;
return 0;
}
if (!infile2)
{
cout << "Error, file could not be opened!" << endl;
return 0;
}
Data(infile1, firstMatrix, rowFirst, columnFirst,
infile2, secondMatrix, rowSecond, columnSecond);
infile1.close();
infile2.close();
int mult[MAX_ROWS][MAX_COLUMNS];
multiplyMatrices(firstMatrix, secondMatrix, mult, rowFirst,
columnFirst, rowSecond, columnSecond);
//displays the mult array.
for(int i = 0; i < rowFirst; ++i)
{
for(int j = 0; j < columnSecond; ++j)
{
cout<< '\t' << mult[i][j] << '\t';
if(j == columnSecond - 1)
cout << endl;
}
}
return 0;
}
void Data(ifstream& infile1, int firstMatrix[][MAX_COLUMNS], int rowFirst, int columnFirst,
ifstream& infile2,int secondMatrix[][MAX_COLUMNS], int rowSecond, int columnSecond)
{
while (!infile1.eof())
{
while(infile1 >> firstMatrix[rowFirst][columnFirst++]);
columnFirst--;
rowFirst++;
}
while (!infile2.eof())
{
while(infile2 >> secondMatrix[rowSecond][columnSecond++]);
columnSecond--;
rowSecond++;
}
}
void multiplyMatrices(int firstMatrix[][MAX_COLUMNS], int secondMatrix[][MAX_COLUMNS], int mult[][MAX_COLUMNS],
int rowFirst, int columnFirst, int rowSecond, int columnSecond)
{
if (columnFirst != rowSecond)
{
cout<<"Error: Matrices cannot be multiplied!";
}
else
{
// Initializing elements of matrix mult to 0.
for(int i = 0; i < rowFirst; ++i)
{
for(int j = 0; j < columnSecond; ++j)
{
mult[i][j] = 0;
}
}
// Multiplying matrix firstMatrix and secondMatrix and storing in array mult.
for(int i = 0; i < rowFirst; ++i)
{
for(int j = 0; j < columnSecond; ++j)
{
for(int k = 0; k<columnFirst; ++k)
{
mult[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
}
}
|