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
- Read n, the number of names (1 to 20).
- Read each name with
fgetsinto a row of a two-dimensional character array, and remove the newline at the end. - Repeat for pass = 1 to n − 1:
- For each pair of neighbouring names, compare them with
strcmp. Ifstrcmpreturns a value greater than 0, the first name comes later in order, so swap them usingstrcpyand a temporary array. - Print the sorted names.
Program
#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
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. SureshRecorded 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 intemp = names[j];. Arrays cannot be assigned in C. Copy them withstrcpy.Comparing names with
<or>, as innames[j] > names[j + 1]. That compares addresses, not the text. Usestrcmp.Calling
fgetsstraight afterscanf("%d"). The firstfgetsreads the leftover newline and gets an empty name. Clear the rest of the line first.Not removing the newline that
fgetskeeps. 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.
strcpycopies 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
strcmpreplaces>, andstrcpyreplaces the=used in swapping.
Learn the concepts
- Strings in C: char Arrays, the Null Terminator and Reading Text Safely
- String Functions in C: strlen, strcpy, strcat, strcmp, strchr, strstr and snprintf
- Multidimensional Arrays in C: 2D Arrays, Matrices and Passing Them to Functions
- Functions in C: Declaration, Definition, Prototypes and Calling
- Bubble Sort, Selection Sort and Insertion Sort in Python