0

I am trying to print out the total of the numbers inside of the 2D array.

I tried doing the thing that is in my code but it gives me the average of each row not the total of all numbers inside the row and column.

int[,] prices = new int[,]{ {475, 450, 450, 475 },

                          {425, 425, 425, 425 },

                          {410, 400, 400, 410 },

                          {400, 375, 375, 400 },

                          {350, 340, 340, 350 },

                          {325, 325, 325, 325 }};
int row;
int col;
int price;
int revSum;


Write("Enter a row number: ");
while (!(int.TryParse(ReadLine(), out row)) || !(row > 0 && row <= 6))
{
     Write("Invalid row number.  Please try again: ");
}

Write("Enter a col number: ");
while(!(int.TryParse(ReadLine(), out col)) || !(col >0 && col <= 4))
{
Write("Invalid col number. Please try again: ");
}

WriteLine($"\nThe price of row {row}, col {col} is ${prices[row - 1, col - 
1]}\n");

 revSum = 0;

for (int i = 0; i < prices.GetLength(0); i++)
{
revSum = 0;
for (int j = 0; j < prices.GetLength(1); j++)
{
revSum += prices[i, j];
}
WriteLine($"The total revenue is {i + 1} {(double)revSum / 7:N1}");

I would really like if the sum of all the numbers would print out.

  • You can get the sum of the all numbers inside the 2d array with int sum = prices.Cast().Sum(); – Slaven Tojić Jun 21 '19 at 20:36
  • Possible duplicate : https://stackoverflow.com/questions/19034970/sum-multidimensional-array-c-sharp – Slaven Tojić Jun 21 '19 at 20:37
  • I wonder why you wonder about getting some "average" number. After all, you are dividing your revSum by 7 there. Not sure why you think you need to do a division when all you seem to want is to sum up numbers. It's like: "Lets add 3 and 5... \[typing `(3+5)/2` into the calculator\]... Jolly gee, i expected to get 8, why do i get 4 instead? What's going on here? My calculator must be broken..." –  Jun 21 '19 at 21:02

0 Answers0