this is what I am supposed to do and what its supposed to look like:
Write 3 functions:
a) Function fill2DArray will fill each element in a 2D array with a random number between -25 to 25 (inclusive). It takes in 3 inputs and returns nothing back to the calling function.
b) Function print2DArray will print out the elements in the 2D array. The 2D array, row size and column size will be passed in as inputs with no return value back to the caller.
c) A function called largestColSum that calculates and returns the largest possible sum of entries of any column in a 2-dimensional array. It has 3 input parameters.
You should see the following output using the main program provided above:
Part A:
-15 24 -16 9 7
12 12 23 20 -6 // the numbers are supposed to be properly aligned .
-20 6 -5 -6 4
-3 20 5 15 6
10 -17 11 14 -11
Largest column sum = 52
My code that doesn't match what you see above - please help! Ignore the extra "includes..." that's for something else. Would appreciate if someone could edit my functions and send it back to me. thanks
// part a functions
void fill2DArray(int a[][5], int r, int c) {
for(int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
a[i][j] = (rand() % 50) - 25;
}
}
}
void print2DArray(int a[][5], int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if(i < 0 || j < 0) {
cout<< a[i][j] << "";
} else
cout<< a[i][j] << " ";
}
cout << endl;
}
}
int largestColSum(int a[][5], int r, int c) {
int col[5];
int max = col[0];
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++) {
col[i] = col[i] + a[i][j];
if(max < col[i]) {
max = col[i];
}
}
}
}
int main () {
cout << "Part A:\n";
srand(time(0)); //Commented out for testing purpose
int x[5][5] = {};
fill2DArray(x, 5, 5);
print2DArray(x, 5, 5);
cout << "Largest column sum = " << largestColSum (x, 5, 5) << endl;
cout << endl;
return 0;
}
void print2DArray(int a[][5], int r, int c) {
for ( int i = 0; i < r; i++ ) {
for ( int j = 0; j < c; j++ ) {
if ( i < 0 || j < 0 ) {
cout<< a[i][j] << "";
}
else
cout<< a[i][j] << " ";
}
cout << endl;
}
}
What is the purpose of the if? When is i or j less than 0 on these loops?
1 2 3 4 5 6 7 8 9 10 11 12 13
int largestColSum(int a[][5], int r, int c) {
int col[5];
int max = col[0]; // use of uninitialized value
for ( int i = 0; i < r; i++ ) {
for ( int j = 0; j < c; j++ ) {
col[i] = col[i] + a[i][j]; // use of uninitialized value
if ( max < col[i] ) {
max = col[i];
}
}
}
// your function does not return any int value
}
Would it make sense to change the order to:
set max to a very small value*
FOR EACH column DO
compute sum of whole column
update max (if necessary)
return max