🏗️Beginner

Store Information of Students Using Structure

Student data structure

A structure groups related variables of different types under one name. Perfect for representing real-world entities like students, books, employees, etc.

❓ Why Use Structures?

❌ Without Structure

int id1, id2, id3;
char name1[50], name2[50];
float gpa1, gpa2, gpa3;

Hard to manage and error-prone

✓ With Structure

struct Student s1, s2, s3;
struct Student students[100];

Clean, organized, and scalable

🏗️ Structure Diagram

struct Student
intid(4 bytes)
char[50]name(50 bytes)
floatgpa(4 bytes)

Program Code

struct_student.c
C
1#include <stdio.h>
2#include <string.h>
3
4// Define the structure
5struct Student {
6 int id; // Student ID
7 char name[50]; // Student name
8 float gpa; // Grade point average
9};
10
11int main() {
12 // Declare a structure variable
13 struct Student s1;
14
15 // Input student data
16 printf("Enter student ID: ");
17 scanf("%d", &s1.id); // Use &s1.id (address of member)
18
19 printf("Enter name: ");
20 scanf("%49s", s1.name); // Array name is already an address
21
22 printf("Enter GPA: ");
23 scanf("%f", &s1.gpa);
24
25 // Display student data using dot operator
26 printf("\n--- Student Information ---\n");
27 printf("ID: %d\n", s1.id);
28 printf("Name: %s\n", s1.name);
29 printf("GPA: %.2f\n", s1.gpa);
30
31 return 0;
32}
Output

Enter student ID: 101

Enter name: John

Enter GPA: 3.75

 

--- Student Information ---

ID: 101

Name: John

GPA: 3.75

Code Explanation

struct Student { ... }

Defines a new data type called struct Student. This is a blueprint, not a variable.

struct Student s1;

Creates a variable s1 of type struct Student. Memory is allocated for all members.

s1.id, s1.name, s1.gpa

The dot operator (.) accesses structure members.

📝 Different Ways to Initialize

struct Student s1 = {101, "John", 3.75};

In order of declaration

struct Student s2 = {.name = "Jane", .id = 102, .gpa = 3.9};

Designated initializers (C99) - any order

🎯 Key Takeaways

Group related data together
Use dot (.) to access members
struct is a user-defined type
Can create arrays of structures