You are on page 1of 12

Structure

• Collection of related elements or data items


• Collection of multiple data types that can be
referenced with single name.
• A structure is unlike an array,
 all elements in an array are of the same type. But
 in structures, the elements can be of different types.
• Are commonly used in File processing.
• File is a collection of related records and a record
is a collection of related fields of the same or
different types.
Declaring a Structure
• Declaration tells the compiler about the details of
the structure.
• Compiler does not allocate any memory
• Syntax
struct structname
{
datatype identifier1;
datatype identifier2;
.
.
.
};
• Example
struct student
{
int rollno, marks;
float avg;
char grade;
};
Defining Structure Variable
• Structure variable can be defined after the
declaration of structure of a structure.
• Structure definition tells the compiler to
allocate memory space for the variable.
• Syntax
structname identifier;
• Example
Student s;
Accessing Members of Structure
Variable
• Any member of a structure variable can be
accessed by using dot operator also known as
member access operator.
• Syntax
struct_variable.structure_element
• Example
student s;
s.rollno=1;
s.marks=690;
s.avg=60.75;
s.grade=‘B’;
• cin>>s.rollno;
• cin>>s.marks;
• cin>>s.avg;
• cin>>s.grade;
------------------------------------
• cout<<s.rollno;
• cout<<s.marks;
• cout<<s.avg;
• cout<<s.grade;
#include<iostream.h>
struct student
{ int rno,marks;
float avg;
char grade;
};
void main()
{
clrscr();
student s;
cout<<“enter roll no = “;
cin>>s.rno;
cout<<”ener marks = “;
cin>>s.marks;
cout<<“enter avg =“;
cin>s.avg;
cout<<“enter grade =“;
cin>>s.grade;
Cout<<“ u entered “;
Cout<<“roll no “<<s.rno<<endl;
Cout<<“marks “<<s. marks<<endl;
Cout<<“avg “<<s.avg<<endl;
Cout<<“grade “<<s.grade;

getch();
}
Initializing structure variable
• Syntax
structure-name identifier={value1,…}
• Example
student s={1,786,90.65,’A’}
Array of Structures
• An array can be of user-defined type such as a structure.
• Can be used to store many records.
• Example
struct book
{ int bookid, pages;
float price;
};

book b[3];

Array can store the records of three books.


Array of structure can accessed as
B[0].bookid=1;
B[0].pages=250;
B[0]price=150;
B[1].bookid=1;
B[1].pages=250;
B[1].price=150;
B[2].bookid=1;
B[2].pages=250;
B[2].price=150;
Initializing Array of Structure
struct book
{ int bookid, pages;
float price;
};
Book b[3]={ {1,150,68.50},{ … },{…}}
struct book
{ int bookid, pages;
float price;
};
Void main()
{
book b[5];
int I,max,m;
for(i=0;i<=4,i++)
{cout<<“ enter bid =“;
cin>>b[i].bookid;
cout<<“ enter pages =“;
cin>>b[i].pages;
cout<<“ enter price =“;
cin>>b[i].price;
}

You might also like