Write a C program to arrange names in alphabetical order.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char **names, temp[32];
int n, i, j;
/* get the number of names from user */
printf("Enter the number of names:");
scanf("%d", &n);
getchar();
/* allocate memory to store input names */
names = (char **)malloc(sizeof(char *) * n);
for (i = 0; i < n; i++) {
names[i] = (char *)malloc(sizeof(char) * 32);
}
/* get the names from the user */
printf("Enter the input names:\n");
for (i = 0; i < n; i++) {
printf("Name[%d]: ", i);
fgets(names[i], 32, stdin);
names[i][strlen(names[i]) - 1] = '\0';
}
#include <stdlib.h>
#include <string.h>
int main() {
char **names, temp[32];
int n, i, j;
/* get the number of names from user */
printf("Enter the number of names:");
scanf("%d", &n);
getchar();
/* allocate memory to store input names */
names = (char **)malloc(sizeof(char *) * n);
for (i = 0; i < n; i++) {
names[i] = (char *)malloc(sizeof(char) * 32);
}
/* get the names from the user */
printf("Enter the input names:\n");
for (i = 0; i < n; i++) {
printf("Name[%d]: ", i);
fgets(names[i], 32, stdin);
names[i][strlen(names[i]) - 1] = '\0';
}
/* sort the names in alphabetical order */
for (i = 0; i < n - 1; i++) {
strcpy(temp,names[i]);
for (j = i + 1; j < n; j++) {
if (strcmp(temp, names[j]) > 0) {
strcpy(temp, names[j]);
strcpy(names[j], names[i]);
strcpy(names[i], temp);
}
}
}
/* print the sorted names */
printf("\nArranged Names In Alphabetical Order:\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
Enter the input names:
Name[0]: Sam
Name[1]: Anand
Name[2]: Raj
Name[3]: Vino
Name[4]: San
Arranged Names In Alphabetical Order:
Anand
Raj
Sam
San
Vino
Enter the number of names:5
Enter the input names:
Name[0]: Sam
Name[1]: Anand
Name[2]: Raj
Name[3]: Vino
Name[4]: San
Arranged Names In Alphabetical Order:
Anand
Raj
Sam
San
Vino
No comments:
Post a Comment