+ 1
Can we use enhanced for loop of array from any other index than 0.
for(int t : arr) //this always take value from starting index can we take value, using it, from any other desired index.
2 odpowiedzi
+ 2
Sure. Java also has a different kind of for loop. This:
for(int t : arr) System.out.println(t);
Is equivalent to this:
for(int i = 0; i < arr.length; i++) System.out.println(arr[i]);
In the second example you are saying alright, make an int i equal to zero, do the loop, add 1 to i. Now do the whole thing again for as long as i < arr.length.
This is a lot uglier but also more flexible since you can adjust the starting index to wherever you need it:
for(int i = 4; ...)
+ 1
A foreach loop isn't the exact equivalent as a for loop as it's read-only. If you want to iterate through an array and change values you have to use a normal for loop.