- 2071 Chaitra · 4 marks
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)
Related questions
- Rewrite string characters alphabetically · Computer Programming, chapter 7
- Steps to develop a computer program · Computer Programming, chapter 2 · asked 6×
- Structure of a FORTRAN program · Computer Programming, chapter 11 · asked 5×
- Declaration vs definition; C program structure · Computer Programming, chapter 3
- Sort employee structures by salary · Computer Programming, chapter 8 · asked 2×
- Computer program and programming · Computer Programming, chapter 2
- Cache management; direct vs associative address structure · Computer Organization and Architecture, chapter 6
- Program for RK-4 first order IVP · Numerical Method, chapter 6
- Program for RK-4 second order IVP · Numerical Method, chapter 6
- Interconnection structure of computer · Computer Organization and Architecture, chapter 1 · asked 3×