calculate the sum of diagonals in a matrix

前端 未结 5 1647
梦如初夏
梦如初夏 2020-12-16 01:45

I need to calculate the sum of two diagonals in a matrix in C++, I already have a solution for that but I must be dumb because I cant understand what it is doing, so I would

5条回答
  •  佛祖请我去吃肉
    2020-12-16 02:41

    you must use i + j == n + 1 instead of i + j == n - 1 for secondary diagonal i.e

    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= n; j++)
        {
            if(i == j) 
                d += a[i][j]; //principal diagonal 
            if(i + j == n+1)
                s += a[i][j];//secondary diagonal
    
        }
    }
    

提交回复
热议问题