This blog is under construction

Monday 22 July 2013

C program to sort names using pointers

Write a C program to sort names using pointers.


  #include <stdio.h>
  #include <string.h>
  #include <stdlib.h>


  /* compares given two strings */
  int strcompare(char *str1, char *str2) {
        int i, flag = 0;

        /* strcmp operation */
        for (i = 0; i <= strlen(str1); i++) {
                flag = str1[i] - str2[i];
                if (flag != 0) {
                        break;
                }
        }

        return flag;
  }

  int main() {
        char **names, temp[32];
        int i, j, n;

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

        getchar();

        /* dynamically allocate memory and get names from user */
        names = (char **)malloc(sizeof(char *) * n);
        for (i = 0; i < n; i++) {
                *(names + i) = (char *)malloc(sizeof(char) * 32);
                printf("Name[%d]: ", i);
                fgets(*(names + i), 32, stdin);
                *(*(names + i) + strlen(*(names + i)) - 1) = '\0';
        }


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

        /* display the results */
        printf("Names After Sorting:\n");
        for (i = 0; i < n; i++) {
                printf("%s\n", *(names + i));
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of names:5
  Name[0]: Sam
  Name[1]: Ram
  Name[2]: Tom
  Name[3]: Jerry
  Name[4]: Bheem

  Names After Sorting:
  Bheem
  Jerry
  Ram
  Sam
  Tom


No comments:

Post a Comment