Ví dụ về sử dụng cấu trúc trong C

#include <stdio.h>
#include <string.h>

typedef struct Employee {
char name[50];
int id;
float salary;
} Employee;

void inputEmployees(Employee employees[], int n)
{
char buffer[100]; // temporary buffer for reading input with fgets()
for (int i = 0; i < n; i++) {
printf("Enter details of Employee %d:\n", i+1);
printf("ID: ");
scanf("%d", &employees[i].id);
getchar();

printf("Name: ");
fgets(buffer, sizeof(buffer), stdin); // read input with fgets()
buffer[strlen(buffer)-1] = '\0';
strncpy(employees[i].name, buffer, sizeof(employees[i].name)); // copy input to name field

printf("Salary: ");
scanf("%f", &employees[i].salary);
printf("\n");
}
}
void printEmployees(Employee employees[], int n) {
printf("**** Employee details:***\n");
for (int i = 0; i < n; i++) {
printf("Employee %d:\n", i+1);
printf("Name: %s\n", employees[i].name);
printf("ID: %d\n", employees[i].id);
printf("Salary: %.2f\n", employees[i].salary);
printf("\n");
}
}

float calculateAverageSalary(Employee employees[], int n) {
float totalSalary = 0;
for (int i = 0; i < n; i++) {
totalSalary += employees[i].salary;
}
return totalSalary / n;
}


int main() {
int n=3;
Employee employees[n];
//enter information of employees
inputEmployees(employees, n);

//get average salary
float averageSalary = calculateAverageSalary(employees, n);
printf("*** Average salary of employees: %.2f\n\n", averageSalary);
//print the detail
printEmployees(employees, n);

return 0;
}