Skip to main content

Sort names and addresses alphabetically

Short answer

Read names and addresses into struct computer array. Sort by name using strcmp and swapping whole structures. Print the alphabetically ordered list.

Write a C program that reads several different names and address using structure computer, rearrange the names into alphabetical order and write out alphabetical list.

Design. A structure computer (as named in the question) has name and address. Several entries (5 here) are read into an array of structures. The array is sorted on name with strcmp(); when the names are out of order the whole structures are swapped, so each address stays with its name. The sorted list is printed.

#include <stdio.h>
#include <string.h>
#define N 5

struct computer {
    char name[30];
    char address[40];
};

int main(void)
{
    struct computer c[N], t;

    for (int i = 0; i < N; i++) {
        printf("Name and address %d: ", i + 1);
        scanf("%29s %39s", c[i].name, c[i].address);
    }

    for (int i = 0; i < N - 1; i++)           /* sort by name */
        for (int j = i + 1; j < N; j++)
            if (strcmp(c[i].name, c[j].name) > 0) {
                t = c[i];
                c[i] = c[j];
                c[j] = t;
            }

    printf("\nAlphabetical list\n");
    for (int i = 0; i < N; i++)
        printf("%-10s %s\n", c[i].name, c[i].address);
    return 0;
}

Sample run

Input (entered one after another): Ram Kathmandu Bibek Pokhara Sita Lalitpur Anil Butwal Hari Bhaktapur

Alphabetical list
Anil       Butwal
Bibek      Pokhara
Hari       Bhaktapur
Ram        Kathmandu
Sita       Lalitpur

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 8 questions →