0
0
C++programming~5 mins

Why structures are needed in C++

Choose your learning style9 modes available
Introduction

Structures help group related data together in one place. This makes it easier to organize and use information about things.

When you want to store information about a person, like name, age, and height.
When you need to keep details about a book, such as title, author, and pages.
When you want to manage data about a car, like model, year, and color.
When you want to pass multiple related values to a function easily.
Syntax
C++
struct StructureName {
    dataType member1;
    dataType member2;
    // more members
};
Each member inside a structure can be a different type.
Structures group data but do not hold functions (in basic use).
Examples
This structure stores a person's name, age, and height.
C++
struct Person {
    char name[50];
    int age;
    float height;
};
This structure holds information about a book.
C++
struct Book {
    char title[100];
    char author[50];
    int pages;
};
Sample Program

This program creates a Person structure, fills it with data, and prints it. It shows how structures keep related data together.

C++
#include <iostream>
using namespace std;

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

int main() {
    Person p1 = {"Alice", 30, 5.5f};
    cout << "Name: " << p1.name << "\n";
    cout << "Age: " << p1.age << "\n";
    cout << "Height: " << p1.height << "\n";
    return 0;
}
OutputSuccess
Important Notes

Structures make your code cleaner and easier to understand by grouping related data.

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

Summary

Structures group different pieces of data into one unit.

They help organize information about real-world things.

Using structures makes your programs easier to read and manage.