Structure in C++ Programming with Example.

In programming, we often get a situation in which we want to store a group of related data together as a single unit. We can use Array in C++ to store similar data types but what to use to store non-similar data together? 


In C++, structures provide a powerful tool for organizing related data elements into a single entity. They allow programmers to create user-defined data types, facilitating the representation of complex entities.


What is a Structure?

A structure is a user-defined data type in C++ that allows the grouping of different data elements of different types under a single name. It provides a convenient way to represent a complex entity by combining variables of various data types into a single unit.

Syntax of Structure

How to create a Structure in C++?

In C++, a structure is created using the struct keyword followed by the structure name and a block of member declarations enclosed within curly braces. Each member declaration represents a variable of a specific data type. 

Syntax:

struct StructureName {
    // Member declarations
    DataType1 member1;
    DataType2 member2;
    // ...
};

Inside the curly braces {}, you declare the members of the structure. You can include multiple member declarations of different data types.

Structure in C++ can contain data members as well as member functionsHere's an example to illustrate this.

Example:
struct Rectangle {
    // Data members
    double length;
    double width;
    
    // Member function to calculate the area
    double calculateArea() {
        return length * width;
    }
};

In the above example, we define a struct named Rectangle that represents a rectangle shape. It contains two data members: length and width, which store the dimensions of the rectangle.


How to Declare and Initialize Structure Variables?

Once a structure is defined, variables of that structure type can be declared using the structure name followed by the variable name. Structure members can be initialized at the time of declaration using the dot (.) operator to access the member and assign it a value.

Example: 
int main(){
   //Declaration of structure variable
   Rectangle r1;
   r1.length = 5.0;
   r1.width = 3.0;
   Rectangle r2 {10.0, 9.0};
}

In the main() function, we create an instance of the Rectangle struct named rectangle. We assign values to its data members' length and width.

How to Access Structure Variable?

To access the elements of a structure variable, the dot (.) operator is used to access a specific member. 

Example:
//accessing members
cout << "Rectangle Length: " << r1.length << endl;
cout << "Rectangle Width: " << r1.width << endl;

Here is a complete working example of Structure using C++ programming.
//C++ Example Program to show working of structure
#include <iostream>
using namespace std;

struct Rectangle {
    // Data members
    double length;
    double width;
    
    // Member function to calculate the area
    double calculateArea() {
        return length * width;
    }
};

int main() {
    //declaring struct variable
    Rectangle r1;
    r1.length = 5.0;
    r1.width = 3.0;
    
    //Accessing structure elments
    cout<<"Rectangle Length: " << r1.length <<endl;
    cout<<"Rectangle Width: " <<r1.width <<endl;

    double area = r1.calculateArea();
    std::cout << "Area: " << area << std::endl;
    
    return 0;
}
Output:
Rectangle Length: 5
Rectangle Width: 3
Area: 15

As we can see in the above code, the struct contains both data members (length and width) and member functions calculateArea(). This allows us to encapsulate related data and behavior within a single struct, providing a convenient way to work with objects and perform operations on them.

What is an Array of Structures?

An array of structures allows the creation of multiple instances of a structure. It provides a convenient way to store and manipulate a collection of related data elements.

Example of Array Structure:
//C++ program to show working of Array Structure.
#include <iostream>
#include <string>
using namespace std;

struct Student {
    std::string name;
    int age;
    int rollNumber;
};

int main() {
    const int SIZE = 3;
    Student students[SIZE];

    // Populate the array of structures
    students[0] = { "John Doe", 18, 101 };
    students[1] = { "Jane Smith", 19, 102 };
    students[2] = { "Alice Johnson", 20, 103 };

    // Access and display the data
    for (int i = 0; i < SIZE; ++i) {
        cout << "Student #" << i + 1 << endl;
        cout << "Name: " << students[i].name << endl;
        cout << "Age: " << students[i].age << endl;
        cout << "Roll Number: " << students[i].rollNumber << endl;
        cout << endl;
    }

    return 0;
}
output:
Student #1
Name: John Doe
Age: 18
Roll Number: 101

Student #2
Name: Jane Smith
Age: 19
Roll Number: 102

Student #3
Name: Alice Johnson
Age: 20
Roll Number: 103


What is Structure Pointer?

A structure pointer is a pointer variable that points to a structure. It allows indirect access to the members of the structure using the arrow (->) operator.

Example of Structure Pointer:
//C++ Program to show working of structure pointer
#include <iostream>
#include <string>
using namespace std;

struct Person {
    std::string name;
    int age;
};

int main() {
    Person person;
    person.name = "John Doe";
    person.age = 30;

    // Create a structure pointer
    Person* personPtr = &person;

    // Access structure members using the arrow operator
    cout << "Name: " << personPtr->name << endl;
    cout << "Age: " << personPtr->age << endl;

    // Modify structure members using the arrow operator
    personPtr->name = "Jane Smith";
    personPtr->age = 25;

    // Access modified structure members
    cout << "Updated Name: " << person.name << endl;
    cout << "Updated Age: " << person.age << endl;

    return 0;
}
Output:
Name: John Doe
Age: 30
Updated Name: Jane Smith
Updated Age: 25

By using structure pointers, you can dynamically allocate memory for structures, pass structures to functions by reference, and efficiently access and modify structure members.

What is Structure Member Alignment?

Structure member alignment refers to the arrangement of structure members in memory. It ensures that each member is aligned according to its data type's memory requirements to optimize memory access and prevent memory alignment issues.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS