C Structures Introduction

C Structures Introduction – Grouping Variables in C

In C, a structure (or struct) is a user-defined data type that allows you to group variables of different data types under one name. It’s perfect for representing real-world entities like a student, car, or employee.

🔸 Why Use Structures?

  • To group related data (like name, age, marks).
  • To create complex data types.
  • To improve code organization and readability.

🧠 Syntax: Defining a Structure

Use the struct keyword to define a structure.

struct StructureName {
    dataType member1;
    dataType member2;
    // more members...
};
  

Try It Now

📝 Example: Defining and Using a Structure

This example creates a structure for a student and prints the data.

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

struct Student {
    char name[50];
    int age;
    float marks;
};

int main() {
    struct Student s1;

    // Assign values
    strcpy(s1.name, "Alice");
    s1.age = 20;
    s1.marks = 89.5;

    // Display
    printf("Name: %s\n", s1.name);
    printf("Age: %d\n", s1.age);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}
  

Try It Now

🧾 Key Points

  • Structures allow you to group variables of different types.
  • You access members using the dot . operator.
  • You can declare variables of the structure type just like any other type.

🎯 Practice Tip!

Try creating your own structure for a Book with members like title, author, and price. Experiment and have fun!