Thursday, 27 March 2014

Write a program to read in an array of names and to sort them in alphabetical order.

#include<stdio.h>
#include<string.h>
main()
{
         int num,i,j;
         char name[100][100],temp[100];
         printf("Enter a number of names=");
         scanf("%d",&num);
         printf("#%d\n",num);
         for(i=0;i<num;i++)
         {
                  printf("\nEnter name %d=",i+1);
                  scanf("%s",&name[i]);
         }
         printf("\nThe names are\n");
         for(i=0;i<num;i++)
         {
                  printf("\nName %d=",i+1);
                  puts(name[i]);
         }
         for(i=0;i<num;i++)
         {
                  for(j=0;j<num-1-i;j++)
                  {
                           if(strcmp(name[j],name[j+1])>0)
                           {
                                    strcpy(temp,name[j]);
                                    strcpy(name[j],name[j+1]);        
                                    strcpy(name[j+1],temp);
                           }
                  }
         }
         printf("\nThe names after sorting are\n");
         for(i=0;i<num;i++)
         {
                  printf("\nName %d=",i+1);
                  puts(name[i]);
         }
}

No comments:

Post a Comment