C program to sort given names in alphabetical order:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#include <stdio.h> #include <string.h> int main() { int i, j, num; char name[20][10], t_name[15][10], temp[20]; printf("Please enter how many number of names to be sorted in alphabetical order\n"); scanf("%d", &num); printf("Please enter %d names one by one\n", num); for(i=0; i< num ; i++) { scanf("%s",name[i]); strcpy (t_name[i], name[i]); } for(i=0; i < num-1 ; i++) { for(j=i+1; j< num; j++) { if(strcmp(name[i],name[j]) > 0) { strcpy(temp,name[i]); strcpy(name[i],name[j]); strcpy(name[j],temp); } } } printf("Names before sorting in alphabetical order\n"); for(i=0; i< num ; i++) { printf("%s\n",t_name[i]); } printf("Names after sorting in alphabetical order\n"); for(i=0; i< num ; i++) { printf("%s\n",name[i]); } } |
Output:
Please enter how many number of names to be sorted in alphabetical order
Please enter 4 names one by one
thiyagu
raja
mani
Arul
Entered names before sorting in alphabetical order
thiyagu
raja
mani
Arul
Entered names after sorting in alphabetical order
Arul
mani
raja
thiyagu