--
Using the following link to learn what the Enhanced for Loop is(The For-Each Loop). The following code is an interesting example of using Enhanced for Loop. The enhanced for loop will go through the array
Using the following link to learn what the Enhanced for Loop is(The For-Each Loop). The following code is an interesting example of using Enhanced for Loop. The enhanced for loop will go through the array
arr
and set i
to each member of the "int" array. class Program { public static void main(String[] args) { int []arr = {1,2,3,4}; for ( int i : arr ) { arr[i] = 0; } for ( int i : arr ){ System.out.println(i); } } }Why it output :
0030
? Let's take a look:int []arr = {1,2,3,4}; for ( int i : arr ) { arr[i] = 0; }
- Step 1. On the first iteration,
i
will be 1 becausearr[0]=1
, and setarr[1]
to 0. - Step 2. On the second iteration,
i
will be 0 becausearr[1]=0
set by Step 1., and setarr[0]
to 0. - Step 3. On the third iteration,
i
will be 3 becausearr[2]=3
, and setarr[3]
to 0. - Step 4. On the last iteration, i will be 0 because
arr[3]=0
set by Step 3, and set arr[0] to 0.
class Program { ... static void useEnhancedFor(int x[][]) { for(int[] l:x) { for(int m:l) { System.out.print(m+" "); } } System.out.println(); } }
Comments
Post a Comment