At the start of your program, you are going to need to declare a 4 by 4 element two
dimensional array. That is, 4 dimensions by 4 dimensions for a total of 16 elements in the
array. Your program needs to read in from a file, values.txt, where each line of the le
will have a comma delimited list of integer values with 4 lines in total.
Each value of each line should be placed into the array, with the line corresponding
to the row index. The first value in the line goes into the first, index 0, column of the
array. So the array is filled row by row, from left to right.
Once furnished, you need to compute the following:
- Row Totals: The sum of all elements per row
- Column Totals: The sum of all elements per column
- Array Average: The average of all elements in the array
The output format should be displayed as follows (with example values):
Row Total 1: 4
Row Total 2: 4
Row Total 3: 4
Row Total 4: 4
Col Total 1: 4
Col Total 2: 4
Col Total 3: 4
Col Total 4: 4
Array Average: 1
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main (){
int values[4][4];
//The file name
const string FILE_NAME="values.txt";
//Open the file
ifstream ifstreamValuesFile;
ifstreamValuesFile.open(FILE_NAME);
string line;
int rows=0;
float sum=0;
while (!ifstreamValuesFile.eof()){
getline(ifstreamValuesFile,line);
stringstream ss(line);
int columns=0;
while(ss.good())
{
string substr;
getline(ss, substr,',');
values[rows][columns]=stoi(substr);
sum+=values[rows][columns];
columns++;
}
rows++;
}
//close files stream
ifstreamValuesFile.close();
for(int r=0;r<4;r++){
int rowTotal=0;
for(int c=0;c<4;c++){
rowTotal+=values[r][c];
}
cout<<"Row Total "<<(r+1)<<": "<<rowTotal<<"\n";
}
for(int c=0;c<4;c++){
int colTotal=0;
for(int r=0;r<4;r++){
colTotal+=values[r][c];
}
cout<<"Col Total "<<(c+1)<<": "<<colTotal<<"\n";
}
float arrayAverage=sum/16.0;
cout<<"Array Average: "<<arrayAverage<<"\n";
system("pause");
return 0;
}
Comments
Leave a comment