C Program to sort an array in ascending order


In this program, You will learn how to sort an array in ascending order in c.


List is: 1 4 5 2 3 6

After sort: 1 2 3 4 5 6


Example: How to sort an array in ascending order in c

Run it Now
#include<stdio.h>

int main() {

   int a[10];
   int n, temp;

   printf("Enter Size of an Array :");
   scanf("%d", &n);

   printf("\nEnter  Array  Elements :");
   for (int i = 0; i < n; i++) {
       scanf("%d", &a[i]);
   }

   for (int i = 0; i < n; i++) {
       for (int j = 1 + i; j < n; j++) {
           if (a[i] > a[j]) {
               temp = a[i];
               a[i] = a[j];
               a[j] = temp;
           }
       }
   }
   printf("\nArray After Sorting :");
   for (int i = 0; i < n; i++) {
       printf("%d ", a[i]);
   }

   return 0;
}

Output:

Enter Size of an Array :5
Enter  Array  Elements :2 4 3 1 7
Array After Sorting :1 2 3 4 7