Karl
Karl

Reputation: 9

We want to display values in an ascending order using while loop

I have the following code and when I enter a number, the terminal should display the values from 1 to the entered number, meaning in an ascending order. As the code is, it displays values in descending order. How can I change my code to make it to an ascending order?

// Example5.java

import java.util.Scanner;

public class Example5 {

    public static void main(String[] args) {
        int count;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number: ");
        count = in.nextInt();
        while (count > 0) {
            System.out.println(count);
            --count;
        }
    }

}

Upvotes: 0

Views: 421

Answers (1)

Codere
Codere

Reputation: 23

I think that's a better way to do it:

import java.util.Scanner;

public class Example5 {

   public static void main(String[] args) {

         int count=0;
            Scanner in = new Scanner(System.in);

            System.out.println("Enter a number: ");
           int number = in.nextInt();
            while (count <= number) {
                System.out.println(count);
                count++;
            }
    }

}

Having a variable for the number and a variable for the counter is easier to understand if you want it in ascending order, you should start from the smaller number (0) and then increase the counter to get to the greater number (input)

Upvotes: 2

Related Questions