Aaron Collins
Aaron Collins

Reputation: 43

multiplying each element of one array by all the elements of a second array

I am having a difficult time multiplying elements that are in two array's.

    int[] firstArray = { 1,2,3,4 };
    int[] secondArray = { 10,20,30,40 };

I need to multiply the first element of the "firstArray" by each of the elements in the "secondArray". Then take the second element of the "firstArray" by each of the elements in the "secondArray", and so on until i have multiplied all of the elements in the first array by each of the elements in the second array.

so far I have figured out how to get the first element to do this by building a 3rd array

    int[] thirdArray = [4]

    for (int counter = 0; counter < thirdArray.Length; counter ++)
    thirdArray[counter] = firstArray[counter] * secondArray[counter];
    console.WriteLine(thirdArray[counter]);

This just takes the elements of the first array and directly multiply across to the second element. I should have 16 int results but if I change the thirdArray to [16] there is a out of range exception. if you can help it would be greatly appreciated.

Upvotes: 2

Views: 8041

Answers (5)

joce
joce

Reputation: 9902

Done in a single line, using LINQ:

var allMultiples = firstArray.SelectMany(a => secondArray.Select(b => a * b));

Upvotes: 0

Ben H
Ben H

Reputation: 494

Heck, you can even do away with the braces to denote scope, since there's only one operation in the scope of each iteration:

int[] firstArray = { 1, 2, 3, 4 };
int[] secondArray = { 10, 20, 30, 40 };
for (int i = 0; i < firstArray.Length; i++ )
    foreach (int second in secondArray)
        firstArray[i] *= second;

Upvotes: 0

Nikola Davidovic
Nikola Davidovic

Reputation: 8666

This should solve your problem:

int[] firstArray = { 1,2,3,4 };
  int[] secondArray = { 10,20,30,40 };
    int[] thirdArray = new int[firstArray.Length*secondArray.Length];
    for (int i = 0; i < firstArray.Length; i++)
    for (int j = 0; j < secondArray.Length; j++)
    {
        thirdArray[i*firstArray.Length + j] = firstArray[i] * secondArray[j];
        Console.WriteLine(thirdArray[i*firstArray.Length + j]);
    }

Upvotes: 1

Martin
Martin

Reputation: 16453

I believe this will achieve what you are looking for:

int[] thirdArray = new int[16];

for (int i = 0; i < 4; i++)
    for (int j = 0; j < 4; j++)
        thirdArray[i * 4 + j] = firstArray[i] * secondArray[j];

Upvotes: 3

dtb
dtb

Reputation: 217401

As an alternative approach, you could use LINQ for this:

var query = from x in firstArray
            from y in secondArray
            select x * y;

int[] thirdArray = query.ToArray();

Upvotes: 3

Related Questions