how to calculate the sum of primary diagonal matrix and secondary diagonal matrix using c++

Calculate the Sum of Primary and Secondary Diagonal Matrix in C++

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the size of the square matrix: ";
    cin >> n;

    int matrix[n][n];
    cout << "Enter the elements of the matrix: ";
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> matrix[i][j];
        }
    }

    int primarySum = 0, secondarySum = 0;
    for (int i = 0; i < n; i++) {
        primarySum += matrix[i][i];
        secondarySum += matrix[i][n - 1 - i];
    }

    cout << "Sum of primary diagonal: " << primarySum << endl;
    cout << "Sum of secondary diagonal: " << secondarySum << endl;

    return 0;
}

This C++ program calculates the sum of the primary and secondary diagonals of a square matrix. It first takes the size of the square matrix as input from the user and then prompts the user to enter the elements of the matrix. After obtaining the matrix elements, the program iterates through the matrix to calculate the sum of the elements on the primary and secondary diagonals. Finally, it prints out the sums of the primary and secondary diagonals.

This program utilizes nested loops to iterate through the matrix and calculate the sums of the primary and secondary diagonals. The primary diagonal elements have the same row and column indices, while the secondary diagonal elements have row indices that are in ascending order and column indices that are in descending order.