WAP_F06: Write a C program that sorts a given array of names.|| Sorting and Searching
WAP_F06: C Lab Program
//Sorts a given array of names. #include <stdio.h> #include <string.h>
int main() { char names[50][50], temp[50]; int n, i, j;
// Input number of names printf("Enter number of names: "); scanf("%d", &n);
// Read names printf("Enter %d names:\n", n); for (i = 0; i < n; i++) { scanf("%s", names[i]); // Reads a single word as name }
// Sorting names using simple string comparison for (i = 0; i < n - 1; i++) { for (j = i + 1; j < n; j++) { if (strcmp(names[i], names[j]) > 0) { strcpy(temp, names[i]); strcpy(names[i], names[j]); strcpy(names[j], temp); } } }
// Print sorted names printf("\nNames in alphabetical order:\n"); for (i = 0; i < n; i++) { printf("%s\n", names[i]); }
return 0; } |
OUTPUT
Enter number of names: 6 Enter 6 names: Vishnu Hanuman Shiva Krishna Rama Ganesha
Names in alphabetical order: Ganesha Hanuman Krishna Rama Shiva Vishnu |
For all 2026 published articles list: click here
...till the next post, bye-bye & take care