ryanh92
ryanh92

Reputation: 15

multiplying 2D arrays in C#

I am quite new to C# and I need some help with multiplying two numbers from a 2d array. I have this code:

int[,] myArray = { {50,74}, {9,88}, {75,53}, {46,98}, {100,99} };

I need to multiply each pair e.g. 50 * 0.4 and 74 * 0.6, then the two answers from each added together to get my total and the same with the others. Any help would be much appreciated, Thank you

Upvotes: 0

Views: 4539

Answers (2)

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9201

First, to go through all pairs, we will need to know how long your array is. To achieve that, we can use myArray.GetLength(0). This will return the total number of elements in the first dimension. Using only Length would return the total number of elements, which is not what we want.

Once we have that, we can loop through all pairs with a classic for loop.

For each pair, we can multiply the first element, myArray[i,0] by 0.4d and the other one, myArray[i,1], by 0.6d. The d here indicate the double data type. int won't do it here, because we have a number with decimals.

We simply add up the result of those two operations and add it as a new entry in our final list.

Here's the code:

int[,] myArray = { { 50, 74 }, { 9, 88 }, { 75, 53 }, { 46, 98 }, { 100, 99 } };

var result = new List<double>();
for (int i = 0; i < myArray.GetLength(0); i++)
{
    result.Add(myArray[i,0] * 0.4d + myArray[i,1] * 0.6d);
}

If your final list explicitly needs to be an array, you can use this instead:

int arrayLength = myArray.GetLength(0);
double[] result = new double[arrayLength];
for (int i = 0; i < arrayLength; i++)
{
    result[i] = myArray[i, 0] * 0.4d + myArray[i, 1] * 0.6d;
}

It's pretty much the same thing, but we first need to define an array with the size of our collection.

Upvotes: 1

Ian CT
Ian CT

Reputation: 1411

Simply the following:

double[] result = new double[myArray.GetLength(0)];
for(int i = 0; i < myArray.GetLength(0); ++i)
    result[i] = myArray[i, 0] * 0.4 + myArray[i, 1] * 0.6;
// result now contains what you need

The first index of multidimensional "2D" arrays refers to row position (each constituent array) and the second index refers to the column position (position in each constituent array).

GetLength(0) means getting the 0th dimension length of your multidimensional array. In this case, it is 5 because there are five rows in your array. On the other hand GetLength(1) will return 2 because there are 2 columns.

Upvotes: 1

Related Questions