Reputation: 29
We were told to find the value of a[1]
after executing the following program:
int [] a = {0,1,2,3,4} ;
for(p=0 ; p< a.length ; p++){
a[p] = a[ (p + 3) % a.length] ;
}
So my teacher work it out like this
a[0] = a[(0+3) % 4]; = 3
a[1] = a[(1+3) % 4]; = 0
So a[1] = a[0]
therefore a[1] = 3
But I think the a.length
should be 5 so a[1] = a[(1+3) % 5]; = 4
What is the correct answer?
Upvotes: 3
Views: 90
Reputation: 11659
Yes you are partially right.
Length will be 5.
But if you work your way up, you would see that
a[0] = a[(0+3) % 5] ===> a[3] = 3;
a[1] = a[(1+3) % 5] ===> a[4] = 4;
a[2] = a[(2+3) % 5] ===> a[0] = 3; // note that now a[2] will take updated value of a[0];
& so on
Upvotes: 4
Reputation: 1663
You are right:
a.length
is the number of elements in the array. There are 5 elements: 0
,1
,2
,3
,4
.
Therefore A[1] = a[(1+3) % 5]; = 4
Further expanding on .length
:
When you access a[a.length]
you are out of bounds. This is why you have p < a.length
in your for-contidion. The indices are 0-indexed
meaning the 1st element has index 0. But non-the-less; if there is only a[0]
present, there is 1
element.
Upvotes: 1