File I/O and Arrays. Please use C++. Part 3 - Calculate stats for two dimensiona
ID: 3597572 • Letter: F
Question
File I/O and Arrays. Please use C++.
Part 3 - Calculate stats for two dimensional array In this part, you will be working with a two dimensional array float arrayStats (string filename, float numbers [l [5]) The arrayStats function takes in two arguments: a filename and a 2D array of floats that can hold 5 floats in each row. The input file will have the same format as the file in Part 2 You can call fillArray in this function. The input file will have a variable number of rows but exactly 5 floats on each row, and a header line Format of Input File valu 4, 1, 2, 3.8, 5 2, 3.2, 4, 1, 0 6, 4, 0, 2.5, 1 5, -3, 2, 1, 0 el, value2, value3, val ue4, value5 Read in the values from the input file, then calculate the mean of every odd row and odd column (row/column 1, 3 ,...) and sum these values. Return the sum as a float. For this example, the sum of the means of the odd columns is 3.4 and the sum of the means of the odd rows is 3. So the function arrayStats should return 6 . 4 Mean of 4 1 2 3 5 row 1: 2 64 0 2-1 3 2 1 0 row 3: 1 WARNING: Make sure to do the calculations by looping over individual columns and rows. Values calculated using other methods may result in discrepancies with expected output in COG due to roundingExplanation / Answer
Hi,
here is the complete copyable code with comments.
float arrayStats(string filename,float numbers[][5])
{
fillArray(string filename,float numbers[][5]);// this function definition is not given, but it could be like below
/* filling array- feel free to remove if you already have a function for it*/
FILE *fp;
fp = fopen(filename,"r");
if ( fp != NULL )
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
fscanf( fp, "%lf", &(numbers[i][j]));
}
fscanf(fp, " ", NULL);
}
}
/* end of filling */
//variables to hold row and column means
float row1=0.0;
float row3=0.0;
float column1=0.0;
float column3=0.0;
int i,j;//loop variables
for(i=1;i<5;i=i+2)//looping through rows
{
for(j=0;j<5;j++)//loop of columns
{
if(i==1)//if 1st row add in row1
row1+=numbers[i][j];
else//else in 3rd row
row3+=numbers[i][j];
}
}
float row_mean=(row1/5)+(row3/5);//divide sum/count and add 2 means
//identical loop as abovem this time for columns
for(i=1;i<5;i=i+2)
{
for(j=0;j<5;j++)
{
if(i==1)
column1+=numbers[j][i];
else
column3+=numbers[j][i];
}
}
float column_mean=(column1/5)+(column3/5);
return column_mean+row_mean;//return sum of means
}
Thumbs up if this was helpful, otherwise let me know in comments
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.