Welcome back to CodeYourCraft! Today, we're diving into a fascinating topic - Arrays of Structures in C programming. This lesson is designed for beginners and intermediates alike, so let's get started! 🎉
In C programming, a structure is a user-defined data type that allows you to combine data items of different types into a single entity. Structures are useful when you need to work with complex data that cannot be represented with simple data types like int or float.
// Defining a structure called 'Student'
struct Student {
int roll_number;
char name[50];
float marks;
};In the above example, we've created a structure named Student which consists of three fields: roll_number, name, and marks. Each field represents a different type of data.
Now that we understand structures, let's learn how to create an array of structures.
// Creating an array of 10 Students
struct Student students[10];In the above code, we've created an array of 10 Student structures. Each element of the array can now be accessed like any other array element.
// Accessing a student in the array
students[0].roll_number = 1;
strcpy(students[0].name, "John Doe");
students[0].marks = 90.5;In the above example, we've accessed the first element of the students array and assigned values to its fields.
Let's create a simple program to manage school records using arrays of structures.
#include <stdio.h>
#include <string.h>
// Defining the Student structure
struct Student {
int roll_number;
char name[50];
char address[100];
float marks;
};
// Function to add a student to the array
void add_student(struct Student students[], int size) {
if (size >= 10) {
printf("Array is full.\n");
return;
}
printf("Enter student's roll number: ");
scanf("%d", &students[size].roll_number);
printf("Enter student's name: ");
scanf("%s", students[size].name);
printf("Enter student's address: ");
scanf("%s", students[size].address);
printf("Enter student's marks: ");
scanf("%f", &students[size].marks);
}
// Function to display student details
void display_student(struct Student student) {
printf("Roll Number: %d\n", student.roll_number);
printf("Name: %s\n", student.name);
printf("Address: %s\n", student.address);
printf("Marks: %.2f\n", student.marks);
}
// Function to display all students
void display_students(struct Student students[], int size) {
for (int i = 0; i < size; i++) {
display_student(students[i]);
}
}
int main() {
struct Student students[10];
int size = 0;
while (size < 10) {
add_student(students, size);
size++;
}
printf("Students:\n");
display_students(students, size);
return 0;
}In the above code, we've created a program that allows you to add up to 10 students and their details. It then displays all the student records.
What is the purpose of a structure in C programming?
How do you create an array of structures in C programming?