Here we are going to write a c program to sort an array in ascending and descending order. This program can be done in many ways like we can use various sorting techniques to sort our array. Some of the sorting techniques are bubble sort, merge sort, normal linear sorting etc. Write a program to sort the numbers in ascending and descending order using array. C program to sort an array in ascending and descending order using Function. Ascending order program in C using for loop etc. We will be solving this problem i.e., C program to sort an array in ascending and descending order using Function and Ascending order program in C using for loop.
Suppose we have an array, a[] = {3,1,4,2,5,7,6,8,10,9}
So the array elements in ascending order, a[] = {1,2,3,4,5,6,7,8,9,10}
And in descending order, a[] = {10,9,8,7,6,5,4,3,2,1}
Now lets code it. But before going down I will suggest you to first try it on your own and then see the solution.
C program to sort an array in ascending and descending order using Function
#include <stdio.h>
void sort_ascending(int a[], int n){
int temp;
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n;j++){
if(a[i] > a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf ("Array in Ascending order: \n");
for(int i=0; i<n; i++){
printf("%d ", a[i]);
}
}
void sort_descending(int a[], int n){
int temp;
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n;j++){
if(a[i] < a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf ("\nArray in Descending order: \n");
for(int i=0; i<n; i++){
printf("%d ", a[i]);
}
}
int main(){
int n;
printf("Enter size of array: ");
scanf("%d",&n);
int a[n];
printf("Enter array elements: ");
for(int i=0; i<n; i++){
scanf("%d",&a[i]);
}
sort_ascending(a,n);
sort_descending(a,n);
return 0;
}Output
Enter size of array: 5
Enter array elements: 5 3 6 2 7
Array in Ascending order:
2 3 5 6 7
Array in Descending order:
7 6 5 3 2
Ascending order program in C using for loop
#include <stdio.h>
int main(){
int n;
printf("Enter size of array: ");
scanf("%d",&n);
int a[n];
printf("Enter array elements: ");
for(int i=0; i<n; i++){
scanf("%d",&a[i]);
}
int temp;
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n;j++){
if(a[i] > a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf ("Array in Ascending order: \n");
for(int i=0; i<n; i++){
printf("%d ", a[i]);
}
return 0;
}Output
Enter size of array: 5
Enter array elements: 5 3 6 2 7
Array in Ascending order:
2 3 5 6 7 More like this -
• C Program to sort an array in ascending and descending order using Bubble sort
Post a Comment
If you have any doubts, please let me know