C Array of Structures
When we need many records of the same type, we make an array of structures. It works like a small table: each element is one record.
Example: three students
#include <stdio.h>
struct Student {
int roll;
char name[20];
float marks;
};
int main(void) {
struct Student list[3] = {
{1, "Robin", 85.5f},
{2, "Maria", 92.0f},
{3, "John", 78.0f}
};
for (int i = 0; i < 3; i++) {
printf("%d %-6s %.1f\n", list[i].roll, list[i].name, list[i].marks);
}
return 0;
}
Output:
Output of the above program is
1 Robin 85.5
2 Maria 92.0
3 John 78.0
Find the topper
#include <stdio.h>
struct Student {
int roll;
char name[20];
float marks;
};
int main(void) {
struct Student list[4] = {
{1, "Robin", 85.5f}, {2, "Maria", 92.0f},
{3, "John", 78.0f}, {4, "Asha", 88.0f}
};
int top = 0;
for (int i = 1; i < 4; i++) {
if (list[i].marks > list[top].marks) {
top = i;
}
}
printf("Topper: %s with %.1f marks\n", list[top].name, list[top].marks);
return 0;
}
Output:
Output of the above program is
Topper: Maria with 92.0 marks
Read records from the user
#include <stdio.h>
struct Student {
char name[20];
int marks;
};
int main(void) {
struct Student s[2];
for (int i = 0; i < 2; i++) {
scanf("%19s %d", s[i].name, &s[i].marks);
}
for (int i = 0; i < 2; i++) {
printf("%s: %d\n", s[i].name, s[i].marks);
}
return 0;
}
Output:
Output of the above program is
Asha 88
Vikram 65
Asha: 88
Vikram: 65
Note:
To sort an array of structures, compare one member (like marks) and swap the whole structures. You can also use qsort() with your own compare function.
Next: C Pointer to Structure.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |