
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Store and Display Information Using Structure in C++
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 and displays information using structure is given as follows.
Example
#include <iostream> using namespace std; struct employee { int empID; char name[50]; int salary; char department[50]; }; int main() { struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } }; cout<<"The employee information is given as follows:"<<endl; cout<<endl; for(int i=0; i<3;i++) { cout<<"Employee ID: "<<emp[i].empID<<endl; cout<<"Name: "<<emp[i].name<<endl; cout<<"Salary: "<<emp[i].salary<<endl; cout<<"Department: "<<emp[i].department<<endl; cout<<endl; } return 0; }
Output
The employee information is given as follows: Employee ID: 1 Name: Harry Salary: 20000 Department: Finance Employee ID: 2 Name: Sally Salary: 50000 Department: HR Employee ID: 3 Name: John Salary: 15000 Department: Technical
In the above program, the structure is defined before the main() function. The structure contains the employee ID, name, salary and department of an employee. This is demonstrated in the following code snippet.
struct employee { int empID; char name[50]; int salary; char department[50]; };
In the main() function, an object array of type struct employee is defined. This contains the employee ID, name, salary and department values. This is shown as follows.
struct employee emp[3] = { { 1 , "Harry" , 20000 , "Finance" } , { 2 , "Sally" , 50000 , "HR" } , { 3 , "John" , 15000 , "Technical" } };
The structure values are displayed using a for loop. This is shown in the following manner.
cout<<"The employee information is given as follows:"<<endl; cout<<endl; for(int i=0; i<3;i++) { cout<<"Employee ID: "<<emp[i].empID<<endl; cout<<"Name: "<<emp[i].name<<endl; cout<<"Salary: "<<emp[i].salary<<endl; cout<<"Department: "<<emp[i].department<<endl; cout<<endl; }