Lesson 4 of 6 · Strings, Structs and Files · 3 min read · Updated
Array of structures
A whole class of student records in one array: storing, printing, averaging, finding the topper and sorting.
One struct Student holds one student. An array of structures holds a whole class: cls[i] is the i-th student, and cls[i].marks is that student's marks. This is how real programs keep lists of records.
#include <stdio.h>
struct Student {
char name[20];
int roll;
float marks;
};
int main(void)
{
struct Student cls[3] = {
{"Priya", 101, 87.5f},
{"Arun", 102, 73.0f},
{"Meena", 103, 94.5f},
};
int top = 0;
float total = 0;
for (int i = 0; i < 3; i++) {
printf("%-6s %d %.1f\n", cls[i].name, cls[i].roll, cls[i].marks);
total += cls[i].marks;
if (cls[i].marks > cls[top].marks) {
top = i;
}
}
printf("Average: %.2f\n", total / 3);
printf("Topper: %s\n", cls[top].name);
return 0;
}
Priya 101 87.5
Arun 102 73.0
Meena 103 94.5
Average: 85.00
Topper: Meena
Sorting records by marks
#include <stdio.h>
struct Student {
char name[20];
float marks;
};
int main(void)
{
struct Student cls[4] = {
{"Priya", 87.5f}, {"Arun", 73.0f}, {"Meena", 94.5f}, {"Ravi", 66.0f},
};
int n = 4;
/* Bubble sort, highest marks first. The whole struct is swapped. */
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (cls[j].marks < cls[j + 1].marks) {
struct Student t = cls[j];
cls[j] = cls[j + 1];
cls[j + 1] = t;
}
}
}
for (int i = 0; i < n; i++) {
printf("%d. %-6s %.1f\n", i + 1, cls[i].name, cls[i].marks);
}
return 0;
}
1. Meena 94.5
2. Priya 87.5
3. Arun 73.0
4. Ravi 66.0
Structs can be assigned in one go — struct Student t = cls[j]; copies every field, the name included. So sorting records is the same bubble sort as for numbers; only the comparison looks inside the struct.
Note
%-6s prints the name left-aligned in 6 spaces, which keeps the columns tidy. And a struct can itself contain an array — float marks[5]; for five subjects — giving you cls[i].marks[j].
How do you read the roll number of the third student in struct Student cls[10]?
Try this now
- Read the name and marks of 5 students with scanf, then print everyone who scored above the class average.
- Add
float marks[3]for three subjects to the struct and print each student's total and grade. - Search the array for a roll number the user types and print that student, or "Not found".
Create a free account to save your progress, or sign in.