write a program to sort 10 numbers in descending order.
Answers
Answer:
Ok so here is your answer
Explanation:
1. Create an array of fixed size (maximum capacity), lets say 10.
2. Take n, a variable which stores the number of elements of the array, less than maximum capacity of array.
3. Iterate via for loop to take array elements as input, and print them.
4. The array elements are in unsorted fashion, to sort them, make a nested loop.
5. In the nested loop, the each element will be compared to all the elements below it.
6. In case the element is smaller than the element present below it, then they are interchanged
7. After executing the nested loop, we will obtain an array in descending order arranged elements.
// Program in C language to sort 10 numbers in descending order.
#include <stdio.h>
int main()
{
// Initializing our array
int arr[] = {6, 5, 28, 4, 13, 9, 25, 11, 7, 1};
int temp = 0;
// Now calculating the length of the array arr
int n = sizeof(arr) / sizeof(arr[0]);
// Printing and displaying the elements of our original array
printf("Elements of the original array are: \n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
// Sort the array in descending order
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (arr[i] < arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\n");
// Displaying elements of array after sorting
printf("Elements of array sorted in descending order are: \n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
Step-by-step Explanation:
1. Create an array of size 10.
2. Declare a variable 'n' which stores the number of elements in the array.
3. Run a for loop to print the elements of our original array.
4. The elements of our array arr are currently in an unsorted manner, to sort them, we make a nested loop.
5. In the nested loop, each element is compared to all the elements to its right.
6. If the element is smaller than the element to its right, the elements are swapped.
7. After executing the nested loop, we will obtain an array with elements arranged in the descending order. We can now print this final array.
#SPJ2