In this program we will input some integers from the user and display them in descending order on the screen. But we have a condition that we have to use less variables and loops in the program and only one array.
Write a program that inputs some integers from the user and displays them in descending order. The program must ask the user that how many integers he/she wants to enter.
- The program should be user friendly.
- You are allowed to use only one array in the program.
- If you use an array in the program, it must be one dimensional and the length of the array can not be greater than the total number of integers given by the user.
- You should try to use less variables and less loops in the program.
Without discussing the import of Scanner class and creating its object in the main method, we come to the point.
- On line 10, the program prompts for the number of the integers the user wants to input which is taken as input at line 11 as the length of array. Please note that we were asked to use less variables, so instead of taking the input into an integer and then declaring an array of that size, we have done this directly.
- From line 13 to 17, the loop takes all the integers from the user.
- From line 19 to 31, a nested loop is executed. For an element of the array it will check all the elements with higher index and store the greatest value in the element. It swaps the values of the elements of the array in such a manner that the greater number is shifted to earlier index in the array. The elements are displayed simultaneously at line 30.
All the things are same in the program as above except that we are using java built in static method Arrays.sort(ArrayName); for arranging the elements of the array. To use this method, we will first import java.util.Arrays; . This method will arange the elements inside the array in ascending order. As we have to display the elements in descending order, we will display the array in reverse order i.e from higher index to lower index using a loop.
Do you have another solution in which we can use less variables and arrays? Tell me in the comments below.