Structure Data type in C++ | What is a Structure datatype? | Examples (2024)

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 Booksstruct Books {char title[50];char author[50];char subject[30]; float price;int book_id;};

Browse more Topics underStructured Data Type

  • Arrays
  • One Dimensional Array
  • Two-dimensional Array
  • User-defined Data Types

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 –

 
Books B;

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 BB.title = "Creativity to the Fullest" ;// For assigning a value to the price of structure variable BB.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 –

 
EnterBookTitle:CreativeMindsEnterAuthor:CGPEnterSubject:ThrillerEnterPrice:25.99EnterBookID:1DisplayBookInformation-BookTitle:CreativeMindsAuthor:CGPSubject:ThrillerPrice:25.99BookID: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 –

 
Student1EnterStudentName:RajEnterRollNo:1EnterContactNo:987654321Student2EnterStudentName:SamEnterRollNo:2EnterContactNo:123456789Student3EnterStudentName:JohnEnterRollNo:3EnterContactNo:533168842Student4EnterStudentName:LilyEnterRollNo:4EnterContactNo:865315798DisplayStudentInformation-StudentName:RajRollNumber:1ContactNo:987654321StudentName:SamRollNumber:2ContactNo:123456789StudentName:JohnRollNumber:3ContactNo:533168842StudentName:LilyRollNumber:4ContactNo: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: 18cm 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 : 1Title : Creative MindsPrice : 9.99

FAQs onStructure 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

Structure Data type in C++ | What is a Structure datatype? | Examples (2024)
Top Articles
Satisficing: Definition, How the Strategy Works, and an Example
Readers share ideas for recycling the old encyclopedias
Skylar Vox Bra Size
Avonlea Havanese
La connexion à Mon Compte
Kristine Leahy Spouse
Mustangps.instructure
Pj Ferry Schedule
Clafi Arab
Toonily The Carry
Dusk
Purple Crip Strain Leafly
How Much Is Tj Maxx Starting Pay
Magicseaweed Capitola
Pricelinerewardsvisa Com Activate
Velocity. The Revolutionary Way to Measure in Scrum
Concordia Apartment 34 Tarkov
Canvasdiscount Black Friday Deals
Shreveport City Warrants Lookup
What Time Does Walmart Auto Center Open
Weve Got You Surrounded Meme
Reviews over Supersaver - Opiness - Spreekt uit ervaring
6 Most Trusted Pheromone perfumes of 2024 for Winning Over Women
Hctc Speed Test
Koninklijk Theater Tuschinski
Mals Crazy Crab
Milwaukee Nickname Crossword Clue
January 8 Jesus Calling
Movies - EPIC Theatres
Rs3 Bring Leela To The Tomb
Till The End Of The Moon Ep 13 Eng Sub
91 Octane Gas Prices Near Me
Motor Mounts
Taktube Irani
Utexas Baseball Schedule 2023
El agente nocturno, actores y personajes: quién es quién en la serie de Netflix The Night Agent | MAG | EL COMERCIO PERÚ
AI-Powered Free Online Flashcards for Studying | Kahoot!
USB C 3HDMI Dock UCN3278 (12 in 1)
Dying Light Nexus
Mixer grinder buying guide: Everything you need to know before choosing between a traditional and bullet mixer grinder
Gary Lezak Annual Salary
Me Tv Quizzes
Shipping Container Storage Containers 40'HCs - general for sale - by dealer - craigslist
Lady Nagant Funko Pop
Babykeilani
Centimeters to Feet conversion: cm to ft calculator
Secrets Exposed: How to Test for Mold Exposure in Your Blood!
Craiglist.nj
Fredatmcd.read.inkling.com
Electric Toothbrush Feature Crossword
Causeway Gomovies
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6146

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.