A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword.
An example of a structure is as follows.
struct employee {
int empID;
char name[50];
float salary;
};A program that stores student information in a structure is given as follows.
Example
#include <iostream>
using namespace std;
struct student {
int rollNo;
char name[50];
float marks;
char grade;
};
int main() {
struct student s = { 12 , "Harry" , 90 , 'A' };
cout<<"The student information is given as follows:"<<endl;
cout<<endl;
cout<<"Roll Number: "<<s.rollNo<<endl;
cout<<"Name: "<<s.name<<endl;
cout<<"Marks: "<<s.marks<<endl;
cout<<"Grade: "<<s.grade<<endl;
return 0;
}Output
The student information is given as follows: Roll Number: 12 Name: Harry Marks: 90 Grade: A
In the above program, the structure is defined before the main() function. The structure contains the roll number, name, marks and grade of a student. This is demonstrated in the following code snippet.
struct student {
int rollNo;
char name[50];
float marks;
char grade;
};In the main() function, an object of type struct student is defined. This contains the roll number, name, marks and grade values. This is shown as follows.
struct student s = { 12 , "Harry" , 90 , 'A' };The structure values are displayed in the following manner.
cout<<"The student information is given as follows:"<<endl; cout<<endl; cout<<"Roll Number: "<<s.rollNo<<endl; cout<<"Name: "<<s.name<<endl; cout<<"Marks: "<<s.marks<<endl; cout<<"Grade: "<<s.grade<<endl;