Solved

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

Posted on 2008-02-06
Medium Priority
314 Views
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));
}

0
Question by:dandeliondream
• 3

LVL 53

Accepted Solution

Infinity08 earned 500 total points
ID: 20836872
sum += table [maxRows][maxCols];

should be :

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

LVL 53

Expert Comment

ID: 20836891
>> 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

LVL 3

Author Comment

ID: 20836964
i'm so careless. Thanks for your help!
0

LVL 53

Expert Comment

ID: 20838866
No problem ;) It happens to all of us heh :)
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.htâ€¦
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticallâ€¦
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
###### Suggested Courses
Course of the Month5 days, 3 hours left to enroll