Write a C++ Program to Store and Display Information Using Structure

As a C++ programmer, you may often come across a situation where you need to store and display information for different entities.

This is where the concept of structures comes into play.

A structure is a user-defined data type that groups together variables of different data types under a single name.

In this tutorial, we will learn how to use structures in C++ to store and display information.


Declaring a Structure

To declare a structure, we use the struct keyword, followed by the name of the structure and the variables that we want to group together.

For example, let’s create a structure called Person that will store the name, age, and gender of a person.

struct Person {
string name;
int age;
char gender;
};

Storing Information in a Structure

Once we have defined the structure, we can create variables of this structure type and store information in them.

For example, to store information for a person, we can create a variable of the Person structure type and use the dot operator to assign values to its member variables.

Person p1;
p1.name = "John";
p1.age = 30;
p1.gender = 'M';

Displaying Information from a Structure

To display information from a structure, we can again use the dot operator to access the member variables of the structure.

For example, to display the information for p1 that we stored above, we can use the following code.

cout << "Name: " << p1.name << endl;
cout << "Age: " << p1.age << endl;
cout << "Gender: " << p1.gender << endl;

Complete Program to Store and Display Information Using Structure

Here is a complete program that demonstrates how to use structures to store and display information for multiple persons.

#include <iostream>
#include <string>
using namespace std;

struct Person {
    string name;
    int age;
    char gender;
};

int main() {
    Person p1, p2;
    
    p1.name = "John";
    p1.age = 30;
    p1.gender = 'M';
    
    p2.name = "Jane";
    p2.age = 25;
    p2.gender = 'F';
    
    cout << "Information for Person 1:" << endl;
    cout << "Name: " << p1.name << endl;
    cout << "Age: " << p1.age << endl;
    cout << "Gender: " << p1.gender << endl;
    
    cout << endl;
    
    cout << "Information for Person 2:" << endl;
    cout << "Name: " << p2.name << endl;
    cout << "Age: " << p2.age << endl;
    cout << "Gender: " << p2.gender << endl;
    
    return 0;
}

Output:

Information for Person 1:
Name: John
Age: 30
Gender: M

Information for Person 2:
Name: Jane
Age: 25
Gender: F


Conclusion

Structures in C++ are a powerful tool for storing and organizing information for different entities.

By grouping together variables of different data types under a single name, structures make it easier to manage complex data structures.