0
0
Cprogramming~5 mins

Why structures are needed

Choose your learning style9 modes available
Introduction

Structures help group different pieces of related information together in one place. This makes it easier to organize and use data that belongs together.

When you want to store information about a person, like name, age, and height, all together.
When you need to keep details of a book, such as title, author, and pages, in one unit.
When managing data for a car, including model, year, and color, as a single item.
When you want to pass multiple related values to a function easily.
When you want to create a list of items where each item has several properties.
Syntax
C
struct StructureName {
    dataType member1;
    dataType member2;
    // ...
};
Use struct keyword to define a structure.
Each member can be a different data type, like int, float, or char.
Examples
This defines a structure named Person with three members: name, age, and height.
C
struct Person {
    char name[50];
    int age;
    float height;
};
This structure groups book details together.
C
struct Book {
    char title[100];
    char author[50];
    int pages;
};
Sample Program

This program creates a Person structure, assigns values to its members, and prints them. It shows how structures keep related data together.

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

struct Person {
    char name[50];
    int age;
    float height;
};

int main() {
    struct Person person1;

    // Assign values
    strncpy(person1.name, "Alice", sizeof(person1.name) - 1);
    person1.name[sizeof(person1.name) - 1] = '\0';
    person1.age = 30;
    person1.height = 5.5f;

    // Print values
    printf("Name: %s\n", person1.name);
    printf("Age: %d\n", person1.age);
    printf("Height: %.1f\n", person1.height);

    return 0;
}
OutputSuccess
Important Notes

Structures let you handle complex data easily by grouping related information.

You can create many variables of the same structure type to store multiple records.

Summary

Structures group different types of data into one unit.

They help organize and manage related information clearly.

Using structures makes your programs easier to read and maintain.