DATA STRUCTURE AND ALGORITHM (Structure)

STRUCTURE

Structures in C++ are user defined data types which are used to store group of items of non-similar data types. 

Def:
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. 


Structure


Syntax Of Structure:
struct structureName{
    member1;
    member2;
    member3;
    .
    .
    .
    memberN;
};

Structures in C++ can contain two types of members:  

  • Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++.
  • Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration.
// Data Members
int roll;
int age;
int marks;
     
// Member Functions
void printDetails()
{
    cout<<"Roll = "<<roll<<"\n";
    cout<<"Age = "<<age<<"\n";
    cout<<"Marks = "<<marks;
}

In the above structure, the data members are three integer variables to store roll number, age and marks of any student and the member function is printDetails() which is printing all of the above details of any student.



Variable declaration with structure declaration:

struct Point { int x, y; } p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data types struct Point { int x, y; }; int main() { struct Point p1; // The variable p1 is declared like a normal variable }


Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory.


We can Initialize the Variables with Declaration in Structure in C++

#include <iostream> using namespace std; struct Point {     int x = 0; // It is Considered as Default Arguments and no Error is Raised     int y = 1; }; int main() {     struct Point p1;     // Accessing members of point p1     // No value is Initialized then the default value is considered. ie x=0 and y=1;     cout << "x = " << p1.x << ", y = " << p1.y<<endl;     // Initializing the value of y = 20;     p1.y = 20;     cout << "x = " << p1.x << ", y = " << p1.y;     return 0; }



How to access structure elements? 

#include <iostream>
using namespace std;

struct Point {
int x, y;
};

int main()
{
struct Point p1 = { 0, 1 };

// Accessing members of point p1
p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;

return 0;
}

Output:
x = 20, y = 1

What is an array of structures?

#include <iostream> using namespace std; struct Point { int x, y; }; int main() { // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << " " << arr[0].y; return 0; }


Output:
10 20
Connect with the Author:

Comments

Popular posts from this blog

DATA STRUCTURE AND ALGORITHM (Array)

DATA STRUCTURE AND ALGORITHM (Pointer)