C++ Structure

  • Structure is a user defined data type.
  • Structure is a collection of heterogeneous types of elements.
  • The variables declared within the structure may be pointer variables, arrays or variables of some other strcture.

Syntax


struct structure_name  
{  
    //Members of structure  
}   

How to Access Structure Members


Members of structure are individual entities so we can access them individually.
By using dot(.) or arrow operator (->) we can access values of members of structure.

Syntax


structure_variable.member_name;
or
structure_variable->member_name;

Program to show use of structure.




#include<iostream.h>
#include<conio.h>
struct data
{
   int a;
   float b;
}
void main()
{
    clrscr();
    data d;      //Declaration of structure variable
    d.a=10;
    d.b=6;
    cout<<"\n d.a="<<d.a;
    cout<<"\n d.b="<<d.b;
    getch();
} 


Output


d.a=10
d.b=6

Program to read and display a structure



#include<iostream.h>
#include<conio.h>
struct data
{
   int a;
   float b;
}
void main()
{
    clrscr();
    data d;
    cout<<"Enter value of d.a = ";
    cin>>d.a;
    cout<<"\nEnter value of d.b = ";
    cin>>d.b;
    cout<<"\nd.a = "<<d.a;
    cout<<"\nd.b = "<<d.b;
    getch();
}


Output


Enter value of d.a = 10
Enter value of d.b = 6.7
d.a = 10
d.b = 6.7

Back To Top