# Regarding arrays

Vijay Chandran
Ranch Hand
Posts: 186

Dear friends,

Case 1:
Using the new syntax of the for loop in //1 and //2,
for (int i : arr) and for (int j : arr)
i get the following output: 0 0 3 0

Case 2:
When i use the old for loop in //1 and new for loop in //2
for(int i = 0 ; i < arr.length ; i++) and then for (int j : arr)
i get the following output: 0 0 0 0

Case 3:
Using the new syntax of the for loop in //1 and old syntax in //2
for (int i : arr) and for(int j = 0 ; j < arr.length ; j++)
i get the following output: 0 1 2 3

Case 4:
Using the old syntax of the for loop in //1 and //2
for(int i = 0 ; i < arr.length ; i++) and
for(int j = 0 ; j < arr.length ; j++)

i get the following output: 0 1 2 3

Why there is change in the output between the old syntax of the for loop and the new syntax?
Please provide your help to solve this problem.

Thank you very much,
Vijay

dhwani mathur
Ranch Hand
Posts: 621
well!!
i hope the below shown explanation
can clear your doubt.....please read it till
the end...and read text which is made bold .its the explanation of enhanced for loop........
[ July 27, 2007: Message edited by: dhwani mathur ]

Bob Ruth
Ranch Hand
Posts: 320
Yes, refering to the form:

for (int i : arr) // 1

the int i that you get her is NOT an INDEX....

it is the value from the array. This form of "for loop" starts by retrieving arr[0] and putting THAT INT into i, then falling into your loop code. When the bottom of that block is reached it arr[1] is retrieved and put into i, then on the next pass arr[2], and on the last pass arr[3]. But the important thing to grab is that there is no way to stuff anything back in the array at the current index ( I refer you to the earlier posted response). This style of "for" loop exists ONLY to facilitate stepping through an array and handing you a copy of each and every element in the array. Nothing more.

Vijay Chandran
Ranch Hand
Posts: 186
Thanks a lot Dwani & Bob...

I grasped the concept

Regards,
Vijay