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
Here's some example code that will statically create a 2D array of dimensions 5x5. It populates it like your example above, and calculates the sum of the elements on the diagonal (note that this doesn't equal 117).

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
#include <iostream>
#include <string>

using namespace std;
int main()
{
	int myArray[5][5];

	// Populate array
	for(int i=0; i<5; i++)
	{
		for(int j=0; j<5; j++)
		{
			myArray[i][j] = (i)*5 + (j+1);
		}
	}

	// Calculate sum of elements on diagonal
	int sum = 0;
	for(int i=0; i<5; i++)
	{
		sum += myArray[i][i];
	}

        return 1;
}

Sigh. http://www.cplusplus.com/forum/general/21169/

I'm not sure whether I'm more disappointed with the OP or with the blithe answer. What ever happened to figuring stuff out for yourself?
... disappointed with ... the blithe answer.


Hmmmm....I don't get it. Did I misinterpret something or write something incorrectly? If so, please let me know!
Ahhhh ok, he wanted the sum of both diagonals, not just the main diagonal in a matrix (maths). My bad...
No, you should help people learn stuff for themselves instead of just giving answers.
Topic archived. No new replies allowed.