+ 1

Hey friends !please explain this code below

iostream> using namespace std; int main(){ int a[3]={9,3,4}; for(int i =2;i>0;i--){ a[0]-=a[i]; } cout<<a[0]; return 0; } //output 2 ?

22nd Aug 2018, 12:10 PM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
4 Respostas
+ 4
The for loop runs 2 iterations, in the first iteration, the first element (9) is decremented by third element (4) which changed first element's value to 5. In second iteration, the first element (5) is decremented by second element (3) which then changed first element's value to 2. Hth, cmiiw
22nd Aug 2018, 12:17 PM
Ipang
+ 3
Just to add what Ipang said, remember that arrays start at 0, so the first element (item) in your array is a[0]. So, the line a[0] -= a[i]; Takes the value of a[0] which is 9 and reduces it by the value of a[i]. The value of 'i' starts at 2 in the loop, so you essentially have 1st time in loop a[0] = 9 - 4; Then 2nd time in loop a[0] = 5 - 3;
22nd Aug 2018, 12:27 PM
Duncan
Duncan - avatar
+ 3
Thanks Ipang and Duncan
22nd Aug 2018, 1:08 PM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
0
You're welcome Albert, glad if it helps : )
22nd Aug 2018, 1:12 PM
Ipang