Array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Array

int[] list = {1,2,3,5,4}; for (int i = 0, j = list.length - 1; i < list.length; i++, j--) { int temp = list[i]; list[i] = list[j]; list[j] = temp;} I'm trying reverse the elments in array list but this doesn't work..please how do I go about it?

8th Aug 2016, 5:44 AM
Ridwan
Ridwan - avatar
4 Answers
+ 1
I think you've overcomplicated it bud. You pretty much solved it in your for loop() without all those extra variables and list switching. Just put in System.out.println(list[j]); public class Program { public static void main(String[] args) { int[] list = {1,2,3,5,4}; for(int i = 0, j = list.length - 1; i < list.length; i++, j--) { System.out.println(list[j]); } } }
8th Aug 2016, 8:11 AM
James
James - avatar
0
your code is public class Program { public static void main(String[] args) { int[] list = {1,2,3,5,4}; for(int i = 0, j = list.length - 1; i < list.length; i++, j--) { int temp = list[i]; list[i] = list[j]; list[j] = temp; System.out.println(list[j]); } } } ________ output : 1 2 3 2 1
8th Aug 2016, 6:46 AM
Mohammad Reza Karimi
Mohammad Reza Karimi - avatar
0
The output should be 4 5 3 2 1
8th Aug 2016, 7:05 AM
Ridwan
Ridwan - avatar
0
try this way List<Integer> list = Arrays.asList(1, 2, 3, 5, 4); System.out.println(list); Collections.reverse(list); System.out.println(list); or this way public class Program { public static void reverse(int[] args) { int arr[] = {1,2,3,5,4}; for(int i = 0; arr.length / 2; i <++) { int temp = arr[i]; arr[i] = arr[arr.length - i - 1]; arr[arr.length - i - 1] = temp; System.out.println("myArray[" + i + "] = " + arr[i]); } } }
8th Aug 2016, 7:37 AM
Mohammad Reza Karimi
Mohammad Reza Karimi - avatar