Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Example question - not understanding answer

Natasha Reaney
Greenhorn
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
Posts: 3159
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.

Rameshwar Soni
Ranch Hand
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
Posts: 50738
83
Please always tell us where such questions come from.