SlideShare a Scribd company logo
1 of 6
Download to read offline
Page 1 of 6



                                 Structures
What is a Structure?

Structure is a collection of variables under a single name. Variables can be of
any type: int, float, char etc. The main difference between structure and array is
that arrays are collections of the same data type and structure is a collection of
variables under a single name.

How to declare and create a Structure

Declaring a Structure:

The structure is declared by using the keyword struct followed by structure name,
also called a tag. Then the structure members (variables) are defined with their
type and variable names inside the open and close braces { and }. Finally, the
closed braces end with a semicolon denoted as ; following the statement. The
above structure declaration is also called a Structure Specifier.

Example:

Three variables: custnum of type int, salary of type int, commission of type float
are structure members and the structure name is Customer. This structure is
declared as follows:




In the above example, it is seen that variables of different types such as int and
float   are    grouped      in   a     single   structure      name     Customer.

Arrays behave in the same way, declaring structures does not mean that memory
is allocated. Structure declaration gives a skeleton or template for the structure.

After declaring the structure, the next step is to define a structure variable.



                          Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 2 of 6


How to declare Structure Variable?

This is similar to variable declaration. For variable declaration, data type is
defined followed by variable name. For structure variable declaration, the data
type is the name of the structure followed by the structure variable name.

In the above example, structure variable cust1 is defined as:




What happens when this is defined? When structure is defined, it allocates or
reserves space in memory. The memory space allocated will be cumulative of all
defined structure members. In the above example, there are 3 structure
members: custnum, salary and commission. Of these, two are of type in and one
is of type float. If integer space allocated by a system is 2 bytes and float four
bytes the above would allo9acter 2bytes for custnum, 2 bytes for salary and 4
bytes for commission.

How to access structure members in C++?

To access structure members, the operator used is the dot operator denoted by
(.). The dot operator for accessing structure members is used thusly:


structure variable name.member name

For example:

A programmer wants to assign 2000 for the structure member salary in the above
example of structure Customer with structure variable cust1 this is written as:

Nested Structures
A structure can be nested inside another structure.

Stuct addr
{
int houseno;
char area[26];

                        Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 3 of 6

char city[26];
char state[26];
};

struct emp
{
int empno;
char name[26];
char desig[16];
addr address;
float basic;
};
emp worker ;

 The structure emp h as been defined having several elements including a
structure address also. The elements address(of structure emp) is itself a
structure of type addr. While defining such structures, just make sure that innder
structure one defined before outer structure one defined before outer structures.



Structure and Arrays
The structure and the array both are c++ derived data types. While arrays are
collections of analogous elements, structures assembles dissimilar elements
under one roof.

Array and structure both combined together to form complex data objects. There
may be structures contained within an array; also there array element of a
structure.

Array of Structure

To declare 100- elements array of structure of type addr

addr mem_addr[100];

To create an array having structures emp type

Emp sales_emp[100];

Above declaration to create an array sales_emp to store 100 structures of emp
type.




                        Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 4 of 6




Array Within Structures

A structure elements my be simple or complex . A complex structure may itself
be a structure or any array. When a structure elements happens to be an array it
is treated in the same way as array are treated. The only additional things to be
kept in mind is that to access it, its structure name followed by a (.) and the name
is to be given. For example consider structure ;



Struct student

       {
       Int rollno;
       char name[21];
       float marks[5]; //array of 5 floats
       };
       students learner;

The above declared statement variable learner is of structure type student that
contains an elements which is a n array of 5 floats to store marks of a students in
5 different subjects.

Passing Structures to Function
If you have a structure local to a function and you need to pass its values to
another function , then it can be achieved in two ways : (i) by passing individual
structure elements , and (ii) by passing the entire structure . Both the ways cab
be achieved by call by value as well as by call by reference method pa passing
variables.

Passing Structure Elements to Functions

When an elements of a structure is passed to a function , you are actually
passing the value of that element to the function Therefore , it just like passing a
simple variable. Consider following structure

Struct date {
                short day;
                shot month;
                short year;
                } Bdate;

