Lecture14 15structures EE
Lecture14 15structures EE
BSE1
Lecture 17
(Structures-Part-I)
Why Structures?
As we already know, an ordinary variable can hold
one piece of information.
Arrays are used to store large set of data and
manipulate them. The disadvantage is that all the
elements stored in an array are to be of the same data
type.
If we need to use a collection of different data type
items it is not possible using an array.
When we require using a collection of different data
items of different data types we can use a structure.
Structures
Definition: “A structure is a collection of
variables under a single name”.
This collection of variables can be of different
types, and each has a name which is used to
select it from the structure.
A structure is a convenient way of grouping
several pieces of related information together.
Structures (cont’d)
struct books
{
char title[20];
char author[15];
int pages;
float price;
};
OR
struct books
{
char title[20];
char author[15];
int pages;
float price;
} b1,b2,b3;
Initialization of the struct variables
struct books
{
char title[20];
char author[15];
int pages;
float price;
};
struct books
{
char title[20];
char author[15];
int pages;
float price;
};
struct books b1= {“Let us C”,”Yashawant”, 772,250.0 };
http://www.cplusplus.com/
Fundamentals of C++, Richard L. Halterman
Let us C, Yashwant Kanitkar
Programming Fundamentals
BSE1
Lecture 18
(Structures-Part-II)
Array of Structures
So far our sample program told us
How a structure can be declared.
How structure variables are declared.
How individual elements of structure variable are
referenced.
But what if we want to store data of 100
books?
We can use 100 different variables from b1 to
b100, which is obviously not a very convenient
way.
A better way will be to use an array of structures.
Array of Structures
main()
{
struct books
{
char title[20];
char author[15];
int pages;
float price;
};
struct books b[2];
int i;
for (i=0;i<2;i++)
{
cout<<"Enter title, author, pages and prices of books"<<endl;
cin>>b[i].title >> b[i].author>> b[i].pages>> b[i].price;
}
cout<<"Record of Books is:"<<endl;
for (i=0;i<2;i++)
{
cout<< b[i].title<<"\t"<<b[i].author<<"\t"<<b[i].pages<<"\t"<<b[i].price<<endl;
}}
Additional Features of
Structures
1- Nested Structures
main()
{
struct address
{
int phone;
char city[15];
int postal_c;
};
struct emp
{
char name[25];
struct address a;
};
struct emp e= {"Bushra", 212,"Rwp",10};
cout<<"Name"<<"\t"<<"Phone Number"<<"\t"<<"City"<<"\t"<<“Postal
Code"<<endl;
cout<<e.name<<"\t"<<e.a.phone<<"\t"<<"\t"<<e.a.city<<"\t"<<e.a.postal_c;
}
2. Functions and structures
Like ordinary variables , a structure can also
be passed to a function. We may either pass
individual structure elements or the entire
structure at one go.
2.1- Passing a individual structure elements to a function
int display(char *s, int t);
main()
{
struct book
{
char name[20];
int pages;
};
Let us C 772
system("pause");
}