[Solved] Reverse loop from bigger to smaller in Java

  

5
Topic starter

How can I do a reverse loop - meaning going from bigger to smaller (for example integer) in Java?

For example I have 12 months and instead of getting this in the console:

  • January
  • February
  • March
  • April
  • May
  • June
  • July
  • August
  • September
  • October
  • November
  • December

I want to get this:

  • December
  • November
  • October
  • September
  • August
  • July
  • June
  • May
  • April
  • March
  • February
  • January

....in reverse order!

Here is my code:

public class MonthsNumber {
 
    public static void main(String[] args) {
 
        String[] monthsNumber = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
 
        for (int i = 0; i < months.length; i++) {
            System.out.println(months[i]);
        }
    }
}
3 Answers
4

Here's the answer with for loop:

public class MonthsOrder {
    public static void main(String[] args) {
 
        String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
 
        for (int i = months.length - 1; i >= 0; i--) {//REVERSE LOOP - going from bigger number to smaller
            System.out.println(months[i]);
        }
    }
}
3

Here's the reverse order with while loop:

public class Upr {
    public static void main(String[] args) {
 
        String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
 
        int counter = months.length;
        while (counter > 0) {
            counter--;
            System.out.println(months[counter]);
        }
    }
}
2

The reverse order with do-while loop:

public class Upr2 {
    public static void main(String[] args) {
 
        String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
 
        int counter = months.length;
        do {
            counter--;
            System.out.println(months[counter]);
        }
        while (counter > 0);
    }
}
Share: