reverse an array in java using for loop code example
Example 1: Reverse an array in java using for loop
public class ReverseArrayUsingForLoop
{
public static void main(String[] args)
{
int[] arrNumbers = new int[]{2, 4, 6, 8, 10};
System.out.println("Given array: ");
for(int a = 0; a < arrNumbers.length; a++)
{
System.out.print(arrNumbers[a] + " ");
}
System.out.println("Reverse array: ");
for(int a = arrNumbers.length - 1; a >= 0; a--)
{
System.out.print(arrNumbers[a] + " ");
}
}
}
Example 2: reverse array in java
int length = array.length;
for(int i=0;i<length/2;i++) {
int swap = array[i];
array[i] = array[length-i-1];
array[length-i-1] = swap;
}
or
Collections.reverse(Arrays.asList(array));
Example 3: how to print array backwards
var array = ['a','b','c','d','e','f','g']
var j = array.length
for(var i = 0; i < array.length ; i++){
console.log(array[j])
j=j-1 }
Example 4: reverse an array in java using while loop
import java.util.Scanner;
public class Example
{
public static void main(String args[])
{
int counter, i=0, j=0, temp;
int number[] = new int[100];
Scanner scanner = new Scanner(System.in);
System.out.print("How many elements you want to enter: ");
counter = scanner.nextInt();
for(i=0; i<counter; i++)
{
System.out.print("Enter Array Element"+(i+1)+": ");
number[i] = scanner.nextInt();
}
j = i - 1;
i = 0;
scanner.close();
while(i<j)
{
temp = number[i];
number[i] = number[j];
number[j] = temp;
i++;
j--;
}
System.out.print("Reversed array: ");
for(i=0; i<counter; i++)
{
System.out.print(number[i]+ " ");
}
}
}
Example 5: java reverse loop
for (int i = aList.size() - 1; i >= 0; i--) {
String s = aList.get(i);
}
Example 6: how to iterate through an array backwards java
for (int counter = myArray.length - 1; counter >= 0; counter--) {