Dremendo Tag Line

Input a number and check digits are in ascending order or not using while loop in Java

while Loop - Question 13

In this question, we will see how to input a number and check if the digits are in ascending order or not in Java programming using while loop. To know more about while loop click on the while loop lesson.

Q13) Write a program in Java to input a number and check if the digits are in ascending order or not using while loop.

Program

import java.util.Scanner;

public class Q13
{
    public static void main(String args[])
    {
        int n,d,td=0,ld=10,asc=0;
        Scanner sc=new Scanner(System.in);

        System.out.print("Enter any number ");
        n=sc.nextInt();

        while(n>0)
        {
            d=n%10;
            if(d<ld)
            {
                ld=d;
                asc=asc+1;	// counting the digits present in the number in ascending order
            }
            td=td+1;		// counting the total number of digits
            n=n/10;
        }

        if(td==asc)
        {
            System.out.println("All digits are in ascending order");
        }
        else
        {
            System.out.println("All digits are not in ascending order");
        }
    }
}

Output

Enter any number 1469
All digits are in ascending order
video-poster