+ 2

Could someone explain this code and its output?

Here's the code, written in C++: "#include <iostream> using namespace std; int main() { int a[]={1, 2, 3, 4}; for (int i=0; i<3; i++) { a[3]-=a[i]; } cout<<a[2] % a[3]<<"\t"; cout<<a[3]; return 0; }" This code outputs: "1 -2" Evidently the operation "a[3]-=a[i]" will get you "-2." How is this possible?

6th Jun 2017, 3:16 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
2 Respostas
+ 15
1st iteration: a[3] = a[3]-a[0] = 4-1 = 3 2nd iteration: a[3] = a[3]-a[1] = 3-2 = 1 3rd iteration: a[3] = a[3]-a[2] = 1-3 = -2
6th Jun 2017, 3:19 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 2
Wow I feel dull...I was only counting what I saw instead of changing the value of a[3] in my head. Thanks a bunch Shamima Yasmin.
6th Jun 2017, 3:43 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar