KnowledgeBoat Logo

Computer Applications

Write a program in Java to enter a number containing three digits or more. Arrange the digits of the entered number in ascending order and display the result.
Sample Input: Enter a number 4972
Sample Output: 2, 4, 7, 9

Java

Java Nested for Loops

83 Likes

Answer

import java.util.Scanner;

public class KboatDigitSort
{
    public void sortDigits() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number having 3 or more digits: ");
        int OrgNum = in.nextInt();
        
        for (int i = 0; i <= 9; i++) {
            int num = OrgNum;
            int c = 0;
            while (num != 0) {
                if (num % 10 == i)
                    c++;
                num /= 10;
            }
            for (int j = 1; j <= c; j++) {
                System.out.print(i + ", ");
            }
        }
        
        System.out.println();
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program in Java to enter a number containing three digits or more. Arrange the digits of the entered number in ascending order and display the result. Sample Input: Enter a number 4972 Sample Output: 2, 4, 7, 9

Answered By

35 Likes


Related Questions