File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array doubt

 
cathymala louis
Ranch Hand
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a mock exam question. The answer given is: 0 0 3 0
Could some one please explain how we will get 3 in arr[2].

 
Lata Bagga
Ranch Hand
Posts: 35
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Cathymala,

Earlier I had the same doubt in this question but I got this explanation from Vishwanath which cleared my doubt and hope will clear yours also:

for the first value in the array:
arr[1]<-- 0
so arr becomes,
{1,0,3,4}

for the next value in the array: [Remb: The array is changed now]

arr[0]<-- 0;
and arr is now,
{0,0,3,4}

for the next value in the array:

arr[3]<--0
gives
{0,0,3,0}

and for the last value in the array:
arr[0]<--0
so, arr remains {0,0,3,0}


Regards,
Lata
 
Akshay Dashrath
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I could not understand this explanation, why do you start with arr[1] when its actually goes arr[0], arr[1], arr[2] etc.. and why does it remain 3 only in the 3rd position.

Thank you in advance,

Akshay
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The zeroth element in the array has a value of 1 which is what gets assigned to i in the first iteration.

arr[i] equals array[1].
 
Akshay Dashrath
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ben,

Is'nt it like this now, does'nt an array always start from the zeroeth element?

a[0] = 1
a[1] = 2
a[2] = 3
a[3] = 4

Thanks,

Akshay
 
ramchandra sugasi
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

the critical thing to notice here is that

'i' is used to hold the value in the array
and also to index through the array.

Hence,

when we go step by step into the for loop, its as follows:
arr = {1,2,3,4}

loop(1)
i = 1 , arr[1] = 0 // i takes first value of the array arr
arr = {1,0,3,4}

loop(2)
i = 0, arr[0] = 0 // i takes second value of the array arr
arr = {0,0,3,4}

loop(3)
i = 3 , arr[3] = 0 // i takes third value of the array arr
arr = {0,0,3,0}

loop(4)
i = 0 , arr[0] = 0 // i takes fourth value of the array arr
arr = {0,0,3,0}

confusing...
but observe things step by step and it will be clear.
 
cathymala louis
Ranch Hand
Posts: 77
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic