How do you add 2D array elements diagonally?

In a C++ program I have a 2D array of integers. What kind of code would I need to sum each diagonal row of integers going from array[i][j] = (0, 0) to array[i][j] = (nmax, mmax) and assign the sum of each row a cell on a 1D array? I have found code for summing just the center row but not each consecutive row like this.
Last edited on
Start with a simple example.

1 2 3
4 5 6
7 8 9

What answer would you expect?


> I have found code for summing just the center row but not each consecutive row like this.
You need to practice writing your own code for every problem.
Every time you search for a quick and easy answer, you miss out on the learning experience.
Which leaves you clueless when an original problem comes along.
¿what's a diagonal row?
Hello Dbreaker,

Another way to look at what salem c start with.

I have found this to work best when looking at a 2D array:

R      C o l
o    0  1  2  3
w   -----------
0 |  0  1  2  3
1 |  4  5  6  7
2 |  8  9 10 11
3 | 12 13 14 15 

5 + 10 + 15 = 30



To have something to work with I used 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>

typedef unsigned int UINT;

constexpr unsigned int MAXROW{ 4 }, MAXCOL{ 4 };

int main()
{
    //int nums[MAXROW][MAXCOL]{};  // <--- An empty array initialized to zeros.
    int nums[MAXROW][MAXCOL]
    {
        { 0,  1,  2,  3},
        { 4,  5,  6,  7},
        { 8,  9, 10, 11},
        {12, 13, 14, 15}
    };
    int sum{};
    int val{200};

    for (int row = 0; row < MAXROW; row++)
    {
        for (int col = 0; col < MAXCOL; col++)
        {
            nums[row][col] = val;

            val += 10;
        }
    }

    //  For loop to sum diagonal.

    std::cout << "\n\n Press Enter to continue: ";
    std::cin.get();

    return 0;  // <--- Not required, but makes a good break point.
}

You could write line 27 as: nums[row][col] = val++; and comment or delete line 29.

For line 33 I used a single for loop to sum the diagonal. I will give you a chance to work on that.

For ideas you could search here for "Tic Tac Toe" programs to see how they dealt with the diagonals.

Line 13 is not needed, but an example of how to initialize an array that gives a better visual representation of the array. You will find it useful in the future. Here it is overwritten with the following for loop.

Andy
Topic archived. No new replies allowed.