+ 2

Anyone having an idea on array flipping, i cant understand the loop part of it

Array flipping

5th Aug 2017, 10:45 PM
Kevinoh Kelvin
Kevinoh Kelvin - avatar
3 Answers
+ 2
It's reversing the array. In order to reverse the array, you swap the left side withthe right side, but the middle stays. Therefore, the loop only need to itterate from 0-length/2. int temp = a[i]; This will be the first element, so 10. a[i] = a[a.length-1-i]; This will make a[0] equal to the last element (length - 1), so 40. a[a.length-1-i] = temp; This will make the last element (40) equal to temp, which was the first element (10). So, 10 and 40 have now swapped. Since they did '-i', as the loop continues, it will continue swapping the next elements in the array. So, 20 and 30 will also swap. @Adi Pramata-Universitas Brawijaya That is not a function in Java. That is PHP.
6th Aug 2017, 12:41 AM
Rrestoring faith
Rrestoring faith - avatar
0
import java.util.Arrays; public class Arrays{ public static void main(String[]arts){ int[]a={10,20,30,40}; system. out.println(Arrays. toString (a)); for(int i=0;i<a.length/2; i++){ //I'm not getting this part int temp=a[i]; //please help a[i]=a[a.length-1-i]; a[a.length-1-i]=temp; } system. out. println (Arrays.toString (a)); } }
6th Aug 2017, 12:24 AM
Kevinoh Kelvin
Kevinoh Kelvin - avatar
0
thanks so much
6th Aug 2017, 12:46 AM
Kevinoh Kelvin
Kevinoh Kelvin - avatar