Professional Documents
Culture Documents
struct structuretag
{
datatype variablename1;
datatype variablename2;
.
.
};
here struct is the keyword to define a structure.Structure tag or structure name is
an identifier and it is the new user defined data type. Variable1,variable2 etc are the
structure elements .
2) struct student
{
int admno;
char name[20];
char group[10];
float fee;
};
work for you
Note: Structure tag can be avoided as follows if we declare structure variable along
with the definition.But it has some limitations.
struct
{
int admno;
char name[20];
char group[10];
float fee;
}s1,s2;
Variable initialisation
Initialisation means assigning values to a variable.After declaring a
structure variable it can be initialised as follows.
Syntax: structuretag variable={value1,value2,......};
Ex: student s1={100,”Anurag”,”Science”,250.00};
Note: A structure variable can be assigned with the values of another structure
variable if they should be of the same structure type
ex: student s2=s1;
Accessing elements of a structure
The dot operator(.) is used with structure variable for accessing elements of a
structure.
Syntax: stucturevariable.elementname;
Ex: cin>>s1.admno;
cout<<s1.fee;
Note:
Consider the two structures given below.
struct test1 struct test2
{ {
int a; and int a;
float b; float b;
}t1={4,5.5} }t2;
here t2=t1 is invalid because t2 and t1 are of different types as test2 and
test1respectively.
But t2.a=t1.a; and t2.b=t1.b is possible.
Program1: Using structure to read and write the details of a students
#include<iostream>
#include<cstdio>
using namespace std;
struct student
{
int admno;
char name[20];
char group[10];
float fee;
};
int main()
{
student s1;
cout<<”Enter admissionno:”;
cin>>s1.admno;
cout<<”Enter student name:”;
gets(s1.name);
cout<<”Enter group:”;
gets(s1.group);
cout<<”Enter fee:”;
cin>>s1.fee;
cout<<s1.admno<<” “<<s1.name<<” “<<s1.group<<” “ <<s1.fee;
return 0;
}
Note: A structure can be defined within or outside the main().If it is outside its scope
is global.otherwise local to main()
Array of structure
consider the statement
student s[10];
here s is a student array can contain the details of 10 students.
Nested structure
If a structure contains another structure type data as its element such a structure
is called a nested structure.
or struct date
{
int dd,mm,yy;
};
struct student
{
int admno;
char name[20];
date dtadm;
float fee;
};
Here student is a nested structure as it contains another structure type element dtadm
which is of type date.
cout<<s.admno<<s.name<<s.dtadm.dd<<s.dtadm.mm<<s.dtadm.yy<<s.fee;