+ 1

What is the output, and explain how you got the answer.

int × [6]; for ( int i=0; i <6; i++) { x [i] = i+3; if(i>=4) x [i-1]= ×[i]+4 } //Display content of the array. for (i=0; i <6; i++) cout <<x [i] << " ";

25th May 2017, 2:32 AM
Sami
7 Réponses
+ 3
Step by step: x[0] = 0 + 3 = 3. i = 0 x[1] = 1 + 3 = 4. i = 1 x[2] = 5. i = 2 x[3] = 6. i = 3 x[4] = 7. i = 4 i is now >= 4! x[4-1] = x[3] = x[4] + 4 = 7 + 4 = 11 So x[3] is now 11. x[5] = 8. i = 5 i is >= 4! x[5-1] = x[4] = x[5] + 4 = 8 + 4 = 12 So x[4] is now 12. i = 6, 6 < 6. False. Therefore the loop is finished. ~~~~Errors~~~~ Compilation ERROR variable i not declared. Fix: (int i = 0.....etc Compilation ERROR, you used different letters for your 'x'. Compilation ERROR missing semi-colon. Fix: x [i-1] = x[i] + 4; ~~~~~~~~~~~~ Assuming no mistakes were made: Output: 3 4 5 11 12 8 The real output is error though 😛.
25th May 2017, 3:00 AM
Rrestoring faith
Rrestoring faith - avatar
+ 3
Its from the line: x[i] = i + 3. At the moment i = 5.
25th May 2017, 3:09 AM
Rrestoring faith
Rrestoring faith - avatar
+ 3
Careful, x is the array. I think you mean i. 😜 i went up to 5. I've just posted everything in order of execution. So after x[4] was the if statement/next operation. Then it went to x[5]. i doesn't go up to 6 though, that's when the loop stops. I've editted the original post by adding an extra space after x[5]. Hopefully it's easier to see now.
25th May 2017, 3:22 AM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Ahh, of course! Thank you!
25th May 2017, 3:10 AM
Sami
+ 1
Ohhhh, okay! Makes sense! Thanks a lot :D
25th May 2017, 3:23 AM
Sami
0
How did you get x [5]=8?? Unsure where that came from.
25th May 2017, 3:07 AM
Sami
0
Also, why does x only go up to 4, and not 5? Thought the array size was six.
25th May 2017, 3:11 AM
Sami