Programming Example
Sort array elements in c programming language
Sort array elements
#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;
}
How many numbers5
Enter the array elements
6
5
3
8
4
The numbers in sorted order
3
4
5
6
8
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.