HOw will i make a 5 X 5 2D array w/ diagonal sum.

5 X 5 Two dimensional integer array in the main function and its diagonal sum.should i use 3 pre-defined functions?

example like this :



1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

sum is = 117
It seems that a pre-defined structure would be useful, but this is simple enough that you could take any square matrix.

The sum is easy enough to compute with a couple of loops, making sure not to add the center value in an odd matrix more than once.

Hope this helps.
For your amusement, and mine...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>

const int kDimension = 5;

int main()
{
  int matrix[kDimension][kDimension];
  int value = 1;
  for (int i = 0; i < kDimension; ++i)
    for (int j = 0; j < kDimension; ++j) {
      matrix[i][j] = value++;
      std::cout << std::setw(2) << matrix[i][j] <<
        (!((j + 1) % kDimension) ? '\n' : ' ');
    }
  value = 0;
  for (int i = 0, n = 1; i < kDimension; ++i, ++n)
    for (int j = 0; j < kDimension; ++j, ++n)
      if (!(n % kDimension) && (!(kDimension % 2) ||
        n / kDimension != kDimension / 2 + 1))
        value += matrix[i][j];
  for (int i = kDimension - 1, n = 0; i >= 0; --i, ++n)
    for (int j = kDimension - 1; j >= 0; --j, ++n)
      if (!(n % kDimension))
        value += matrix[i][j];
  std::cout << "\nSum is: " << value << std::endl;
  return 0;
}


~psault
How is that amusing? Someone asks for help and you post code you knew would be cryptic to a beginner. Get over yourself douche bag.
1) This is the General C++ Forum
2) Why don't you watch your mouth?

~psault
Topic archived. No new replies allowed.