Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
So for each row but the last I want to have the last element be the sum of earlier values in the row and for each column i want to have the bottom most element be the sum of those values above it. this is my array


const int ROWS = 5;
const int COLS = 6;
int ourNumbers[ROWS][COLS] = { { 17, 44, 7, 8, 2, 0},
{ 2, 4, 88, 2, 11, 0},
{ 11, 6, 9, 55, 3, 0},
{ 1, 18, 25, 31, 22, 0},
{ 0, 0, 0, 0, 0, 0}
};
Posted
Comments
George Jonsson 29-Nov-15 1:47am    
So what is the problem?
Richard MacCutchan 29-Nov-15 3:38am    
This is a simple matter of for loops.

1 solution

First of all, I don't see why would you need to add any elements to your array. This is asked in the title of the question and not confirmed by its body. It's unclear why you cannot just create all elements of fixed sizes.

But if the real question is the one of the title, let's assume you really need to add some elements.

It's a bad idea to add something to an array which is already initialized, no matter "two-dimensional" or not, jagged array or not. This dimension is not "real" and is majorly irrelevant to the problem of adding. Very good explanation of so called "multidimensional arrays" can be found here: http://www.cplusplus.com/doc/tutorial/arrays[^].

If you understand this explanation thoroughly, you may also understand that you cannot simply change the size of the memory needed to place additional array elements. You would need to reallocate the array, which, generally, essentially means creation of a brand-new array object with elements copies from the original array; so reallocation can be quite expansive operation. This because the array allocation is based on continuous memory location. With jagged array, the picture is a bit more complex, but each inner array still takes its one room of continuous memory. So, in all cases, you will need additional piece of memory for added elements, which is, generally, may be not available.

You need to use different data structures to implement add/insert/remove operations. As you are using C++, this is not a problem, due to C++ standard library. See, in particular, std::vector, std::list:
http://www.cplusplus.com/reference/vector/vector[^],
http://www.cplusplus.com/reference/list/list[^].

Also, you can use a linked list:
http://www.cplusplus.com/articles/LACRko23[^],
http://cslibrary.stanford.edu/103[
href="http://cslibrary.stanford.edu/103" target="_blank" title="New Window">^
].

This CodeProject article can also be useful: http://www.codeproject.com/Articles/24684/How-to-create-Linked-list-using-C-C.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900