This is a C Program to sort an array in descending order.
This program will implement a one-dimentional array of some fixed size, filled with some random numbers, then will sort all the filled elements of the array.
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.
Here is source code of the C program to sort the array in an descending order. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
/*
* C program to accept a set of numbers and arrange them
* in a descending order
*/
#include <stdio.h>
void main ()
{
int number[30];
int i, j, a, n;
printf("Enter the value of N\n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
/* sorting begins ... */
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in descending order are given below\n");
for (i = 0; i < n; ++i)
{
printf("%d\n", number[i]);
}
}
1. Declare an array of some fixed capacity, lets say 30.
2. From users, take a number N as input, which will indicate the number of elements in the array (N <= maximum capacity)
3. Iterating through for loops (from [0 to N) ), take integers as input from user and print them. These input are the elements of the array.
4. Now, create a nested for loop with i and j as iterators.
5. Start the sorting in descending order by extracting each element at position i of outer loop.
6. This element is being compared to every element from position i+1 to size-1 (means all elements present below this extracted element)
7. In case any the extracted element is smaller than the element below it, then these two interchange their position, else the loop continues.
8. After this nested loop gets executed, we get all the elements of the array sorted in descending order.
Enter the value of N 5 Enter the numbers 234 780 130 56 90 The numbers arranged in descending order are given below 780 234 130 90 56
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
- Check C Books
- Apply for C Internship
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Practice BCA MCQs