0
Why does this code give output 0?
int i; int a[] = {1,2,3,4}; for (i = 0; i< 3; i++) { a[3] = a[3] - a[i];} cout << a[3] - a[i]; First round of for loop: i = 0, a[3] = 4, Now a[3] = 4 - 1 = 3 Second round of the loop: i = 1, a[3] = 3, Now a[3] = 3 - 2 = 1 Third round: i = 2, a[3] = 1 Now a[3] = 1 - 3 = -2. The last cout should give - 2 - 3 = -5 But the output is 0. Where did I get it wrong?
2 Respostas
+ 2
For that, you need to print the output inside loop.
You can see where the curly braces are closed.
In outside loop, it just uses the last value of i which is 3.
So, a[3]- a[i] is same as a[3]-a[3] hence, output is 0.
+ 1
Thanks!