Hey, I am doing an array assignment and i understand how to use arrays, but my professor wants us to add 2 2-d arrays together. Here's what he gave us as our assignment:
"Write a C++ program that adds equivalent elements of the two-dimensional arrays named first and second. Both arrays should have three rows and four columns. For example, element [1][2] of the resulting array should be the sum of first[1][2] and second[1][2]. The program must use two nested for loops. Use the outer for loop to keep track of the row number and the inner for loop to keep track of the column number. Display the sum as a 3 by 4 array. The first and second arrays should be initialized as follows:
first
16 18 23 34
54 91 11 48
18 27 9 81
second
24 52 77 31
16 19 59 67
73 60 7 12
"
I am struggling to figure out how to add each element on the left with the corresponding element on the right. Here's what my code looks like and ik its wrong but i guess i just need help with the 2 nested loops. not looking for you to give the exact answers or codes, just merely point me in the right direction.
There are a number of places in the code where the constant values ROWS and COLUMN are mistakenly used.
For example here: cout << "This first array: " << first[ROWS][COLUMN] << "is being added to this array " << second[ROWS][COLUMN] << endl;
Let's simplify the problem and look at an example using a one-dimensional array.
I've modeled the following on the above code, but cut it back to the bare minimum:
There are two problems, the main one is that the array has four elements, they are:
1 2 3 4
first[0]
first[1]
first[2]
first[3]
But what is first[COLUMN]? Well, it is the fifth element, one position past the end of the array. This memory does not belong to the program and it should not be used.
The second problem is that to print the array we need to access each element in turn using a loop.
note: above I used setw() to give a neater output, it can be omitted.
Now this should give you a start. If you can handle a 1-D array, a 2-D array can be handled similarly using nested for loops. And if you know how to access an element in order to print it, then you can also use it for calculations or changing the value.