STRUCTURES:
We have seen
that arrays can be used to represent a group of data items that belong to the
same type, such as int or float. However if we want to represent a collection
of data items of different types using a single name, then we cannot use array.
C supports a
constructed data type known as structure, which is a method of packing data of
different data types.
A structure is a
convenient tool for handling a group of logically related data items.
Def:- A structure is a collection of one or more
members of different data types grouped together under a single name.
An array
can store more number of elements that belong to same datatype but by using a
structure we can store number of elements each of different datatype under the
same name.
Declaration of a
structure:-
A structure can be declared as follows:
Syntax:-
Struct tagname
{
data member 1;
data member
2;
:
:
data member
n;};
·
The keyword struct
is used to declare a structure.
·
The tagname indicates the name of the structure.
·
member 1,member 2,……up to member n are the
members of different datatypes which are to be stored under the tagname.
·
The structure declaration should always
terminate with a semicolon.
·
The
members are not variables by themselves. The members are used to indicate the
different datatypes of information that is stored under the tagname.
Declaration of
structure variables:-
To access the members of a
structure, structure variables are to be declared after the declaration of a
structure.
e.g.,
struct student
{
char name[10];
int rollno;
float avg;
};
struct student s1;
Where s1 is the structure variable which occupies 16 bytes(10 for name, 2 for rollno, 4 for avg).
The
structure declaration and variable declaration can be combined as follows:
Struct student
{
char name[20];
int rollno;
float avg;
}s1;
Initialization of a
structure:-
Ø
A structure can be initialized as follows:
struct tagname variable={values separated
with commas};
Ø
Where order of initialization should be same as
order of member declaration.
Eg., struct student s1={“ramya”,20,80.5};
Ø
The values can be initialized to the variables
using dot operator(.).
Syntax:-
Variablename.member name=value;
Eg., s1.rollno=5;
Ø
Dot operator is also known as member operator or
period operator.
Ø A
Program to initialize the structure and display the details.
void main()
{
struct book
{
char name[10];
int pages;
float price;
};
struct book b1={“c& ds”,250,150.5};
printf(“name=%s”,b1.name);
printf(“pages=%d”,b1.pages);
printf(“price=%f”,b1.price);
getch();
}
Ø
A Program to enter and print details of a structure.
void main()
{
struct book
{
char name[10];
int pages;
float price;
};
struct book b1;
printf(“enter details\n”);
scanf(“%s,b1.name);
scanf(“%d”,&b1.pages);
scanf(“%f”,&b1.price);
printf(“the details are\n”);
printf(“name=%s”,b1.name);
printf(“pages=%d”,b1.pages);
printf(“price=%f”,b1.price);
getch();
}
No comments:
Post a Comment