What is the C plus plus program to find the sum of elements above and below the diagonal?

In order to sum the elements above and below the diagonal, the array must be perfectly square. To guarantee the array is square we'll use a class template to implement an array of N arrays of length N. The following program demonstrates the minimal implementation required to sum the elements above and below the diagonal and will work for any array type for which operator+ is defined, which includes all the built-in numeric types such as int and double. operator<< has also been overloaded to assist in printing the array.

#include<iostream>

#include<array> #include<random>

template<typename T, const size_t N>

class square_array {

private:

std::array<std::array<T, N>, N> data; // the 2D array

public:

T sum_above (void) const;

T sum_below (void) const;

const std::array<T, N>& operator[] (const size_t row) const { return data[row]; }

std::array<T, N>& operator[] (const size_t row) { return data[row]; }

};

template<typename T, const size_t N>

T square_array<T, N>::sum_above (void) const {

T sum = 0;

for (size_t row=0; row<N; ++row)

for (size_t col=row+1; col<N; ++col)

sum += data[row][col];

return sum;

}

template<typename T, const size_t N>

T square_array<T, N>::sum_below (void) const {

T sum = 0;

for (size_t row=0; row<N; ++row)

for (size_t col=0; col<row; ++col)

sum += data[row][col];

return sum;

}

template<typename T, const size_t N>

std::ostream& operator<< (std::ostream& os, const square_array<T, N>& sa) {

os << '{';

for (size_t row=0; row<N; ++row) {

os << '{';

for (size_t col=0; col<N; ++col) {

os << sa[row][col];

if (col<N-1) os << ',';

}

os << '}';

if (row<N-1) os << ',';

}

os << '}';

return os;

}

int main (void) {

std::default_random_engine engine;

std::uniform_int_distribution<int> dist (1, 9);

square_array<int, 5> sa; // 5x5 square array of int

// initialise elements with random values (range: 1 to 9)

for (size_t row=0; row<5; ++row)

for (size_t col=0; col<5; ++col)

sa[row][col] = dist (engine);

std::cout<<"Array = "<<sa<<std::endl;

std::cout<<"Sum above: "<<sa.sum_above()<<std::endl;

std::cout<<"Sum below: "<<sa.sum_below()<<std::endl;

}