Can someone please tell me how to pass a 2d Array to a function and then have that function return the highest number in the array to the main function?
So I only have to use the first parameter for the array?
this is my array double food [3][7]
and massing it to a function would look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
constint ROWS = 3;
constint COLUMNS = 7;
double getLargest (array[][3])
{
double high = array[0][0]
//get HIGHEST number in the array
for (int a = 0; a <= ROWS; a++)
{
for(int b = 0; b <=COLUMNS; b++)
{
if (array[ROWS][COLUMNS] > high)
high = array [a][b];
}
}
return high;
}
So I only have to use the first parameter for the array?
no, you have to use all dimensions except the first one or you may include first one as well but it's not deeded,
you fogod to specify type of the array pased into function:
1 2 3 4 5 6 7 8 9 10 11
int ROWS = 3; //no need for const
constint COLUMNS = 7; //all dimenstions must be const except first one
double getLargest (double array[][COLUMNS]) { //or any other type
double high = array[0][0]
for (int a = 0; a < ROWS; ++a)
for(int b = 0; b < COLUMNS; ++b)
if (array[ROWS][COLUMNS] > high)
high = array [a][b];
return high;
}
arrays are always passed by reference to the functions.
but you may use some other metods like copying array and the passing the copy.
I'm not shure if that would be a smart move tough...
unless I'm mistaken, this should get the lowest from the array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
double getLeast (double lowFood[][COLUMNS])
{
double low = lowFood[0][0];
//get LOWEST number in the array
for (int c = 0; c <= ROWS; c++)
{
for(int d = 0; d <=COLUMNS; d++)
{
if (lowFood[ROWS][COLUMNS] <= low)
low = lowFood[c][d];
}
}
return low;
}
but the only thing that the this function only returns is 0.0 and not anything else.
Line 9 is wrong and you are going one too high in the for loops
how so? The opposite, get the highest number, works like its supposed to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
double getMost (double highFood[][COLUMNS])
{
//accumulator
double high = highFood[0][0];
//get HIGHEST number in the array
for (int a = 0; a <= ROWS; a++)
{
for(int b = 0; b <=COLUMNS; b++)
{
if (highFood[ROWS][COLUMNS] >= high)
high = highFood[a][b];
}
}
return high;
}
however, my get average isn't working correctly either, the math isn't correct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
constint COLUMNS = 7;
cons int ROWS = 3;
double getAverage (double aveFood[][COLUMNS])
{
cout << fixed << showpoint << setprecision(1);
double mean = 0.0;
double total = 0.0;
//get MEAN number in the array
for (int e = 0; e <= ROWS-1; e++)
{
for(int f = 0; f <= COLUMNS-1; f++)
{
total += aveFood[e][f];
}
}
mean = total / (ROWS * COLUMNS);
return mean;
}