Summary - Structs
- C course
- Beginner
- Lesson 99/116
- 5 min
Combine struct, typedef and struct array to write a student database.
Summary - Structs
In this group you learned the basics of structs. struct unites different types; . accesses members. typedef gives a short name; a struct array holds multiple records; nested structs build complex models.
struct Point { int x; int y; };
typedef struct { int id; int grade; } Student;
struct Student students[2];
r.topleft.xThese concepts are the basis of data modeling in C. Without structs, real projects are very hard to write. Now you will do an exercise that combines all of them.
Practice Average grade of two students
Define struct Student (int id, int grade). Create a two-student array: {{1, 85}, {2, 90}}. Use a for loop to sum the grades; print the total with printf.
Starter code
#include <stdio.h>
/* Define struct Student (int id, int grade) */
int main(void) {
/* Declare a two-student array; sum grades with for; print with printf */
return 0;
}Sample solution
struct Student { int id; int grade; };
struct Student students[2] = {{1, 85}, {2, 90}};
int total = 0;
for (int i = 0; i < 2; i++) {
total += students[i].grade;
}
printf("%d\n", total);Expected output
175
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match concept to usage
| Term | Meaning |
|---|---|
struct |
Groups data |
. |
Member access |
typedef |
Gives short name |
struct[3] |
Three-element array |
2 How is a variable declared after a typedef struct?
- struct Point p;
- typedef Point p;
- new Point()
- Point p; Correct answer
Explanation: After typedef you write only Point p;
3 Fill in the blank: array element
printf("%d
", students[0]____);
printf("%d
", students[0].grade);
Explanation: students[0].grade gives the first student's grade.