Programming Examples
C program using dynamic memory allocation to read numbers as input and display them in sorted order thereafter
Write a program using dynamic memory allocation to read numbers as input and display them in sorted order thereafter.
Solution
#include<stdio.h>
#include<malloc.h>
int main()
{
int *ptr,*ptr1,n,a,b,temp;
printf("Enter how many elements you want to store: ");
scanf("%d",&n);
ptr=(int *)malloc(sizeof(int)*n);
ptr1=ptr;
printf("Enter %d elements for Array : ",n);
for(a=0;a<n;a++)
{
scanf("%d",ptr+a);
}
printf("\nElements of Array Before Sort : \n");
for(a=0;a<n;a++)
{
printf("%d\t",*(ptr+a));
}
for(a=0;a<n;a++)
{
for(b=0;b<(n-1)-a;b++)
{
if(*(ptr+b)>*(ptr+b+1))
{
temp=*(ptr+b);
*(ptr+b)=*(ptr+b+1);
*(ptr+b+1)=temp;
}
}
}
printf("\nElements of Array After Sort : \n");
for(a=0;a<n;a++)
{
printf("%d\t",*(ptr+a));
}
return 0;
}
Output
Enter how many elements you want to store: 7
Enter 7 elements for Array : 4 7 2 9 6 1 8
Elements of Array Before Sort :
4 7 2 9 6 1 8
Elements of Array After Sort :
1 2 4 6 7 8 9