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.

Shopping Basket
Verified by MonsterInsights