Structured Data Type

Structure Datatype in C++

Various Built-in Data types allow a programmer to store data elements that are of similar types. For example, the Integer data type allows us to store only non-decimal numerical values, the Character data type allows us to store single characters in the variable, etc. But what if we want to store a variety of data that are of different types? For this purpose, programming languages allow the user to create a User-defined Data type. These User-Defined data types store values of similar or different types. One such User-defined Data type is the Structure Data type. Let us learn more about this data type in the following article.

Definition

  • A Structure is a user-defined data type in C/C++ that is used to store similar, different data types or a combination of both under a single variable.
  • Unlike Array, a Structure is used to store a collection of different types of data elements under a single variable name.

Structure Data type

There often arises a need where a user wants to store data that are of similar or different data types under one variable. For example, a Data entry system in a school might need to store various types of information regarding their students such as Student Name, Address, Mobile Number, Roll Number, Class, Division, Age, etc. In order to store such a wide variety of data types under one single variable, we use the Structure Data type.

The structure is a user-defined data type that stores data elements of similar or different types and different lengths. Structures are used to represent a record of various other data elements.

Structure Syntax

In order to create a structure data type, we use the ‘struct’ keyword. The general syntax of the structure is shown below.

Syntax

                    

struct structure_name
{
        member data_type1   member_name1 ;
        .
        .
        .
        member data_typeN   member_nameN;
} ;

Note – End the struct declaration with a semi-colon(;)

Example

                    

// To create a structure for variable Books
struct Books {
      char title[50];
      char author[50];
      char subject[30];
      float price;
      int book_id;
};

Browse more Topics under Structured Data Type

Defining a Structure Variable

Once we declare the structure data type, the work is not done. Only a blueprint is created, no memory is allocated to it. In order to allocate the required memory to the structure and use it in the program, we need to define a structure variable.

Considering the above example –

Here, we created a structure variable or a structure instance B for the declared structure Books.

Accessing Members of a Structure

If we want to access the members of the structure variable, we need to use the dot(.) operator. For example, if we want to access the ‘title’ member of the structure variable B which we defined before and assign a value to it, then we would do it using the following method –

                    

// For assigning a value to the title of structure variable B

B.title = "Creativity to the Fullest" ;

// For assigning a value to the price of structure variable B

B.price = 250.99 ;

We can also initialize the values for each data member by using the following method –

                    

int main()
{
    // For every data member declared, we will assign a value in the list as per the order of declaration

    struct Books B1 = {"Creative Minds", "CGP", "Thriller", 25.99, 1};
}

Note – We cannot initialize structure values in the structure itself.

Simple C++ Structure Program

C++ Program to assign data to members of a structure variable and display it.

                    

#include 
using namespace std;

struct Books    // Create structure Books
{
    char title[50];
    char author[50];
    char subj[30];
    float price;
    int book_id;
};

int main()
{
    Books B1;   // Create structure instance B1

    cout << "Enter Book Title: ";
    cin.get(B1.title, 50);

    cout << "Enter Author: ";
    cin >> B1.author;

    cout << "Enter Subject: ";
    cin >> B1.subj;

    cout << "Enter Price: ";
    cin >> B1.price;

    cout << "Enter Book ID: ";
    cin >> B1.book_id;

    cout << "\nDisplay Book Information -" << endl;
    cout << "Book Title: " << B1.title << endl;
    cout << "Author: " << B1.author << endl;
    cout << "Subject: " << B1.subj << endl;
    cout << "Price: " << B1.price << endl;
    cout << "Book ID: " << B1.book_id << endl;
    return 0;
}

Output –

                    

Enter Book Title: Creative Minds
Enter Author: CGP
Enter Subject: Thriller
Enter Price: 25.99
Enter Book ID: 1

Display Book Information -

Book Title: Creative Minds
Author: CGP
Subject: Thriller
Price: 25.99
Book ID: 1

Array of Structures

Instead of creating one instance every time to store values in the structure, we can create an array of structures. When we create an instance, we define an array instead of a simple name. This is useful when, if we want to store the records of a large number of data. For example, to store data of 100 children, store 1000s of book data in a library, etc.

Example –

                    

#include 
using namespace std;

struct Student 
{
    char name[50];
    int roll_No;
    int contact;
};

