In C++, the structure is a user-defined data type. When you want to use different data types in a single unit then structure is used. It is declared by the key word struct.
A structure in c++ is different form the Class data type. In class all the variables are private by default while in the structure all the variables are always public. There is no concept of private or public in a structure data type.
//program to declare and initialize a structure.
//program to declare and initialize a structure.
struct student
{
int roll,
float marks;
};
int main()
{
struct student e1;
e1.roll = 5;
e1.marks = 39;
//accessing the values thru the variables
cout<< "roll: " << e1.name <<endl;
cout<< "marks : " << e1.age <<endl;
}
//program to declare a structure and input the values thru variables.
struct student
{
int roll;
float marks;
};
int main()
{
struct student e;
cout<<" enter your roll no:";
cin>>e.roll;
cout<<" enter your marks:";
cin e.marks;
//diplay the result
cout<<"roll="<<e.roll<<endl;
cout<<"marks="<<endl;
}
//program to declare an array of structure of 5 size.
struct student
{
int roll;
float marks;
};
int main()
{
struct student e[5];
for(int i=0;i<5;i++)
{
cout<<" enter your roll no:";
cin>>e[i].roll;
cout<<" enter your marks:";
cin e[i].marks;
}
//diplay the result
for(int i=0;i<5;i++)
{
cout<<" your roll no: ";
cout<<e[i].roll;
cout<<" your marks: ";
cout<<e[i].marks;
cout<<endl;
}
}
// In above programs kindly include header files.