• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Example question - not understanding answer

 
Natasha Reaney
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

Could someone help me understand the output of the following code? I have just begun learning arrays so forgive me if this is a silly question...



The output is 1 1 1 1 1 1.

Why is it that the i does not move, or rather why does the output remain 1?

Cheers,
Natasha
 
Mohamed Sanaulla
Saloon Keeper
Pie
Posts: 3159
33
Google App Engine Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are trying to assign the array element with the value of the previous array element.

So you start with index 1 and assign the value of index 0 which is "1" and then you continue so on until you have exhausted the array and end up assigning all the elements with the value 1.
Please trace the program using pen and paper and see how it works. You can even use a debugger or use print statements in the code to understand the flow and values of each variables.
 
Rameshwar Soni
Ranch Hand
Posts: 247
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Natasha Reaney wrote:

Why is it that the i does not move, or rather why does the output remain 1?


Array index starts from 0. Therefore list[0] has the first element i.e. 1 (here in your example as you have written this)


Similarly list[1] has second element i.e. 2 and so on.

Now you have this statement


First Iteration: Here i =1

Therefore list[1] = list [1-1] ------------> list [1] = list [0]---------> Replace list[1] element with list[0]-----> therefore 1 is stored in list[1] instead of 2, since list[0] has 1.

Second Iteration Here i=2

Therefore list[2] = list [2-1]----------> list[2] = list [1]-------------> Replace list[2] element with list[1]-----> therefore again 1 is stored in list [2] since list[1] has 1 from iteration 1
.
.
.
.
and so on



 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please always tell us where such questions come from.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic