# Build 2D array and find the average of the array elements

Hi,

I'm trying to build a 2D array and find the average. I have no compilation error but the result is wrong.The average shoud be 6.38. Can someone please advise what is wrong? I do not wish to use pointer as I have yet to study.

//calculate the average for all values in 2D array
#include <iostream>
using namespace std;
const int maxRows = 2;
const int maxCols = 4;

//prototype declaration
double avg(const int [][maxCols], double &);
//void printArray (const int [][maxCols]);

int main()
{
double average, sumTotal = 0;

int table [maxRows][maxCols] =
{
{0, 1, 2, 3},
{10, 11, 12, 13}
};
average = avg(table, sumTotal);

cout << "The sum of all array elements is " << sumTotal << endl;
cout << "The average is " << average << endl;

return 0;
}

double avg(const int table [][maxCols], double & sumTotal)
{
int col, row;
double sum = 0;
for (row = 0; row < maxRows; row++)
{
for (col = 0; col < maxCols; col++)
sum += table [maxRows][maxCols];
}
sumTotal = sum;
return (sum / (maxRows * maxCols));
}

LVL 3
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
sum += table [maxRows][maxCols];

should be :

sum += table [row][col];
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
>> The average shoud be 6.38

The average for the array you have in your code should be 6.5 :

(0 + 1 + 2 + 3 + 10 + 11 + 12 + 13) / 8 = 52 / 8 = 6.5
0
Author Commented:
i'm so careless. Thanks for your help!
0
Commented:
No problem ;) It happens to all of us heh :)
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.