wood burning stoves*
The moose likes Beginning Java and the fly likes Example question - not understanding answer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Example question - not understanding answer" Watch "Example question - not understanding answer" New topic
Author

Example question - not understanding answer

Natasha Reaney
Greenhorn

Joined: Oct 10, 2012
Posts: 15
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

Joined: Sep 08, 2007
Posts: 3068
    
  33

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.


Mohamed Sanaulla | My Blog
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
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

Joined: Oct 13, 2005
Posts: 38756
    
  23
Please always tell us where such questions come from.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Example question - not understanding answer