I'm working with 2D arrays. I'm reading information from a text file and printing out the information, also attaching that info to a 2D array. I need to calculate the sum and average of each row and column. I can figure out how to do the math, but I'm stumped on what to pass to my functions so I can use the array to calculate my rows and columns.
My first function worked with just getData() (it worked in main and the function itself) I want to include parameters but I'm not sure of the correct way to do it?
Can I use the same parameters all through the code?
int array2D[15][15];
//PROTOTYPES:
void getData(int i, int j);
void rowsum();
//Function 1: Read in a file to an array
void getData(int i, int j)
{
ifstream input; // ifstream
input.open("num.txt"); // open text file containing the information
for (int i = 0; i < col; i++) //nested for loop to assemble .txt into a 2D Array
{
for (int j = 0; j < row; j++)
{
input >> array2D[i][j];
cout << array2D[i][j];
cout << " ";
}
}
}
int main()
{
//Call functions
getData(array2D);
system("pause");
return 0;
}
just run the loops like you did in getData but insead of input and output add to a variable the number from array2D[i][j] and in another variable add the number from array2D[j][i] for each iteration of j for
so after you done with the second loop you output both variable divided by the number of rows or colums accordingly
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
usingnamespace std;
constint ROW_COUNT = 15;
constint COL_COUNT = 15;
//PROTOTYPES:
void getData(int data[ROW_COUNT][COL_COUNT]);
int rowSum(int data[ROW_COUNT][COL_COUNT], int row);
int colSum(int data[ROW_COUNT][COL_COUNT], int col);
int colAverage(int data[ROW_COUNT][COL_COUNT]);
int rowAverage(int data[ROW_COUNT][COL_COUNT]);
int main()
{
int data[ROW_COUNT][COL_COUNT];
getData(data);
system("pause");
return 0;
}
void getData(int data[ROW_COUNT][COL_COUNT])
{
ifstream input("num.txt");
if (!input)
{
cerr << "\aERROR opening file - abort";
exit(EXIT_FAILURE);
}
for (int row = 0; row < ROW_COUNT; row++) //nested for loop to assemble .txt into a 2D Array
{
for (int col = 0; col < COL_COUNT; col++)
{
input >> data[row][col];
}
}
}
int rowSum(int data[ROW_COUNT][COL_COUNT], int row)
{
// TODO - place your code here
}
int colSum(int data[ROW_COUNT][COL_COUNT], int col)
{
// TODO - place your code here
}
int colAverage(int data[ROW_COUNT][COL_COUNT])
{
// TODO - place your code here
}
int rowAverage(int data[ROW_COUNT][COL_COUNT])
{
// TODO - place your code here
}