🏗️📚Intermediate
Store and Sort Student Records by Name
Sort structures by name
Store student records and sort them by name alphabetically.
Program Code
struct_sort_name.c
C
1#include <stdio.h>2#include <string.h>34struct Student {5 int id;6 char name[50];7 float gpa;8};910int main() {11 struct Student students[] = {12 {101, "Charlie", 3.5},13 {102, "Alice", 3.9},14 {103, "Bob", 3.7},15 {104, "David", 3.2}16 };17 int n = 4;18 19 printf("Before sorting:\n");20 for (int i = 0; i < n; i++) {21 printf("ID: %d, Name: %-10s, GPA: %.2f\n", 22 students[i].id, students[i].name, students[i].gpa);23 }24 25 // Bubble sort by name26 for (int i = 0; i < n - 1; i++) {27 for (int j = 0; j < n - i - 1; j++) {28 if (strcmp(students[j].name, students[j+1].name) > 0) {29 struct Student temp = students[j];30 students[j] = students[j + 1];31 students[j + 1] = temp;32 }33 }34 }35 36 printf("\nAfter sorting by name:\n");37 for (int i = 0; i < n; i++) {38 printf("ID: %d, Name: %-10s, GPA: %.2f\n", 39 students[i].id, students[i].name, students[i].gpa);40 }41 42 return 0;43}Output
Before sorting:
ID: 101, Name: Charlie , GPA: 3.50
ID: 102, Name: Alice , GPA: 3.90
ID: 103, Name: Bob , GPA: 3.70
ID: 104, Name: David , GPA: 3.20
After sorting by name:
ID: 102, Name: Alice , GPA: 3.90
ID: 103, Name: Bob , GPA: 3.70
ID: 101, Name: Charlie , GPA: 3.50
ID: 104, Name: David , GPA: 3.20
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials