# How do I create a GetAverage method for a 3x3 retangular array in C#?

1 Reputation point
2022-02-28T02:05:46.617+00:00

I am having trouble figuring this out. I need to put items in a 3x3 rectangular array and then average them. This is my code for putting the values in the array:

``````                    // Add Values to Rectangular Array
for (int i = 0; i < retailPrices.GetLength(0); i++)
{
for (int j = 0; j < retailPrices.GetLength(1); j++)
{
retailPrices[i, 0] = wholesaleCost;
retailPrices[i, 1] = markupPercentage;
retailPrices[i, 2] = futureValue;
}
}
``````

This is my code for my GetAverage Method:

``````  private decimal GetAverage(decimal[,] retailPrices)
{
decimal sum = 0m;
for (int i = 0; i < retailPrices.GetLength(0); i++)
{
for (int j = 0; j < retailPrices.GetLength(1); j++)
{
sum += retailPrices[i, j];
}
}
decimal average = sum / retailPrices.GetLength(0);
return average;
}
``````

What is the correct way to do this? What am I doing incorrectly? Please correct my code.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,356 questions

1. 112.9K Reputation points
2022-02-28T09:44:12.783+00:00

To calculate the average of all nine values:

``````using System.Linq;
. . .
private decimal GetAverage( decimal[,] retailPrices )
{
return retailPrices.Cast<decimal>( ).Average( );
}
``````

2. 57,646 Reputation points
2022-02-28T17:54:38.557+00:00

You need to calc the size of the arrays.

``````   private decimal GetAverage(decimal[,] retailPrices)
{
decimal sum = 0m;
decimal count =0m;
for (int i = 0; i < retailPrices.Length; i++)
{
count += retailPrices[i].Length;
for (int j = 0; j < retailPrices[i].Length; j++)
{
sum += retailPrices[i, j];
}
}
decimal average = sum / count;
return average;
}
``````