Computer Science, asked by chandrasekharhazra00, 3 months ago

a java program to break an integer and store in an array and arrange the digits in desending order​

Answers

Answered by anindyaadhikari13
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.

  1. import java.util.*;
  2. public class JavaBrainly {
  3. public static void main(String[] args) {
  4. Scanner sc=new Scanner(System.in);
  5. // Taking Input.
  6. System.out.print("Enter a number: ");
  7. int n=sc.nextInt();
  8. int a[]=new int[Integer.toString(n).length()];
  9. int len=a.length;
  10. // Storing the digits in arr.
  11. System.out.println("Storing the digits in array.....");
  12. for(int i=len-1;i>=0;i--)
  13. {
  14. a[i]=n%10;
  15. n/=10;
  16. }
  17. // Displaying the array.
  18. System.out.println("Digits stored successfully.");
  19. System.out.print("Here is it.\n"+Arrays.toString(a));
  20. // Sorting the array.
  21. System.out.println("\n\nSorting the array....");
  22. for(int i=0;i<len;i++)
  23. {
  24. for(int j=i+1;j<len;j++)
  25. {
  26. if(a[i]<a[j])
  27. {
  28. int temp=a[i];
  29. a[i]=a[j];
  30. a[j]=temp;
  31. }
  32. }
  33. }
  34. System.out.println("Array Sorted Successfully.");
  35. System.out.print("Here is the array.\n");
  36. System.out.print(Arrays.toString(a));
  37. sc.close();
  38. }
  39. }

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