Write a C program to sort names in descending order.
#include <stdlib.h>
#include <string.h>
int main() {
char **names, tmp[100];
int i, j, n;
/* get the number of entries from the user */
printf("Enter the no of entries:");
scanf("%d", &n);
/* dynamically allocate memory to store names */
names = (char **)malloc(sizeof (char *) * n);
for (i = 0; i < n; i++)
names[i] = (char *)malloc(sizeof (char) * 100);
/* get the names from the user */
printf("Enter input names:\n");
getchar();
for (i = 0; i < n; i++) {
fgets(names[i], 100, stdin);
}
/* sort the names in descending order */
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(names[i], names[j]) < 0) {
strcpy(tmp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], tmp);
}
}
}
/* sorted names */
printf("\nNames In Descending Order:\n");
for (i = 0; i < n; i++)
printf("%s", names[i]);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the no of entries:5
Enter input names:
Adam
Sam
Nick
Fred
Edward
Names In Descending Order:
Sam
Nick
Fred
Edward
Adam
Enter the no of entries:5
Enter input names:
Adam
Sam
Nick
Fred
Edward
Names In Descending Order:
Sam
Nick
Fred
Edward
Adam
No comments:
Post a Comment