settingsAccountsettings
Menusettings

Q: Reverse loop from bigger to smaller in Java

+10 votes

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]);
        }
    }
}
asked in Java category by user eiorgert
edited by user golearnweb

3 Answers

+4 votes

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]);
        }
    }
}

 

answered by user hues
edited by user hues
+3 votes

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]);
        }
    }
}

 

answered by user john7
+2 votes

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);
    }
}

 

answered by user john7
...