Write a C++ program that will add three matrices of any size from an input data
ID: 3546381 • Letter: W
Question
Write a C++ program that will add three matrices of any size from an input data file and write the result to an output data file. The input file should have the dimensions of the matrices on row 1 followed by the three matrices. Read the input data into matrices A, B, and C and calculate the value of matrix D and send its contents to the output data file. Print the program, the input data file, and the output data file for the two examples below.
this is the input file.
2 3
1 2 3
4 5 6
1 1 1
2 2 2
2 4 6
3 6 9
This is what I have so far but I keep getting an error "ISO C++ forbids variable-sized array A (and B, C, and D).
Here is my code. I can't seem to find the problem.
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
int Row, Col;
ifstream InFile("inputdata.txt");
InFile >> Row >> Col;
int A[Row][Col],B[Row][Col],C[Row][Col],D[Row][Col];
for(int i=0;!InFile.eof();i++)
{
for(int j=0;j<Col;j++)
{
if(i>=0 && i<=1)
{
InFile >> A[i][j];
}
else if(i>=2 && i<=3)
{
int k;
k=i-2;
InFile >> B[k][j];
}
else if(i>=4 && i<=5)
{
int k;
k=i-4;
InFile >> C[k][j];
}
else
{
cout << "Error" << endl;
}
}
}
InFile.close();
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
{
D[i][j]=A[i][j]+B[i][j]+C[i][j];
}
}
ofstream OutFile("D.dat");
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
OutFile << D[i][j] << " ";
OutFile << endl;
}
OutFile.close();
system("PAUSE");
return EXIT_SUCCESS;
}
Explanation / Answer
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
int Row, Col;
ifstream InFile("inputdata.txt");
InFile >> Row >> Col;
int A[100][100],B[100][100],C[100][100],D[100][100];
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
{
InFile >> A[i][j];
}
}
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
{
InFile >> B[i][j];
}
}
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
{
InFile >> C[i][j];
}
}
InFile.close();
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
{
D[i][j]=A[i][j]+B[i][j]+C[i][j];
}
}
ofstream OutFile("D.dat");
for(int i=0;i<Row;i++)
{
for(int j=0;j<Col;j++)
OutFile << D[i][j] << " ";
OutFile << endl;
}
OutFile.close();
system("PAUSE");
return EXIT_SUCCESS;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.