a java program to break an integer and store in an array and arrange the digits in desending order
Answers
Answered by
4
Required Answer:-
Question:
- Write a Java program to break an integer and store it in an Array and arrange the digits in descending order.
Solution:
Here is the code.
- import java.util.*;
- public class JavaBrainly {
- public static void main(String[] args) {
- Scanner sc=new Scanner(System.in);
- // Taking Input.
- System.out.print("Enter a number: ");
- int n=sc.nextInt();
- int a[]=new int[Integer.toString(n).length()];
- int len=a.length;
- // Storing the digits in arr.
- System.out.println("Storing the digits in array.....");
- for(int i=len-1;i>=0;i--)
- {
- a[i]=n%10;
- n/=10;
- }
- // Displaying the array.
- System.out.println("Digits stored successfully.");
- System.out.print("Here is it.\n"+Arrays.toString(a));
- // Sorting the array.
- System.out.println("\n\nSorting the array....");
- for(int i=0;i<len;i++)
- {
- for(int j=i+1;j<len;j++)
- {
- if(a[i]<a[j])
- {
- int temp=a[i];
- a[i]=a[j];
- a[j]=temp;
- }
- }
- }
- System.out.println("Array Sorted Successfully.");
- System.out.print("Here is the array.\n");
- System.out.print(Arrays.toString(a));
- sc.close();
- }
- }
Explanation:
- At first, we will take the number as input. Then, we will create an array whose length is equal to the length of the number(or the number of digits) Now, we will enter the digits in the array and display the original array. Using selection sort algorithm, we will sort the array in descending order and display it.
Output is attached for verification.
Attachments:
Similar questions