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.

In this article, we will store and display information of an employee using a structure. An example of a structure is as follows:

struct employee {
   int empID;
   char name[50];
   int salary;
   char department[50];
};

Store Information in Structure and Display It

In this program, we store and display employee information using a structure. Here's how we did it:

  • First, we defined a structure called employee.
  • This structure contains four members: empID (integer) for the employee's ID, name (character array) for the employee's name, salary (integer) for the employee's salary, and department (character array) for the employee's department.
  • Next, we created an array of employee structures and initialized it with predefined values.
  • Finally, we used a for loop to access and display the information of each employee.

C++ Program to Store and Display Information Using Structure

Here's the C++ program where we use a structure to stoer and display employee details like ID, name, salary and department.

#include <iostream>
using namespace std;

// Structure for employee details
struct employee {
   int empID;          // Employee ID
   char name[50];      // Employee name
   int salary;         // Employee salary
   char department[50]; // Employee department
};

int main() {
   // Create an array of 3 employees with their details
   struct employee emp[3] = {
      { 1 , "Harry" , 20000 , "Finance" },
      { 2 , "Sally" , 50000 , "HR" },
      { 3 , "John" , 15000 , "Technical" }
   };

   // Print employee details
   cout << "Employee information:" << endl;
   
   // Loop to print each employee's info
   for(int i = 0; i < 3; i++) {
      cout << "Employee ID: " << emp[i].empID << endl;       // Print ID
      cout << "Name: " << emp[i].name << endl;               // Print name
      cout << "Salary: " << emp[i].salary << endl;           // Print salary
      cout << "Department: " << emp[i].department << endl;   // Print department
      cout << endl;  // Print a blank line after each employee
   }

   return 0;  // End of program
}

The output of the program displays the details of three employees including their ID, name, salary, and department.

Employee information:
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
Updated on: 2025-05-16T19:14:01+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements