Thursday, 23 July 2020

Dynamic Memory allocation | Input | Print Ascending Order program | C Language

 Q : Write a program using dynamic memory allocation to read numbers as input and display them in sorted order thereafter.

Answer :


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
/*============================
     Girfa Student Help
     Dynamic array and ascending print
==============================*/
void main()
{

     int *a,r,n,j,tmp;
     clrscr();
     printf("How many number you want to enter>> ");
     scanf("%d",&r);
     a=(int *) malloc(r*sizeof(int));
     for(n=0;n<r;n++)
     {
           printf("Enter %d position number>>",n+1);
           scanf("%d",(a+n));
     }
     /* sorting using bubble sort */
     for(n=0;n<r;n++)
     {
           for(j=0;j<r-1-n;j++)
           {
                if(*(a+j)>*(a+j+1))
                {
                     tmp=*(a+j);
                     *(a+j)=*(a+j+1);
                     *(a+j+1)=tmp;
                }
           }
     }
     /* print */
     printf("\n\nSort order print\n");
     for(n=0;n<r;n++)
           printf("\t%d",*(a+n));
     getch();
}


No comments:

Post a Comment