Win a copy of Design for the Mind this week in the Design forum!

# Array index

Heba Mahmoud
Ranch Hand
Posts: 62

Heba Mahmoud
Ranch Hand
Posts: 62
the source is

inquistion john meyers's SCJP 5 mock exam

but really i have a question regarding quoting the questions?

i prepared for the exam for along time and each time when i found any diffcult question for me , i copied it in some word file till i can ask about it
so i have a lot questions that i don't remember from where i had got it and what its source??

so that matter may make me don't quote some of the questions i send.

Neha Daga
Ranch Hand
Posts: 504
your code executes this way:

first iteration:
i = 1, x[1] = 0, array becomes: x = (1, 0 , 3, 4)
second iteration:
i = 0, x[0] = 0, array becomes: x = (0, 0, 3, 4)
third iteration:
i = 3, x[3] = 0, array becomes: x = (0, 0, 3, 0)
fourth iteration:
i = 0, x[0] = 0, array becomes: x = (0, 0, 3, 0)

final answer: x = (0, 0, 3, 0)

Abimaran Kugathasan
Ranch Hand
Posts: 2066
Neha Daga, I couldn't get that point. How it is happening? Since second enhanced for loop works correctly (traversed through according to index position), so why is that for first?

Neha Daga
Ranch Hand
Posts: 504
ok , I hope you know how for each loop works it iterates through elements in the loop.

when first iteration occurs it sets 'i' to the first value in array that is 1. Now the next statement sets the element at index represented by 'i' to 0 so the element at index 1 is set to 0. Now when the second iteration occurs 'i' is set to the second element that is the element at index 1 which is 0, so now the next statement will set the element at index 0 will be changed to 0. the third iteration sets 'i' to 3 value at the index 2 and hence the value at index 3 will be changed to 0. and in the last iteration the i will be set to 0 beacuase now index 3 has been set to 0 in the last iteration and hence the next statement will change the first value to 0.

Ranch Hand
Posts: 46
This indeed is a good question and the explanation ever better.

Abimaran Kugathasan
Ranch Hand
Posts: 2066
Yea.. Me too.

Henry Wong
author
Marshal
Posts: 21000
76
Abimaran Kugathasan wrote:

If you were able to follow the explanation for the first example, you should be able to figure out this example -- it is basically doing the same thing with different numbers.

Henry

Ankit Garg
Sheriff
Posts: 9519
22
@Abimaran What will happen when the first for loop will iterate for the third time?? At that time i will be 8, so the statement inside the loop will be: x[8] = 0; and that will result in an ArrayIndexOutOfBoundsException...

Abimaran Kugathasan
Ranch Hand
Posts: 2066
Oh! I confused.... Shit! That i refers the elements of that array, not the index. Soooo Sorry. What a stupid mistake! I start to forget all.......
Sorry heba mahmoud.
Sorry Neha Daga.