`

                          Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 5 of 6

Passing entire structure to Functions

Passing entire structure makes the most sense when the structure is relatively
compact. The entire structure can be passed to the function both ways by value
and by reference. Passing by value is useful when the original values are not
to be changed and passing by reference is useful when original values are to
be changed.

User Defined Data Types

  C++ allows you to define explicitly new data type name by using the keyword
typedef doses not actually create a new data class, rather it defines a new
name for an exiting type. This can increase the potablity of a program as only the
typedef statements would have to be changed . Using typedef can also aid in
self- documenting your code by allowing ddescriptive name for the standard data
type. The syntax of the typedef statement is

Typedef type name ;

Use of typedef for declaring structures
The typedef function is used to declare the alias name for the structure type.

typedef structure result
  {
    } progress;
 results report1;
progress report2

in this above program segment the usage of typedef defines a structure result
and an alias name of the same structure as progress.

The two structures report1 and report2 are declared accordingly of the same
type as result and progress are now alternative nomenclature for each other.

Enumerated data types

It is another way of defining data types. It includes all the probables list of values
that a data type can take. It has the following format for declaration;

Enum struc-name {v1 v2 ,v3, v3,v4…..v n }




                           Prepared By Sumit Kumar Gupta, PGT Computer Science
Page 6 of 6


                      Practice Question Paper
1. What is a structure?
2. Define arrays of structures?
3. Differentiate between the following using examples
a. Simple structure
b. multiple structure
4. Explain the following with examples
a. Declaration of a structure
b. Definition of a structure variable
c. Accessing of a structure member
d. Initialization of a member within structures.
e. Arrays of structures.
f. Passing structures to functions
g. Use defined structure
6. Explain the usage of type def for declaring structure .
7.What are enumerated data type?
8. What are symbolic constants?
9. Define a structure for length and breadth of a rectangle of type float and refer
   the same as rect.

10. Write a statement to assign a variable measure to length member of rect
 structure variable.

11. The enumerated type is considered as an integer type . Comment on the
 factual concern of the statement.
12. Write a program segment to declared and initialize an array of four structure
 with name of the student age and marks in three subjects.




                         Prepared By Sumit Kumar Gupta, PGT Computer Science

More Related Content

What's hot

Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++bajiajugal
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointersSamiksha Pun
 
Branching statements
Branching statementsBranching statements
Branching statementsArunMK17
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++Vishesh Jha
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and DestructorKamal Acharya
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++Mauryasuraj98
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarSivakumar R D .
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Languagemadan reddy
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 
Structure in c
Structure in cStructure in c
Structure in cPrabhu Govind
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Strings in c++
Strings in c++Strings in c++
Strings in c++Neeru Mittal
 

What's hot (20)

Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
arrays and pointers
arrays and pointersarrays and pointers
arrays and pointers
 
Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Branching statements
Branching statementsBranching statements
Branching statements
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C string
C stringC string
C string
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
File in c
File in cFile in c
File in c
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Strings in C
Strings in CStrings in C
Strings in C
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Structure in c
Structure in cStructure in c
Structure in c
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Strings
StringsStrings
Strings
 

Similar to Structures in c++

Structures in c++
Structures in c++Structures in c++
Structures in c++Swarup Boro
 
2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++Jeff TUYISHIME
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structuresKrishna Nanda
 
Structures in c language
Structures in c languageStructures in c language
Structures in c languageTanmay Modi
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures topu93
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture topu93
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qbaSowri Rajan
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9patcha535
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.pptParinayWadhwa
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And UnionsDhrumil Patel
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and UnionsDhrumil Patel
 

Similar to Structures in c++ (20)

Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Structure & union
Structure & unionStructure & union
Structure & union
 
2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++2 lesson 2 object oriented programming in c++
2 lesson 2 object oriented programming in c++
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Programming in C
Programming in CProgramming in C
Programming in C
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Structure.pptx
Structure.pptxStructure.pptx
Structure.pptx
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
 
Unit 3
Unit 3Unit 3
Unit 3
 
Structures
StructuresStructures
Structures
 

More from Swarup Kumar Boro

More from Swarup Kumar Boro (20)

c++ program for Railway reservation
c++ program for Railway reservationc++ program for Railway reservation
c++ program for Railway reservation
 
c++ program for Canteen management
c++ program for Canteen managementc++ program for Canteen management
c++ program for Canteen management
 
Pointers
PointersPointers
Pointers
 
File handling
File handlingFile handling
File handling
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Queue
QueueQueue
Queue
 
Stack
StackStack
Stack
 
Functions
FunctionsFunctions
Functions
 
Implementation of oop concept in c++
Implementation of oop concept in c++Implementation of oop concept in c++
Implementation of oop concept in c++
 
2-D array
2-D array2-D array
2-D array
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Unit 3
Unit  3Unit  3
Unit 3
 
Computer science study material
Computer science study materialComputer science study material
Computer science study material
 
01 computer communication and networks v
01 computer communication and networks v01 computer communication and networks v
01 computer communication and networks v
 
1-D array
1-D array1-D array
1-D array
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
computer science sample papers 2
computer science sample papers 2computer science sample papers 2
computer science sample papers 2
 
computer science sample papers 3
computer science sample papers 3computer science sample papers 3
computer science sample papers 3
 
computer science sample papers 1
computer science sample papers 1computer science sample papers 1
computer science sample papers 1
 

Recently uploaded

ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 

Recently uploaded (20)

ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 

Structures in c++

  • 1. Page 1 of 6 Structures What is a Structure? Structure is a collection of variables under a single name. Variables can be of any type: int, float, char etc. The main difference between structure and array is that arrays are collections of the same data type and structure is a collection of variables under a single name. How to declare and create a Structure Declaring a Structure: The structure is declared by using the keyword struct followed by structure name, also called a tag. Then the structure members (variables) are defined with their type and variable names inside the open and close braces { and }. Finally, the closed braces end with a semicolon denoted as ; following the statement. The above structure declaration is also called a Structure Specifier. Example: Three variables: custnum of type int, salary of type int, commission of type float are structure members and the structure name is Customer. This structure is declared as follows: In the above example, it is seen that variables of different types such as int and float are grouped in a single structure name Customer. Arrays behave in the same way, declaring structures does not mean that memory is allocated. Structure declaration gives a skeleton or template for the structure. After declaring the structure, the next step is to define a structure variable. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 2. Page 2 of 6 How to declare Structure Variable? This is similar to variable declaration. For variable declaration, data type is defined followed by variable name. For structure variable declaration, the data type is the name of the structure followed by the structure variable name. In the above example, structure variable cust1 is defined as: What happens when this is defined? When structure is defined, it allocates or reserves space in memory. The memory space allocated will be cumulative of all defined structure members. In the above example, there are 3 structure members: custnum, salary and commission. Of these, two are of type in and one is of type float. If integer space allocated by a system is 2 bytes and float four bytes the above would allo9acter 2bytes for custnum, 2 bytes for salary and 4 bytes for commission. How to access structure members in C++? To access structure members, the operator used is the dot operator denoted by (.). The dot operator for accessing structure members is used thusly: structure variable name.member name For example: A programmer wants to assign 2000 for the structure member salary in the above example of structure Customer with structure variable cust1 this is written as: Nested Structures A structure can be nested inside another structure. Stuct addr { int houseno; char area[26]; Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 3. Page 3 of 6 char city[26]; char state[26]; }; struct emp { int empno; char name[26]; char desig[16]; addr address; float basic; }; emp worker ; The structure emp h as been defined having several elements including a structure address also. The elements address(of structure emp) is itself a structure of type addr. While defining such structures, just make sure that innder structure one defined before outer structure one defined before outer structures. Structure and Arrays The structure and the array both are c++ derived data types. While arrays are collections of analogous elements, structures assembles dissimilar elements under one roof. Array and structure both combined together to form complex data objects. There may be structures contained within an array; also there array element of a structure. Array of Structure To declare 100- elements array of structure of type addr addr mem_addr[100]; To create an array having structures emp type Emp sales_emp[100]; Above declaration to create an array sales_emp to store 100 structures of emp type. Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 4. Page 4 of 6 Array Within Structures A structure elements my be simple or complex . A complex structure may itself be a structure or any array. When a structure elements happens to be an array it is treated in the same way as array are treated. The only additional things to be kept in mind is that to access it, its structure name followed by a (.) and the name is to be given. For example consider structure ; Struct student { Int rollno; char name[21]; float marks[5]; //array of 5 floats }; students learner; The above declared statement variable learner is of structure type student that contains an elements which is a n array of 5 floats to store marks of a students in 5 different subjects. Passing Structures to Function If you have a structure local to a function and you need to pass its values to another function , then it can be achieved in two ways : (i) by passing individual structure elements , and (ii) by passing the entire structure . Both the ways cab be achieved by call by value as well as by call by reference method pa passing variables. Passing Structure Elements to Functions When an elements of a structure is passed to a function , you are actually passing the value of that element to the function Therefore , it just like passing a simple variable. Consider following structure Struct date { short day; shot month; short year; } Bdate; ` Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 5. Page 5 of 6 Passing entire structure to Functions Passing entire structure makes the most sense when the structure is relatively compact. The entire structure can be passed to the function both ways by value and by reference. Passing by value is useful when the original values are not to be changed and passing by reference is useful when original values are to be changed. User Defined Data Types C++ allows you to define explicitly new data type name by using the keyword typedef doses not actually create a new data class, rather it defines a new name for an exiting type. This can increase the potablity of a program as only the typedef statements would have to be changed . Using typedef can also aid in self- documenting your code by allowing ddescriptive name for the standard data type. The syntax of the typedef statement is Typedef type name ; Use of typedef for declaring structures The typedef function is used to declare the alias name for the structure type. typedef structure result { } progress; results report1; progress report2 in this above program segment the usage of typedef defines a structure result and an alias name of the same structure as progress. The two structures report1 and report2 are declared accordingly of the same type as result and progress are now alternative nomenclature for each other. Enumerated data types It is another way of defining data types. It includes all the probables list of values that a data type can take. It has the following format for declaration; Enum struc-name {v1 v2 ,v3, v3,v4…..v n } Prepared By Sumit Kumar Gupta, PGT Computer Science
  • 6. Page 6 of 6 Practice Question Paper 1. What is a structure? 2. Define arrays of structures? 3. Differentiate between the following using examples a. Simple structure b. multiple structure 4. Explain the following with examples a. Declaration of a structure b. Definition of a structure variable c. Accessing of a structure member d. Initialization of a member within structures. e. Arrays of structures. f. Passing structures to functions g. Use defined structure 6. Explain the usage of type def for declaring structure . 7.What are enumerated data type? 8. What are symbolic constants? 9. Define a structure for length and breadth of a rectangle of type float and refer the same as rect. 10. Write a statement to assign a variable measure to length member of rect structure variable. 11. The enumerated type is considered as an integer type . Comment on the factual concern of the statement. 12. Write a program segment to declared and initialize an array of four structure with name of the student age and marks in three subjects. Prepared By Sumit Kumar Gupta, PGT Computer Science