- How to declare and fill an array of structs
- How to sort an array using bubble sort — the simplest algorithm to understand
- How to swap two whole structs (not just one field)
- Why sorting on
s[j].agemoves the entire record, not just the age - How to print the sorted array with both name and age
Why sort by one field
When you have an array of students, you often want to order them by something — age, name, marks, roll number. The key insight is: you sort on one field, but you swap the whole record. If student A is older than student B, you swap their entire entries in the array — A moves to B's position, B moves to A's position, including their names. The comparison is on age, but the movement is on the whole struct.
This is the fundamental pattern for sorting records. You don't sort by moving the age values around separately from the names — you keep each student's data together and move the entire bundle. That's why you use an array of structs, not parallel arrays. The struct keeps the record intact through every swap.
For the sort algorithm itself, bubble sort is the simplest choice. It's not the fastest — a real program might use qsort or a better algorithm — but it's the clearest to read and write, and for five or fifty students the speed difference doesn't matter. The goal here is to understand the pattern, not to write production-grade sorting code.
💡 In one line: use bubble sort. Compare s[j].age with s[j+1].age. If they're out of order, swap the whole structs using a temporary variable. Repeat until no swaps are needed. Print the array.
Designing the struct and array
The struct is the same simple one from assignment 24 — two members, name and age:
struct student {
char name[50];
int age;
};
The array holds five of them:
struct student s[5];
Once you have an array, you can access any field of any student with two dots: s[i].name, s[i].age. The square brackets pick the student, the dot picks the field. To swap two students, you need a temporary struct variable:
struct student temp;
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
That's the whole swap — no need to copy name and age separately. C handles struct assignment member by member automatically. This is one of the biggest advantages of a struct: once you have the pattern, swapping records is as easy as swapping integers.
| Expression | Means | Example |
|---|---|---|
| s[i] | One student (whole struct) | s[2] is the third student |
| s[i].name | That student's name | "Rahul" |
| s[i].age | That student's age | 20 |
Complete C Program
Program: hard-coded array, sort by age with bubble sort
#include <stdio.h>
struct student {
char name[50];
int age;
};
int main(void) {
struct student s[5] = {
{"Rahul", 22},
{"Priya", 19},
{"Amit", 21},
{"Sneha", 20},
{"Vikram", 23}
};
/* Bubble sort — ascending by age */
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (s[j].age > s[j+1].age) {
struct student temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
printf("--- Students sorted by age ---\n");
for (int i = 0; i < 5; i++) {
printf("%-10s %d\n", s[i].name, s[i].age);
}
return 0;
}
And here's a version that reads the students from the user — useful if you want to test with different values:
Variant: read students from the user
#include <stdio.h>
struct student {
char name[50];
int age;
};
int main(void) {
struct student s[5];
printf("Enter 5 students (name age):\n");
for (int i = 0; i < 5; i++) {
scanf("%49s %d", s[i].name, &s[i].age);
}
/* Bubble sort — ascending by age */
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4 - i; j++) {
if (s[j].age > s[j+1].age) {
struct student temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
printf("\n--- Students sorted by age ---\n");
for (int i = 0; i < 5; i++) {
printf("%-10s %d\n", s[i].name, s[i].age);
}
return 0;
}
And here's a third version that wraps the sort logic in its own function — good practice for separating concerns and easier to test:
Variant: with a sort function
#include <stdio.h>
struct student {
char name[50];
int age;
};
void sort_by_age(struct student s[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (s[j].age > s[j+1].age) {
struct student temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
}
void print_students(struct student s[], int n) {
for (int i = 0; i < n; i++) {
printf("%-10s %d\n", s[i].name, s[i].age);
}
}
int main(void) {
struct student s[5] = {
{"Rahul", 22},
{"Priya", 19},
{"Amit", 21},
{"Sneha", 20},
{"Vikram", 23}
};
printf("--- Before sorting ---\n");
print_students(s, 5);
sort_by_age(s, 5);
printf("\n--- After sorting by age ---\n");
print_students(s, 5);
return 0;
}
All three versions do the same thing. The first is the shortest, the second is more flexible, and the third is the cleanest — separating the sort and print logic into their own functions makes the main function read like a story: fill, sort, print. That's the version to write when you're building something real.
Program Output
For the first version (hard-coded array):
--- Students sorted by age ---
Priya 19
Sneha 20
Amit 21
Rahul 22
Vikram 23
For the user-input version, try entering the same students in a different order:
Enter 5 students (name age):
Vikram 23
Priya 19
Rahul 22
Sneha 20
Amit 21
--- Students sorted by age ---
Priya 19
Sneha 20
Amit 21
Rahul 22
Vikram 23
For the third version (with a sort function), you get both the before and after:
--- Before sorting ---
Rahul 22
Priya 19
Amit 21
Sneha 20
Vikram 23
--- After sorting by age ---
Priya 19
Sneha 20
Amit 21
Rahul 22
Vikram 23
Notice that the names move with their ages. Before sorting, Priya was second with age 19. After sorting, she's first — because she has the smallest age. The names didn't get sorted separately; they followed their ages, because the struct keeps them together.
Step-by-Step Explanation
Let's walk through the key pieces.
1. The struct definition
struct student { char name[50]; int age; }; — same two members as assignment 24. The struct defines what one student record looks like. No change here.
2. The array of structs
struct student s[5]; creates five student records, laid out contiguously in memory. Each element s[i] is a full struct. This is why you can sort the array: swapping s[j] with s[j+1] swaps the entire record (name and age together).
3. The bubble sort loops
Two nested loops. The outer loop i runs from 0 to n-2. The inner loop j runs from 0 to n-2-i. Each pass through the inner loop compares adjacent pairs and swaps them if they're out of order. After the first pass, the largest element is at the end. After the second pass, the second-largest is in its place. After n-1 passes, everything is sorted. That's bubble sort.
4. The comparison
if (s[j].age > s[j+1].age) compares the age of student j with the age of student j+1. If the first is bigger (older), they're out of order for ascending sort. If you wanted descending sort, you'd flip the > to <.
5. The swap
Three lines:
struct student temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
The first line copies the whole struct from position j into temp. The second line overwrites position j with the struct from position j+1. The third line writes temp into position j+1. After these three lines, the two students have swapped places — names, ages, everything. You don't need to swap fields individually; C handles the whole struct at once.
6. Why swapping whole structs matters
If you had parallel arrays — one for names, one for ages — you'd need to swap both arrays at the same index to keep them aligned. That's error-prone. With an array of structs, one swap moves everything. That's the whole reason structs are the right choice for record-oriented data.
7. The print loop
for (int i = 0; i < 5; i++) printf("%-10s %d\n", s[i].name, s[i].age); — walks through the array in order and prints each student. The %-10s left-aligns the name in a 10-character field, so the ages line up in a column. That's a cosmetic touch, but it makes the output much easier to read.
8. Why bubble sort and not qsort?
Bubble sort is O(n²) — slow for large arrays. qsort is O(n log n) — much faster. But for five students, the difference is invisible. The point of this assignment is to see how the sort interacts with structs, not to write the fastest possible sort. Once you understand bubble sort on structs, using qsort with a comparison function is a small step — but it's a step for a later day.
9. Why the outer loop condition is i < 4 (or i < n-1)
You need n-1 passes to guarantee a fully sorted array. On each pass, one more element ends up in its final position. After n-1 passes, every element is in place. The inner loop's condition j < 4 - i (or j < n-1-i) shrinks the range of comparisons on each pass, because the last i elements are already sorted. That's a small optimization, but it's also a common source of confusion if you're not expecting it.
🎯 Remember this: sort by one field, swap the whole struct. Use bubble sort for simplicity, not for speed. Declare a temporary struct for the swap. Loop through the sorted array to print. That's the whole pattern, and it works for any sortable struct field — age, name, marks, anything.
Frequently Asked Questions
1. Can I sort by name instead of age?
Yes. Replace s[j].age > s[j+1].age with strcmp(s[j].name, s[j+1].name) > 0. You'll need to include <string.h>. The rest of the code stays the same — the swap still moves the whole struct. strcmp returns a positive value when the first string comes after the second alphabetically, so the comparison works the same way.
2. What if two students have the same age?
Bubble sort with > is a stable sort — students with equal ages keep their original relative order. If you wanted to break ties by name (e.g., sort by age, then alphabetically by name for equal ages), you'd add a secondary comparison: if (s[j].age > s[j+1].age || (s[j].age == s[j+1].age && strcmp(s[j].name, s[j+1].name) > 0)). That's a common interview follow-up.
3. Why does the outer loop stop at n-1 instead of n?
Because after n-1 passes, the array is guaranteed to be sorted. The last element ends up in place automatically after the second-to-last pass. If you looped n times, the extra pass would do nothing useful. The n-1 bound is a small but real optimization — and it's the standard form of bubble sort.
4. Why does the inner loop shrink from pass to pass?
After the first pass, the largest element has bubbled to the last position. After the second pass, the second-largest is in its place. So on pass i, the last i elements are already sorted and don't need to be compared again. The condition j < n-1-i skips those elements. It's not required for correctness — you could always compare to the end — but it saves comparisons.
5. Can I use qsort instead of bubble sort?
Yes. qsort is in <stdlib.h> and takes a comparison function. The call looks like qsort(s, 5, sizeof(struct student), compare_by_age), and you write int compare_by_age(const void *a, const void *b) which casts to struct pointers and returns the difference of ages. It's faster (O(n log n)) but more code. For five students, bubble sort is perfectly fine and easier to read. For hundreds of students, qsort is worth the extra setup.
6. How do I swap without a temporary struct?
You can't, in standard C. Unlike integers, you can't use XOR-swap on structs. The three-line swap with a temporary variable is the correct approach, and it works for any struct size. There's no shortcut that's clearer or safer. Use it.
💡 Tip: After this, try sorting by name with strcmp. Try sorting in descending order — just flip the > to <. Try sorting by a compound key — age first, then name for ties. Try sorting a larger array (say 100 students) and compare bubble sort's time to qsort's. Each of these builds on the same pattern: pick a field, compare, swap the whole struct, print.