C++ code to find out the sum of the special matrix elements

C++Server Side ProgrammingProgramming

Suppose, we are given a square matrix of dimensions n * n. The following values of the matrix are called special elements −

  • Values that are in the main diagonal.

  • Values that are in the second diagonal.

  • Values of the row that has exactly (n - 1 / 2) rows above it and the same number of rows below it.

  • Values of the column that has exactly (n - 1 / 2) columns at its left and right.

We find out the sum of these special values in the matrix.

So, if the input is like n = 4, mat = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}, then the output will be 107.

Steps

To solve this, we will follow these steps −

res := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   for initialize j := 0, when j < n, update (increase j by 1),
do:
   if i is same as j or i is same as n / 2 or j is same as n/ 2 or i + j is same as n - 1, then:
      res := res + mat[i, j]
print(res)

Example

Let us see the following implementation to get better understanding

#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, vector<vector<int>> mat) {
   int res = 0;
   for (int i = 0; i < n; i++)
   for (int j = 0; j < n; j++){
      if (i == j || i == n / 2 || j == n / 2 || i + j == n - 1)
         res += mat[i][j];
   }
   cout << res << endl;
}
int main() {
   int n = 4;
   vector<vector<int>> mat = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
   solve(n, mat);
   return 0;
}

Input

4, {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}

Output

107
raja
Updated on 11-Mar-2022 05:56:21

Advertisements