C Program to Sort Elements of an Array in Ascending and Descending Order

Sorting an array in ascending and descending order is a common task in programming. Below is a simple C program that sorts elements of an array in both ascending and descending order using the bubble sort algorithm.

Program :

#include <stdio.h>
#include<conio.h>
int main()
{
int a[100],n,i,j;
printf(“Array size: “);
scanf(“%d”,&n);
printf(“Elements: “);

for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
for ( i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
{
if (a[j] > a[i])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
printf(“\n\nAscending : “);
for ( i = 0; i < n; i++)
{
printf(” %d “, a[i]);
}
for ( i = 0; i < n; i++)
{
for ( j = 0; j < n; j++)
{
if (a[j] < a[i])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
printf(“\n\nDescending : “);
for ( i = 0; i < n; i++)
{
printf(” %d “, a[i]);
}
return 0;
getch();
}

Output :

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Basket
Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare
Verified by MonsterInsights