Monday, December 13, 2010

Program to sort the numbers entered by user in ascending and descending order using function

#include<stdio.h>
void ascending (int[],int);
void descending (int[],int);
int main()
{
    int a[20],i,n;
    printf("How many numbers?");
    scanf("%d",&n);
    printf("Enter %d numbers:",n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    ascending(a,n);
    descending(a,n);
    return 0;
}
void ascending(int a[],int n)
{
    int i,j,temp;
    printf("\nNumbers sorted in ascending order:\n");
    for(i=0;i<n;i++)
     {
         for(j=i+1;j<n;j++)
         {
             if(a[i]>a[j])
             {
                 temp=a[i];
                 a[i]=a[j];
                 a[j]=temp;
             }
         }
     }
     for(i=0;i<n;i++)
     {
         printf("%d\t",a[i]);
     }

}
void descending(int a[],int n)
{
    int i, j,temp;
    printf("\nNumbers sorted in descending order:\n");
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(a[i]<a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
  for(i=0;i<n;i++)
  {
      printf("%d\t",a[i]);
  }
}

No comments:

Post a Comment