Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Averages in multi arrays

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Anyone with some help. I am trying to find the average of each element of a multi-dimensional array. I can only get the average for just one row. Here is the code I am trying.

double average(double intarray[4][4], double count);

int main()

{
double intarray[4][4]={4,3,2,1,
1,2,3,4,
4,3,2,1,
1,2,3,4}
cout<<endl
<<&quot;Average = &quot;
<< average(intarray,(sizeof intarray)/(sizeof intarray[0]));
cout<<endl;

return 0;
}
double average(double intarray[4][4], double count)
{
double sum = 0.0;
for (int i = 0; i < count; i++)
for (int j =0; j < count; j++)
sum += intarray [j];

return sum/count;
}

 
Try nesting your for..next loops.

Also - please don't post student assignments here. Some schools (like Georgia Tech) will expel you for it.

Chip H.
 
I am confused by what you mean. I thought I did nest the inner loop. Still does not work. Just need some more direction have spent too many hours on this one aspect of project.
 
Alright, a few things wrong.

First, you're passing sizeof the array (assuming units of a double) = 16, then sizeof intarry[0] which is the first row, = 4. So the count you're passing = 4, which is correct (albeit a strange way to do it) as far as your for loops are set up.

In the loop, the statement
Code:
   sum += intarray[j];
should generate an error in any self-respecting compiler. intarray[j] is a pointer to a row of 4 doubles, and cannot be added that way. Change it to
Code:
   sum =+ intarray[i][j];
so you give the row # and col # of the array element you want to add.

With that change, you are correctly summing up all 16 numbers. What you return is that sum divided by 4 (count). It's giving the average sum across a row, 10. I assume you want the average value of the elements, not the rows, so make it
Code:
   return sum/(count*count);
and it should be relatively happy.

Don't forget the ; at the end of your array declaration. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
>sum += intarray[j];<

Ooops. Tek-Tips ate my
Code:
[i]
. Should have been
Code:
intarray[i][j];
like icrf says.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top