Question #52411

Write a C++ program that takes a NxN 2-dimensional square array of
integers. If the summation of all array elements is odd, the function returns the
summation of the elements in the 2 diagonals of the array, otherwise it returns -1.

Expert's answer

Answer to Question #52411 - Programming, C++

Question

Write a C++ program that takes a NxN 2-dimensional square array of integers. If the summation of all array elements is odd, the function returns the summation of the elements in the 2 diagonals of the array, otherwise it returns -1.

Answer

#include <iostream>
using namespace std;
int main()
{
    int n, sum = 0, sum_d = 0;
    cout << "n = ";
    cin >> n;
    cout << endl;
    int a[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
        {
            cout << "a[" << i << "][" << j << "] = ";
            cin >> a[i][j];
        }
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            sum = sum + a[i][j];
            if (i == j || j == n - i + 1)
                sum_d = sum_d + a[i][j];
        }
    }
    if (sum % 2 == 0)
        cout << -1;
    else
        cout << sum_d;
}
LATEST TUTORIALS
APPROVED BY CLIENTS