Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum, Subtract and Multiply arrays

Tags:

c#

I've got the following arrays:

int[,] myArray1 = new int[2, 3] { { 1, 2, 3 }, { 4, 6, 8 } };
int[,] myArray2 = new int[2, 3] { { 6, 4, 3 }, { 8, 2, 8 } };

What I'd like to know how to do is:

  1. Create a new array with the sum of myArray1 and myArray2
  2. Create a new array with the subtraction of myArray1 and myArray2
  3. Create a new array with the multiplication of myArray1 and myArray2

Result of sum would be:

int[,] myArray3 = new int[2, 3] { { 7, 6, 0 }, { -4, 4, 0 } };

Result of subtraction would be:

int[,] myArray3 = new int[2, 3] { { 5, 2, 6 }, { 12, 8, 16 } };

Result of multiplication would be:

int[,] myArray3 = new int[2, 3] { { 6, 8, 9 }, { 32, 12, 64 } };

Can this be done similar to printing out the arrays, with for loops? I tried looking for examples but found none that I could use for my specific problem.

like image 618
Yushell Avatar asked Jan 14 '23 17:01

Yushell


2 Answers

int[,] a3 = new int[2,3];

for(int i = 0; i < myArray1.GetLength(0); i++)
{
for(int j = 0; j < myArray1.GetLength(1); j++)
{
a3[i,j] = myArray1[i,j] + myArray2[i,j];
a3[i,j] = myArray1[i,j] - myArray2[i,j];
a3[i,j] = myArray1[i,j] * myArray2[i,j];
}
}

need to store a3 before doing a new calculation obviously

like image 160
Sayse Avatar answered Jan 21 '23 16:01

Sayse


For Sum:

for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                myArray3[i, j] = myArray1[i, j] + myArray2[i, j];
            }                
        }

For Subtraction:

for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                myArray3[i, j] = myArray2[i, j] - myArray1[i, j];
            }                
        }

For Multiplication:

for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                myArray3[i, j] = A[i, j] * B[i, j];
            }
        }
like image 20
Shaharyar Avatar answered Jan 21 '23 17:01

Shaharyar