Website For Developers

Arrays of Structures in C++



Example of arrays of structures in C++

#include<iostream>
#include<conio.h>
using namespace std;
// structure declaration
struct employee {
  int id;
  float salary;
};

int main() {
  employee e[3] = {{1,10000}, {2,2902}, {3,9321}};

  for(int i=0; i<3; i++) {
    cout<<"Employee ID: "<<e[i].id;
    cout<<endl<<"Employee Salary: "<<e[i].salary;
    cout<<endl<<"--------------"<<endl;
  }
  getch();
  return 0;
}

Output

Employee ID: 1
Employee Salary: 10000
--------------
Employee ID: 2
Employee Salary: 2902
--------------
Employee ID: 3
Employee Salary: 9321
--------------



Example of arrays of structures for getting data

#include<iostream>
#include<conio.h>
using namespace std;
struct book {
  int id;
  int page;
  float price;
};

int main() {
  book b[3];

  for(int i=0; i<3; i++) {
    cout<<"Enter Book ID: ";
    cin>>b[i].id;
    cout<<"Enter Book Pages: ";
    cin>>b[i].page;
    cout<<"Enter Book Price: ";
    cin>>b[i].price;
    cout<<endl;
  }
  cout<<endl<<endl<<"We have following books:"<<endl<<endl;
  for(int i=0; i<3; i++){
    cout<<"Book ID: "<<b[i].id;
    cout<<endl<<"Book Pages: "<<b[i].page;
    cout<<endl<<"Book Price: "<<b[i].price;
    cout<<endl<<"____________________"<<endl;
  }
  getch();
  return 0;
}

Output

Enter Book ID: 2
Enter Book Pages: 234
Enter Book Price: 22

Enter Book ID: 324
Enter Book Pages: 456
Enter Book Price: 34

Enter Book ID: 534
Enter Book Pages: 666
Enter Book Price: 875


We have following books:


Book ID: 2

Book Pages: 234

Book Price: 22

____________________
Book ID: 324

Book Pages: 456

Book Price: 34

____________________
Book ID: 534

Book Pages: 666

Book Price: 875

____________________