1// Reverse an array in java using for loop
2public class ReverseArrayUsingForLoop
3{
4 public static void main(String[] args)
5 {
6 int[] arrNumbers = new int[]{2, 4, 6, 8, 10};
7 System.out.println("Given array: ");
8 for(int a = 0; a < arrNumbers.length; a++)
9 {
10 System.out.print(arrNumbers[a] + " ");
11 }
12 System.out.println("Reverse array: ");
13 // looping array in reverse order
14 for(int a = arrNumbers.length - 1; a >= 0; a--)
15 {
16 System.out.print(arrNumbers[a] + " ");
17 }
18 }
19}
1int length = array.length;
2 for(int i=0;i<length/2;i++) {
3 int swap = array[i];
4 array[i] = array[length-i-1];
5 array[length-i-1] = swap;
6 }
7or
8Collections.reverse(Arrays.asList(array));
1var array = ['a','b','c','d','e','f','g']
2var j = array.length
3
4for(var i = 0; i < array.length ; i++){
5 console.log(array[j])
6 j=j-1 }
7
8 /*
9
10var j holds value of the array's number of values so every time in the loop it decrements by 1 making the
11function print a backwars array
12
13
14
15 */
1import java.util.Scanner;
2public class Example
3{
4 public static void main(String args[])
5 {
6 int counter, i=0, j=0, temp;
7 int number[] = new int[100];
8 Scanner scanner = new Scanner(System.in);
9 System.out.print("How many elements you want to enter: ");
10 counter = scanner.nextInt();
11
12 /* This loop stores all the elements that we enter in an
13 * the array number. First element is at number[0], second at
14 * number[1] and so on
15 */
16 for(i=0; i<counter; i++)
17 {
18 System.out.print("Enter Array Element"+(i+1)+": ");
19 number[i] = scanner.nextInt();
20 }
21
22 /* Here we are writing the logic to swap first element with
23 * last element, second last element with second element and
24 * so on. On the first iteration of while loop i is the index
25 * of first element and j is the index of last. On the second
26 * iteration i is the index of second and j is the index of
27 * second last.
28 */
29 j = i - 1;
30 i = 0;
31 scanner.close();
32 while(i<j)
33 {
34 temp = number[i];
35 number[i] = number[j];
36 number[j] = temp;
37 i++;
38 j--;
39 }
40
41 System.out.print("Reversed array: ");
42 for(i=0; i<counter; i++)
43 {
44 System.out.print(number[i]+ " ");
45 }
46 }
47}