Home / Programs / Sort array elements in c programming language
Programming Example

Sort array elements in c programming language

👁 1,079 Views
💻 Practical Program
📘 Step by Step Learning
Sort array elements

Program Code

#include"stdio.h"
#include"stdlib.h"

int main()
{

int a[30],n,i,j,temp, sorted=0;

printf("\n How many numbers");
scanf("%d",&n);
 if(n>30)
  {
    printf("\n Too many Numbers");
    exit(0);
   }

printf("\n Enter the array elements \n");
 for(i=0 ; i < n; i++)
   scanf("%d", &a[i]);
 for(i = 0; i < n-1 && sorted==0; i++)
  {
    sorted=1;
    for(j = 0; j < (n - i) -1; j++)
      if(a[j] > a[j+1])
        {
          temp = a[j];
          a[j] = a[j+1];
          a[j+1] = temp;
          sorted=0;
         }
    }

printf("\n The numbers in sorted order \n");
 for(i=0 ; i < n; ++i)
  printf("\n %d", a[i]);

return 0;

}

Output

 How many numbers5

 Enter the array elements
6
5
3
8
4

 The numbers in sorted order

 3
 4
 5
 6
 8 

Explanation

None

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.