Johnny
Johnny

Reputation: 53

Calculate the product of two columns in an array then the sum C#

i have an array with columns where i need to do the SUM of the product of each row for 2 columns.

Example:

1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

What i want to do is the following for col2 and col3:

Total = 2*3 + 2*3 + 2*3 + 2*3 = 24

Below is my code for this operation:

int product_col2Xcol3 = 0;
int sum_totalcol2Xcol3 = 0;

//Calculations of the SUM(Product) of col2 and col3
for (int row = 0; row < r; row++)
{
    for (int j = 0; j < r; j++)
    {

        product_col2Xcol3 = matrix[j, col2] * matrix[j, col3];
        sum_totalcol2Xcol3 = sum_totalcol2Xcol3 + product_col2Xcol3 ;


    }

}
Console.WriteLine("Total is :" + 2*sum_totalcol2Xcol3 );

I am getting a result but the answer is wrong its a very big number. Please help. Thank you!

Upvotes: 0

Views: 349

Answers (3)

Rashedul.Rubel
Rashedul.Rubel

Reputation: 3584

  int[,] matrix={
                    {1, 2, 3, 4},
                    {1, 2, 3, 4},
                    {1, 2, 3, 4},
                    {1, 2, 3, 4}
                };


  int product_col2Xcol3 = 0;
  int sum_totalcol2Xcol3 = 0;

  // if you precisely want the column 1 and 2 of each row then do as below:
  for (int row = 0; row <matrix.GetLength(0); row++)
  {

      product_col2Xcol3 = matrix[row, 1] * matrix[row, 2];
      sum_totalcol2Xcol3 += product_col2Xcol3;

  }
  Console.WriteLine("Total is :" + sum_totalcol2Xcol3);

Upvotes: 2

Hasson
Hasson

Reputation: 1914

int product_col2Xcol3 = 0;
int sum_totalcol2Xcol3 = 0;

//Calculations of the SUM(Product) of col2 and col3
for (int row = 0; row < number_of_rows; row++)
{

     product_col2Xcol3 = matrix[row, col2] * matrix[row, col3];
     sum_totalcol2Xcol3 = sum_totalcol2Xcol3 + product_col2Xcol3 ;

}
Console.WriteLine("Total is :" + sum_totalcol2Xcol3 );

Upvotes: 1

Jeroen van Langen
Jeroen van Langen

Reputation: 22073

What does the for (int j = 0; j < r; j++) do? You're calculating the matrix[j, col2] * matrix[j, col3] * r times

int product_col2Xcol3 = 0;
int sum_totalcol2Xcol3 = 0;

//Calculations of the SUM(Product) of col2 and col3
for (int row = 0; row < r; row++)
{
    product_col2Xcol3 = matrix[row, col2] * matrix[row, col3];
    sum_totalcol2Xcol3 = sum_totalcol2Xcol3 + product_col2Xcol3 ;
}

// why 2* ?????? think it shouldn't be there.
Console.WriteLine("Total is :" + 2*sum_totalcol2Xcol3 );

or

int sum_totalcol2Xcol3 = 0;

for (int row = 0; row < r; row++)
{
    sum_totalcol2Xcol3 += matrix[row, col2] * matrix[row, col3];
}
Console.WriteLine("Total is :" + sum_totalcol2Xcol3 );

Upvotes: 2

Related Questions