Write a program to sort array element in ascending order
Method 1:-
#include <stdio.h>
int main()
{
int a[7],i,j,t,n;
printf("Enter the Numbers:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("\nNumbers in Ascending Order:\n");
for(i=0;i<n;i++)
printf("\n%d ",a[i]);
return 0;
}
output:-
Enter the Numbers:
4
1
6
2
8
Numbers in Ascending Order:
1
2
6
8
Method :2
#include <stdio.h>
void main()
{
int arr1[100];
int n, i, j, tmp;
printf("\n\nsort elements of array in ascending order :\n ");
printf("Input the size of array : ");
scanf("%d", &n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(arr1[j] <arr1[i])
{
tmp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = tmp;
}
}
}
printf("\nElements of array in sorted ascending order:\n");
for(i=0; i<n; i++)
{
printf("%d ", arr1[i]);
}
printf("\n\n");
}
output:-
tag:-
Sort array and print it in ascending order - C
Post a Comment
If you have any doubts, Please let me know
Thanks!