Bennett
Bennett

Reputation: 738

How to work with the contents of my array?

I have an array that represents three regions (the regions being rows 1,2,3) and each number represents the stores profits in that region. This is an assignment and I am required to use a multidimensional or jagged array; I realize this would be easier if I made three separate arrays. I can't quite figure out how to use the data to average each row (region).

int[][] stores = {new int [] {2000,4000,3000,1500,4000},
                  new int [] {6000,7000,8000},
                  new int [] {9000,10000}};

Upvotes: 0

Views: 43

Answers (2)

Ckrempp
Ckrempp

Reputation: 324

Another option would be to use a foreach loop like this:

int[][] stores = {new int [] {2000,4000,3000,1500,4000},
          new int [] {6000,7000,8000},
          new int [] {9000,10000}};

foreach (var row in stores)
{
    int average = 0;

    foreach (var item in row)
    {
        average += item;
    }

    average /= row.Length;

    Console.Write("This is your result: " + average + "\n");
}

The benefit of this code segment is that it you are not dependent on knowing the data within your multidimensional array. It will perform the average calculations for each row, and output accordingly.

Upvotes: 0

Simon Whitehead
Simon Whitehead

Reputation: 65087

The first index is the row .. at that point you're accessing the underlying array.

Therefore, your averages can be calculated based purely on that first index. Using LINQ, that would look something like this:

int[][] stores = {new int [] {2000,4000,3000,1500,4000},
              new int [] {6000,7000,8000},
              new int [] {9000,10000}};

Console.WriteLine("Row 1 average: {0}", stores[0].Average());
Console.WriteLine("Row 2 average: {0}", stores[1].Average());
Console.WriteLine("Row 3 average: {0}", stores[2].Average());

Working sample: http://ideone.com/3GQFm3

Upvotes: 2

Related Questions