Welcome to this comprehensive guide on C Structures! This tutorial is designed to help you understand the essence of Structures in C programming, whether you're a beginner or an intermediate learner.
In C, a structure is a user-defined data type that allows us to combine data items of different kinds into a single entity. This is particularly useful when dealing with complex data sets, such as records containing different fields like name, age, and address.
To create a structure, we use the struct keyword, followed by the structure tag (name), and then enclose the members (fields) within curly braces {}.
struct student {
int roll_number;
char name[50];
float marks;
};In the example above, we've created a structure named student with three members: roll_number, name, and marks.
To access a structure's members, we use the dot (.) operator. Here's an example of how to create and initialize a student structure:
struct student s1 = {1, "John Doe", 85.5};To access and print the values, use the dot operator like this:
printf("Roll Number: %d\n", s1.roll_number);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);Just like regular arrays, we can create an array of structures to store multiple records. For example:
struct student students[100];What does a structure allow us to do in C programming?
Let's build a simple student management system that reads student records from a file and calculates the average marks:
#include <stdio.h>
struct student {
int roll_number;
char name[50];
float marks;
};
void readStudents(struct student students[], int size);
void calculateAverage(struct student students[], int size);
int main() {
struct student students[100];
int n;
readStudents(students, 100);
calculateAverage(students, 100);
return 0;
}
void readStudents(struct student students[], int size) {
// Code to read student records from a file and store them in students array
}
void calculateAverage(struct student students[], int size) {
float total = 0;
for (int i = 0; i < size; i++) {
total += students[i].marks;
}
printf("Average Marks: %.2f\n", total / size);
}In this example, we've created a simple student management system that reads student records from a file and calculates the average marks. The readStudents() function is responsible for reading the data from the file, and the calculateAverage() function calculates the average marks.
That's it for this introductory lesson on C Structures! Stay tuned for more in-depth lessons on C programming. Happy coding! 🤘🏼