Operations with arrays in C ++

0

To sum the items of an array (primary diagonal and secondary diagonal) I was able to write the following code. Can someone help me make the code leaner? so I compare the codes ... C ++: And I would like to know if there is any function for this type problem ...

(Can be with other libraries that are not)

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; 
}
    
asked by anonymous 07.08.2017 / 00:49

2 answers

1

You can do everything in just for by calculating the two things simultaneously. And have only one condition because when i ends j also ends.

It can look 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; 
}
    
07.08.2017 / 01:20
1

I made a code here, it was much simpler, there is 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 at Ideone .

    
07.08.2017 / 01:10