C Online Compiler
Example: Sort Names Alphabetically using Structures in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Sort Names Alphabetically using Structures #include <stdio.h> // Required for printf, scanf #include <string.h> // Required for strcmp, strcpy // Define a structure to hold a person's name struct Person { char name[50]; // Assuming names won't exceed 49 characters + null terminator }; int main() { // Step 1: Declare an array of structures // Let's sort 5 names for this example const int MAX_PEOPLE = 5; struct Person people[MAX_PEOPLE]; int i, j; // Loop counters struct Person temp; // Temporary structure for swapping // Step 2: Get names from the user printf("Enter %d names:\n", MAX_PEOPLE); for (i = 0; i < MAX_PEOPLE; i++) { printf("Name %d: ", i + 1); // Using scanf with %s for simplicity, but consider fgets for names with spaces // If using fgets: fgets(people[i].name, sizeof(people[i].name), stdin); // Then remove newline if present: people[i].name[strcspn(people[i].name, "\n")] = 0; scanf("%s", people[i].name); } // Step 3: Sort the names using Bubble Sort // Outer loop for passes for (i = 0; i < MAX_PEOPLE - 1; i++) { // Inner loop for comparisons and swaps for (j = 0; j < MAX_PEOPLE - 1 - i; j++) { // Compare names using strcmp // strcmp returns < 0 if first string is smaller (comes first alphabetically) // strcmp returns > 0 if first string is larger (comes after alphabetically) // strcmp returns 0 if strings are equal if (strcmp(people[j].name, people[j+1].name) > 0) { // If the current name is alphabetically greater than the next name, swap them temp = people[j]; // Store current structure in temp people[j] = people[j+1]; // Move next structure to current position people[j+1] = temp; // Move temp structure to next position } } } // Step 4: Display the sorted names printf("\nNames sorted in alphabetical order:\n"); for (i = 0; i < MAX_PEOPLE; i++) { printf("%s\n", people[i].name); } return 0; }
Output
Clear
ADVERTISEMENTS