This blog is under construction

Monday 24 June 2013

C program to sort names in ascending order

Write a C program to sort names in alphabetical order.


  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  int main() {
        char **data, temp[100];
        int i, j, n;

        /* get the number of entries from the user */
        printf("Enter the no of entries:");
        scanf("%d", &n);

        /* dynamically allocate memory to store names  */
        data = (char **)malloc(sizeof (char *) * n);
        for (i = 0; i < n; i++)
                data[i] = (char *)malloc(sizeof (char) * 100);

        /* get the names from the user */
        printf("Enter your inputs:\n");
        getchar();
        for (i = 0; i < n; i++) {
                fgets(data[i], 100, stdin);
        }

        /* sort the names in ascending order */
        for (i = 0; i < n - 1; i++) {
                for (j = i + 1; j < n; j++) {
                        if (strcmp(data[i], data[j]) > 0) {
                                strcpy(temp, data[i]);
                                strcpy(data[i], data[j]);
                                strcpy(data[j], temp);
                        }
                }
        }

        /* sorted names */
        printf("\nAfter sorting:\n");
        for (i = 0; i < n; i++)
                printf("%s", data[i]);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the no of entries:5
  Enter your inputs:
  Adam
  Sam 
  Nick
  Fred
  Edward

  After sorting:
  Adam
  Edward
  Fred
  Nick
  Sam



No comments:

Post a Comment