int main()
{
    struct Student stud[4];    // Created an Array of Structure which will hold 4 sets of values  

    for(int i = 0; i < 4 ;i++)
    {
        cout << "Student " << i + 1 << endl;
        cout << "Enter Student Name: ";
        cin >> stud[i].name;

        cout << "Enter Roll No: ";
        cin >> stud[i].roll_No;

        cout << "Enter Contact No: ";
        cin >> stud[i].contact;
    }

    cout << "\nDisplay Student Information -" << endl;
    for(int i = 0; i < 4 ;i++)
    {
        cout << "Student Name: " << stud[i].name << endl;
        cout << "Roll Number: " << stud[i].roll_No << endl;
        cout << "Contact No: " << stud[i].contact << endl;
    }
    return 0;
}

Output –

                    

Student 1
Enter Student Name: Raj
Enter Roll No: 1
Enter Contact No: 987654321

Student 2
Enter Student Name: Sam
Enter Roll No: 2
Enter Contact No: 123456789

Student 3
Enter Student Name: John
Enter Roll No: 3
Enter Contact No: 533168842

Student 4
Enter Student Name: Lily
Enter Roll No: 4
Enter Contact No: 865315798

Display Student Information -
Student Name: Raj
Roll Number: 1
Contact No: 987654321

Student Name: Sam
Roll Number: 2
Contact No: 123456789

Student Name: John
Roll Number: 3
Contact No: 533168842

Student Name: Lily
Roll Number: 4
Contact No: 865315798

Passing Structure to a Function

There are 2 methods by which we can pass Structure through a function in our program.

  1. Passing by Value
  2. Passing by Reference

1. Passing by Value/Call by value –

In this method, we pass the structure variables as an agreement to the function.

Example –

                    

#include <bits/stdc++.h>
using namespace std;

struct Distance {
         int meter;
         int cm;
};

void TotalDistance(Distance d1, Distance d2)
{
            // Creating a new instance of the structure
            Distance d;
            d.meter = d1.meter + d2.meter + (d1.cm + d2.cm)/100;
            d.cm = (d1.cm + d2.cm);
            cout << "Total Distance in Meter: " << d.meter << endl;
            cout << "cm total: " << d.cm << endl;
}

void initializeFunction()
{
            // Creating two instances of Distance
            Distance Distance1, Distance2;
            Distance1.meter = 5;
            Distance1.cm = 100;

            Distance2.meter = 10;
            Distance2.cm = 200;
            
            // Passing structure instances as parameters in function
            TotalDistance(Distance1, Distance2);
}

int main()
{
            // Calling function to do the required task
            initializeFunction();
            return 0;
}

Output –

                    

Total Distance in Meter: 18
cm total: 300

2. Passing by Reference/Call by reference –

In this method, we pass the address of the structure variable to the function. For the below example, while declaring the function ‘display’ we pass the pointer of the structure variable b in its parameter. We access the members of the pointer using -> sign.

                    

#include 
#include 
using namespace std;

struct Book
{
        int book_id;
        string title;
        float price;
};

void display(struct Book *bk)
{
          cout << "Book ID : " << bk -> book_id << endl;
          cout << "Title : " << bk -> title << endl;
          cout << "Price : " << bk -> price << endl;
}

int main()
{
         Book b;

         b.book_id = 1;
         b.title = "Creative Minds";
         b.price = 9.99;
         display(&b);
         return 0;
}

Output –

                    

Book ID : 1

Title : Creative Minds

Price : 9.99

FAQs on Structure Datatype in C++

Q1. Data elements in Structure are also known as?

  1. Objects
  2. Classes
  3. Members
  4. None of the above

Answer. Option C

Q2. What happens when a structure is declared?

  1. Memory is allocated to it.
  2. Memory is not allocated to it.
  3. The structure is declared and initialized
  4. Structure is ready to use

Answer. Option B

Q3. What will be the code to assign a value to Salary member of Employee[10]?

  1. Employee[10]->Salary = 1000;
  2. Employee[10].Salary = 1000;
  3. Salary = 1000;
  4. Employee[10] = 1000;

Answer. Option B

Q4. Which of the following is a properly declared structure?

  1. struct {int id}
  2. struct {int id};
  3. struct Number {int id};
  4. struct Number [int id]

Answer. Option C

Q5. What will be the output of the following code?

                    

#include 
using namespace std;

struct Shoe {
     string brand;
     int size;
     float price;
};

int main()
{
     Shoe s1;

     s1.brand = "Nike";
     s1.size = 9;
     s1.price = 9.99;

     cout << s1.brand << endl;
     cout << s1.size << endl;
     cout << "$" << s1.price << endl;
     return 0;
}

A. Nike

9

$9.99

B. Nike

9

9.99

C. Compile time error

D. None of the above

Answer. Option A

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.