Home > Software engineering >  How do i make it so that the program counts in an ascending order instead of descending?
How do i make it so that the program counts in an ascending order instead of descending?

Time:05-19

I just want to know how to change the counting order from descending to ascending

  public class Example5{
    
       public static void main(String[] args){
          int count;
    
          count = Console.readInt("Enter a number: ");
          while (count > 0)
          {
             System.out.println(count);
             --count;
          }
       }
    
    }

image

CodePudding user response:

Your question is not clear as to the reason why you're needing this, but hopefully this helps. Here is an example of using a for loop for both descending and ascending examples.

Here is an alternative using a for loop for descending...

int count = Console.readInt("Enter a number: ");

for ( int i = count; i >= 0; i-- ) {
  System.out.println(i);
}

This would be for ascending...

int count = Console.readInt("Enter a number: ");

for ( int i = 0; i <= count; i   ) {
  System.out.println(i);
}

CodePudding user response:

public static void main(String[] args) {
  int count = Console.readInt("Enter a number: ");
  for (int j = 1; j <= count; j  ) {
    System.out.println(j);
  }
}

CodePudding user response:

Possibly just switch —count; to count;

  •  Tags:  
  • java
  • Related