I try to sum up the values in an array, and would like to store it in another array.
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int rev[2][12] = {{10,20,30,40,50,60,70,80,90,100,110,120},
{100,200,300,400,500,600,700,800,900,1000,1100,1200}};
int temp = 0;
for (int j = 0; j<2;j++){
for(int i = 0; i<12; i++){
temp += rev[j][i];
}
cout << "rev in year " << j+1 << ": " << temp << "\n";
temp = 0;
}
int revYear[2][1];
for (int j = 0; j<2;j++){
for(int i = 0; i<12; i++){
revYear[j][0] += rev[j][i];
}
}
cout << "rev in year 1: " << revYear[0][0] << "\n";
cout << "rev in year 2: " << revYear[1][0] << "\n";
return 0;
}
The first two for loops give me the desired output I'd like to store in revYear, which I tried in the second step. But it returns:
rev in year 18363800
rev in year 278010
Can anyone help me with this? Is it a compiler issue?
I´m using Mac and Xcode but I also ran the code with MS VS on Windows. Same problem, different output.
Please note: in the upper part, i just wanted to show that I found a way to get the desired output.
Let's see why
This snippet produces the correct result, but it's not quite idiomatic. You could rewrite it like the following:
Even better, you could use one of the algorithms of the Standard Library, std::accumulate:
Now it should be clear why the second nested loop in the question's posted code fails.
To fix it, we can properly initialize the array (it's still unclear to me why they want a 2D one, but that seems part of assignment).
Which IMHO is preferable to set the correct value at the beginning of the loop.