I am learning C++ and having a problem with adding numbers in a [10][10] array. It reads the data from a file. I have the array set up and I have to add the numbers diagonally left and right. I have to add prj6[0][0] then prj6[1][1] then[2][2] and so forth. I don't know how to increase through the array.

for(int row = 0; row < NUM_ROW; row++)
	{
	   for(int clm = 0; clm < NUM_CLM; clm++)
		out << setw(5) << prj6 [row][clm];
		cout << endl;
	}

This code gets me to loop through the array.

Recommended Answers

All 4 Replies

The easiest way to read diagonally through your array would be to take the procedural approach and just write out each element of the 2d array that makes up the diagonal you want to add.

But it seems like you are looking for a better method that would involve less code, using a loop. When it comes to something like this, look for a pattern. Once you've discovered the pattern, you have to make it part of your loop condition.

For example, in your [10][10] array, you start out at [0][0], then [1][1], then [2][2], then [3][3] and so on.. so we have identified a pattern; from [0][0], each subsequent element of the diagonal is [row+1][col+1]. So we can make this part of our loop condition:

int subtotal = 0;

//one diagonal
for(int i=0, i<10, i++)
{
     //increment diagonally through the array
     subtotal += array[i][i];
}

To get the other diagonal, you would start at [0][10], then go to [1][9], then [2][8], then [3][7].. etc. Initialize the element indicies to 0 and 10 and handle them appropriately in your loop condition in such a manner that will result in a diagonal summation.

Thanks, that worked great for the left diagonal. I don't understand how to initialize the the element for the right diagonal. I tried to start out at i=10 and count backwards. That didn't work. How do you have the row set for 0 and the column set for 10 while incrementing the row by 1 and decrementing the column by 1?

for(int r=0, c=9; r<10; r++, c--)
{
     subtotal += array[r][c];
}

you should have got this on your own, or at least got really close.. or at least made an attempt.

Thank you for the help. It worked like a charm. Like I said. I am new to C++ and am trying to learn. I did try a lot of differant things but nothing would work. I did try to count backwards while counting but I did not realize how you can split the two subscripts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.