Skip to content
Laviyx Learn

Try

PPS Lab · Experiment 47

Sort an array of names

CSorting and searchingJNTUH R22 · CS108ES

Aim

To write a C program that reads a list of names and sorts them in alphabetical order, using strcmp to compare names and strcpy to swap them.

Algorithm

  1. Read n, the number of names (1 to 20).
  2. Read each name with fgets into a row of a two-dimensional character array, and remove the newline at the end.
  3. Repeat for pass = 1 to n − 1:
  4. For each pair of neighbouring names, compare them with strcmp. If strcmp returns a value greater than 0, the first name comes later in order, so swap them using strcpy and a temporary array.
  5. Print the sorted names.

Program

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

#define MAX_NAMES 20
#define LEN 50

/* Sorts the names in alphabetical order using bubble sort */
void sort_names(char names[][LEN], int n) {
    char temp[LEN];
    for (int pass = 1; pass < n; pass++) {
        for (int j = 0; j < n - pass; j++) {
            if (strcmp(names[j], names[j + 1]) > 0) {
                strcpy(temp, names[j]);
                strcpy(names[j], names[j + 1]);
                strcpy(names[j + 1], temp);
            }
        }
    }
}

int main(void) {
    char names[MAX_NAMES][LEN];
    int n, c;

    printf("Enter the number of names (1 to %d): ", MAX_NAMES);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX_NAMES) {
        printf("Invalid number of names\n");
        return 1;
    }
    /* Remove the rest of the line (the newline) left by scanf */
    while ((c = getchar()) != '\n' && c != EOF) {
    }

    for (int i = 0; i < n; i++) {
        printf("Enter name %d: ", i + 1);
        if (fgets(names[i], LEN, stdin) == NULL) {
            printf("Invalid input\n");
            return 1;
        }
        names[i][strcspn(names[i], "\n")] = '\0';
    }

    sort_names(names, n);

    printf("\nNames in alphabetical order:\n");
    for (int i = 0; i < n; i++) {
        printf("%d. %s\n", i + 1, names[i]);
    }
    return 0;
}

Output

Output
Enter the number of names (1 to 20): 5
Enter name 1: Suresh
Enter name 2: Anitha
Enter name 3: Ravi Kumar
Enter name 4: Bhavya
Enter name 5: Ravi Chandra

Names in alphabetical order:
1. Anitha
2. Bhavya
3. Ravi Chandra
4. Ravi Kumar
5. Suresh

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The names are read with fgets, not scanf("%s"), so that a full name with a space, such as "Ravi Kumar", is kept as one name. scanf("%s") would stop at the space and read "Kumar" as the next name. Because scanf("%d") leaves a newline after the number, the getchar loop removes it before the first fgets.

strcmp compares character by character using character codes. "Ravi Chandra" comes before "Ravi Kumar" because the first difference is C against K. In ASCII all capital letters come before all small letters, so "anil" would be placed after "Suresh". Enter names with the same capitalisation, or compare lowercase copies, to get dictionary order.

Common mistakes

  • Swapping names with =, as in temp = names[j];. Arrays cannot be assigned in C. Copy them with strcpy.

  • Comparing names with < or >, as in names[j] > names[j + 1]. That compares addresses, not the text. Use strcmp.

  • Calling fgets straight after scanf("%d"). The first fgets reads the leftover newline and gets an empty name. Clear the rest of the line first.

  • Not removing the newline that fgets keeps. The names then print with an extra blank line, and the newline takes part in the comparison.

Viva questions

Try to answer each one aloud before you open it.

  • What does strcmp return?

    0 if the two strings are equal, a negative value if the first string comes before the second, and a positive value if it comes after. The comparison uses the character codes of the first characters that differ.

  • Why can't names be swapped with the = operator?

    Each name is a character array, and C does not allow one array to be assigned to another. strcpy copies the characters one by one, including the '\0'.

  • Why is a two-dimensional array used to store the names?

    Each name is itself an array of characters. A 2D array names[20][50] holds 20 names, each up to 49 characters plus the '\0'.

  • Why does "Zara" come before "anil" when sorted with strcmp?

    In ASCII, capital letters (65 to 90) have smaller codes than small letters (97 to 122), so 'Z' (90) is less than 'a' (97).

  • Which sorting method is used here?

    Bubble sort. The only change from sorting numbers is that strcmp replaces >, and strcpy replaces the = used in swapping.

Learn the concepts

All Programming for Problem Solving Lab experiments →