- 1

Which of the following runs this array with number 10?

int x [3]; for(int i=0; i <=3; i++) x [i]=10; for(int=1; i <=3; i++) x [i]=10; for (int i=0; i <3; i++) x[i]=10; The answer is the last one, but I don't understand how it is, or why.

26th May 2017, 4:32 AM
Sami
8 Antworten
+ 9
The question itself "runs this array with number 10" is vague. As far as I can see, only the parameters of array index is altered. We have a lack of info on array declaration, and seeing that the answer is the third one, I'm assuming: int x[3]; where legit array index ranges from 0 to 2, hence the answer. The first two answers would go out of bound.
26th May 2017, 4:44 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
I assume its of the form: int x[3]; Now the array is declared to be able to hold 3 integers in the limit - 32768 to 32767... So, as the index of every array starts from 0, the i variable to access the index must start from 0. Also, since the array can have 3 integers here, the possible index values may be 0,1 or 2.. So, we run the i loop till 2 as when i=3, The 4th element will be altered but that has an undefined existence... Thus c is correct as it makes i = 0, then 1 and then 2...
26th May 2017, 4:48 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
In case 1, i moves from 0 to 3, leading to 4 indexes. But our array have memory defined for only 3, and so accessing the element x[3] makes the loop go out of bounds... This is as x[3] simply has no reserve for memory, it doesn't exist...
26th May 2017, 4:50 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Where is the array? Can you please show?
26th May 2017, 4:43 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Hi Samira, look at the array. You declared an array with 3 members in it. Now look at the first for loop you provided. It's started from x=0 and loop through until x=3. So at the end you will get four member for the array for x= 0, x=1, x=2, x=3 which you don't want. Now come to the second for loop which os technically correct. Because you want an array of three members and this loop will give you that. And the third for loop will provide you the same array except this time, the array index will start from 0, x[0],x[1], x[2].Good luck
26th May 2017, 5:08 AM
Adnan
0
Edited, sorry guys!
26th May 2017, 4:46 AM
Sami
0
How does the first one go out of bounds?
26th May 2017, 4:48 AM
Sami
0
Got it! Thank you guys a lot! Very helpful :)
26th May 2017, 4:51 AM
Sami