2 Ways to Reverse for loop Java
In this article, you are going to learn 2 different ways to reverse for loop in Java.
Generally, we use for loop to iterate over a collection of elements in the same order as defined. But sometimes we need to iterate over a collection of elements in reverse order.
Let's see how we can iterate in reverse order using for loop in Java.
Method 1: Reverse for loop Java
To iterate in reverse order using for loop we have to modify the increment/decrement operator, initialization, and condition part of the for loop.
- First, set the initialization part of the for loop to the last index of the collection.
- Then, look for the first index in condition.
- Finally, the increment/decrement part of the loop should be decremented.
Let's see an example to understand this better.
public class ReverseLoop {
public static void main(String[] args) {
// reverse for loop
for (int i = 10; i > 0; i--) {
System.out.print(i + " ");
}
System.out.println();
}
}
10 9 8 7 6 5 4 3 2 1
Method 2: Reverse for loop Java
Another way to reverse for loop in Java is based on the idea of getting elements from the end of the collection.
In this approach, we move in the forward direction, from the start to the end of the collection, but we get the element from the end of the collection using size() - i - 1 index.
Here is an example showing this in action.
public class ReverseLoop {
public static void main(String[] args) {
// reverse for loop
int size = 10;
for (int i = 0; i < size; i++) {
System.out.print((size - i - 1) + " ");
}
System.out.println();
}
}
9 8 7 6 5 4 3 2 1 0
Examples
Reverse loop on array
Let's see an example to reverse for loop on an array.
public class ReverseLoop {
public static void main(String[] args) {
// reverse for loop on array
int[] arr = { 15, 31, 45, 60, 23 };
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
15 31 45 60 23
Reverse loop on String
Here is an example to reverse for loop on a String.
public class ReverseLoop {
public static void main(String[] args) {
// reverse for loop on String
String str = "Hello World";
for (int i = str.length() - 1; i >= 0; i--) {
System.out.print(str.charAt(i));
}
System.out.println();
}
}
dlroW olleH
You now know how to reverse for loop in Java. You can use this technique to iterate over a collection in reverse order.
Hope you liked this article.
Happy Learning!🙂