Operations with C++ matrices

Asked

Viewed 3,167 times

0

To perform the sum of items of a matrix (primary diagonal and secondary diagonal) I was able to write the following code. Can someone help me dry up the code? so I can compare the codes... C++: And I wonder if there’s any function for that kind of problem...

(It may be with other libraries than)

int main()
{
int matriz[3][3] = {{1, 2, 3},
                    {4, 5, 6},
                    {7, 8, 9}};

        int somaP = 0;
        for(int i = 0, j = 0; i < 3; i++, j++)
        {
               somaP += matriz[i][i];
        }
        cout << somaP << endl;

        int somaS = 0;
        for(int x = 0, y = 2; (x < 3) && (y > -1); x++, y--)
            {
                somaS += matriz[x][y];
            }
        cout << somaS << endl;

    return 0; 
}
  • Compare with what?

  • was not to compare, only to realize the sum of the diagonal Prim. and after the secund.

2 answers

1

I made a code here, it’s much simpler, there’s not much to explain:

int matriz[3][3] = {{1, 2, 3},
                    {4, 5, 6},
                    {7, 8, 9}};

int somaP = 0, somaS = 0;

for(int i = 0; i < 3; i++)
{
    somaP += matriz[i][i];
    somaS += matriz[i][2-i];
}

cout << somaP << endl << somaS;

See working on Ideone.

  • very nice,man !!

  • @Elderson If the answer is right, please mark it as correct.

1


You can do it all in one for calculating both things simultaneously. And have only one condition because when the i ends the j also ends.

You can stay like this:

int main()
{
    int matriz[3][3] = {{1, 2, 3},
                    {4, 5, 6},
                    {7, 8, 9}};

    int somaP = 0, somaS = 0;

    for(int i = 0; i < 3; i++)  //quando i termina j também terminava
    {
        somaP += matriz[i][i];
        somaS += matriz[i][3-1-i]; //este corresponde ao seu antigo y--, que decresce
    }

    cout << somaP << endl;
    cout << somaS << endl;

    return 0; 
}
  • It cleared the idea. Now I’m trying to assimilate the mathematical logic of [3-1-i].

  • @Elderson I put 3-1-i purposely, to be clear that it is tamanho-1-i. If you want to simplify you can put 2-i. The last element is tamanho-1 soon if you go on 2 element, the 2 of the end will be the ultimo-2, soon it will be tamanho-1-2. If it’s not very clear just say I supplement the answer with this detail.

  • Now yes, it was more explanatory, bro ! ;D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.