SlideShare a Scribd company logo
STRUCTURE &
UNION
Ms. Davinder Kaur
Assistant Professor
Department of Computer Applications
Chandigarh Group of Colleges, Landran
STRUCTURE
 A Structure is a collection of related data items which can be of different types held
together in a single unit.
 All the elements of structure are stored at contiguous memory locations.
 The data items enclosed within a structure are known as its members which can be
either of int, float, char etc.
Structure Declaration
 A structure declaration specifies the grouping of
variables of different types in a single unit.
 The syntax for declaring a structure in C++ is-
Example of Structure Declaration is-
struct struct_name struct student
{ {
data_type member1; int rollno;
data_type member2; char name[20];
…….. float marks;
data_type membern; };
};
Structure Definition
 The structure definition creates structure variables and allocates
storage space for them.
 The individual members of the structure variables are stored in
contiguous memory locations.
 For example-
struct student s1,s2;
Or student s1,s2;
struct student
{
int rollno;
char name[20];
float marks;
}s1,s2;
Here s1,s2 are two structure variables of type student.
Accessing Structure Members
 The members can be accessed using a dot operator(.)
or an arrow operator(->).
 The use of extraction operator(>>) and insertion
operator(<<) to input and display the members of
structure variable s1.
cin>>s1.rollno>>s1.name>>s1.marks;
cout<<s1.rollno<<s1.name<<s1.marks;
Example of Accessing members-
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
struct student
{
int rollno;
char name[20];
float marks;
};
void main()
{
struct student s1; clrscr();
cout<<"Enter roll no, name,marks"; cin>>s1.rollno>>s1.name>>s1.marks;
cout<<endl; cout<<"Roll no is:"<<s1.rollno<<endl;
cout<<"Name of student is:"<<s1.name<<endl;
cout<<"Marks are:"<<setprecision(2)<<s1.marks<<endl;
getch();
}
Structure Initialization
 A structure variable is initialized with values that are to be assigned to its members
within the braces.
Example-
struct employee
{
int emp_no;
char emp_name[20];
int dept_id;
double salary;
};
Defining and initialize structure variable emp1 of type employee as follow:
employee emp1={101,”Aman”,1125,20000};
Example of Structure Initialization
#include<iostream.h>
#include<conio.h>
struct employee
{
int emp_no;
char emp_name[20];
int emp_id;
double salary;
};
void main()
{
struct employee emp1={101,"Davinder",1125,20000};
clrscr();
cout<<"Employee Details are-"<<endl;
cout<<"Employee number is "<<emp1.emp_no<<endl;
cout<<"Employee name is "<<emp1.emp_name<<endl;
cout<<"Employee Id is "<<emp1.emp_id<<endl;
Structure Assignment
 The value of one structure variable is assigned to another
variable of same type using assignment statement. If s1 and s2
are structure variable of type student then the statement
s2=s1;
assign value of structure variable s1 to s2.
Example of Structure Assignment
#include<iostream.h>
#include<conio.h>
struct student
{
int rollno;
char name[20];
float marks;
};
void main()
{
struct student s1={101,"Simran",50.677654};
struct student s2;
clrscr();
s2=s1;
cout<<"Roll number is "<<s2.rollno<<endl;
cout<<"Name is "<<s2.name<<endl;
cout<<"Marks are "<<s2.marks<<endl;
getch();
}
Nesting of Structure (Structure
within Structure)
 When a structure contains another structure, it is
called nested structure.
 In other words, a member of a structure is a
variable of another structure. This process in
which a structure can appear within another
structure is known as nesting of structure.
Syntax for structure within
structure or nested structure
struct structure_name1
{
datatype variable_name;
datatype varaiable_name;
};
struct structure_name2
{
datatype variable_name;
datatype variable_name;
struct structure_name1 obj;
};
Example of Nesting Structure#include<iostream.h>
#include<conio.h>
struct date
{
int day;
int month;
int year;
};
struct employee
{
int emp_code;
char emp_name[20];
int dept_id;
float sal;
date doj;
};
void main()
{
employee emp1;
clrscr();
cout<<"Enter employee code, name of employee ";
cin>>emp1.emp_code>>emp1.emp_name;
cout<<"Enter dept id, salary";
cin>>emp1.dept_id>>emp1.sal;
cout<<"Enter date,month and year of joining";
cin>>emp1.doj.day>>emp1.doj.month>>emp1.doj.year;
cout<<endl;
cout<<"Displaying information of Employee is:"<<endl;
cout<<"Employee Code is:"<<emp1.emp_code<<endl;
cout<<"Name of Employee
is:"<<emp1.emp_name<<endl;
cout<<"Department id is:"<<emp1.dept_id<<endl;
cout<<"Salary is:"<<emp1.sal<<endl;
cout<<"Joining date is:"<<emp1.doj.day<<"-
"<<emp1.doj.month<<"-"<<emp1.doj.year;
getch();
}
Array of Structure
 Array of structure refers to an array in which each array
element is a structure variable of same type.
 For Example-
struct student
{
int rollno;
char name[20];
float marks;
}s[10]; //array of structure
Initialization of Array of Structure
An array of structures can be assigned some initial values just as any other build in
types.
For Example-
struct student
{
int rollno;
char name[20];
};
………….
………..
Student s[3]={101,”Aman”,
102,”Vicky”,
103,”Rishi”
};
Example of Array of Structure
#include<iostream.h>
#include<conio.h>
struct student
{
int rollno;
char name[20];
float marks;
};
void main()
{
student s[5];
int n;
clrscr();
cout<<"Enter number of students";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"Enter roll no,name, marks";
cin>>s[i].rollno>>s[i].name>>s[i].ma
rks;
}
cout<<"Displaying Students Information
"<<endl;
for(i=0;i<n;i++)
{
cout<<"Rollno is "<<s[i].rollno<<endl;
cout<<"Name is "<<s[i].name<<endl;
cout<<"Marks is "<<s[i].marks<<endl;
}
getch();
}
Structures & Functions
 Individual members of a structure can be passed to a
function as argument in the function call. This method
of passing individual member is same as that of passing
variable of any primitive type.
Example of Passing Structure to function
#include<iostream.h>
#include<conio.h>
struct employee
{
int emp_code;
char name[20];
double sal;
};
void main()
{
void display(employee);
//Function Declaration
employee emp1={101,"Ritu",12000};
clrscr();
cout<<"Details of Employee are "<<endl;
display(emp1);//Function Call
getch();
}
void display(employee e)
{
cout<<"Code of employee
is:"<<e.emp_code<<endl;
cout<<"name of Employee is
"<<e.name<<endl;
cout<<"Salary is "<<e.sal;
}
Structure With Pointers
 Like pointers to int, char and other data-types, pointers also pointing to
structures. These pointers are called structure pointers.
 Syntax is-
struct structure_name
{
data-type member-1;
data-type member-1;
data-type member-1;
data-type member-1;
};
int main()
{
struct structure_name *ptr;
}
Example of structure with pointer
#include<iostream.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
};
void main()
{
struct student s={"Raman",123};
struct student *ptr;
clrscr();
ptr=&s;
cout<<"name and roll no. of student is
"<<s.name<<"t"<<s.rollno;
cout<<"nname and roll no is "<<ptr-
>name<<"t"<<ptr->rollno;
getch();
}
Union
 A union is a user-defined data type like structure. The union
groups logically related variables into single unit.
 The union data type allocate the space equal to space need to hold
the largest data member of union.
 The union allows different types of variable to share same space in
memory.
 Syntax is-
union <union_name>
{
datatype variable_name;
datatype variable_name;
};
Example of Union
#include<iostream.h>
#include<conio.h>
#include<string.h>
union book
{
char name[20];
double price;
}bk;
void main()
{
clrscr();
strcpy(bk.name,"Communication-I");
cout<<"name of the book is
"<<bk.name<<endl;
bk.price=234;
cout<<"Price of book is "<<bk.price;
getch();
}
Difference between Structure & Union
 Structure occupies memory for all its members whereas Union will
not take memory for all its members. It will take the memory
occupied by the highest memory occupying member.
 In union, one block is used by all members of the union but in case
of structure, each member has its own memory space.
 Union is the best environment where memory is limited as it
shares the allocated memory. But structure cannot be implemented
in shared memory.
 In union, only one member can be assigned a value at a time. But
in structures, all the members can be assigned values at a time.
 In structure, value assigned to one member cannot cause change in
other members, where as in union it causes change in values of
other members.

More Related Content

What's hot

Data types in c++
Data types in c++Data types in c++
Data types in c++
Venkata.Manish Reddy
 
Structures
StructuresStructures
Structures
archikabhatia
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
Dhrumil Patel
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Deepak Singh
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
Ñirmal Tatiwal
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
Smriti Jain
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
Prem Kumar Badri
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 

What's hot (20)

Data types in c++
Data types in c++Data types in c++
Data types in c++
 
Structures
StructuresStructures
Structures
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Constructor
ConstructorConstructor
Constructor
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++Chapter 7 - Input Output Statements in C++
Chapter 7 - Input Output Statements in C++
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
 

Similar to Structure & Union in C++

Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
psaravanan1985
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
nikshaikh786
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
Vijayananda Ratnam Ch
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
GebruGetachew2
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
kavitham66441
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
sudhakargeruganti
 
03 structures
03 structures03 structures
03 structures
Rajan Gautam
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
Sheik Mohideen
 
Structures
StructuresStructures
Structures
selvapon
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
Aneeskhan326131
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structuresTAlha MAlik
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
thenmozhip8
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
Structure in c language
Structure in c languageStructure in c language
Structure in c language
sangrampatil81
 
Structure In C
Structure In CStructure In C
Structure In C
yndaravind
 
Structure c
Structure cStructure c
Structure c
thirumalaikumar3
 
Javascripting.pptx
Javascripting.pptxJavascripting.pptx
Javascripting.pptx
Vinod Srivastava
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 

Similar to Structure & Union in C++ (20)

Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdfEasy Understanding of Structure Union Typedef Enum in C Language.pdf
Easy Understanding of Structure Union Typedef Enum in C Language.pdf
 
03 structures
03 structures03 structures
03 structures
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 
Structures
StructuresStructures
Structures
 
Lab 13
Lab 13Lab 13
Lab 13
 
12Structures.pptx
12Structures.pptx12Structures.pptx
12Structures.pptx
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
Structure In C
Structure In CStructure In C
Structure In C
 
Structure c
Structure cStructure c
Structure c
 
Javascripting.pptx
Javascripting.pptxJavascripting.pptx
Javascripting.pptx
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 

Recently uploaded

Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 

Recently uploaded (20)

Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 

Structure & Union in C++

  • 1. STRUCTURE & UNION Ms. Davinder Kaur Assistant Professor Department of Computer Applications Chandigarh Group of Colleges, Landran
  • 2. STRUCTURE  A Structure is a collection of related data items which can be of different types held together in a single unit.  All the elements of structure are stored at contiguous memory locations.  The data items enclosed within a structure are known as its members which can be either of int, float, char etc.
  • 3. Structure Declaration  A structure declaration specifies the grouping of variables of different types in a single unit.  The syntax for declaring a structure in C++ is- Example of Structure Declaration is- struct struct_name struct student { { data_type member1; int rollno; data_type member2; char name[20]; …….. float marks; data_type membern; }; };
  • 4. Structure Definition  The structure definition creates structure variables and allocates storage space for them.  The individual members of the structure variables are stored in contiguous memory locations.  For example- struct student s1,s2; Or student s1,s2; struct student { int rollno; char name[20]; float marks; }s1,s2; Here s1,s2 are two structure variables of type student.
  • 5. Accessing Structure Members  The members can be accessed using a dot operator(.) or an arrow operator(->).  The use of extraction operator(>>) and insertion operator(<<) to input and display the members of structure variable s1. cin>>s1.rollno>>s1.name>>s1.marks; cout<<s1.rollno<<s1.name<<s1.marks;
  • 6. Example of Accessing members- #include<iostream.h> #include<conio.h> #include<iomanip.h> struct student { int rollno; char name[20]; float marks; }; void main() { struct student s1; clrscr(); cout<<"Enter roll no, name,marks"; cin>>s1.rollno>>s1.name>>s1.marks; cout<<endl; cout<<"Roll no is:"<<s1.rollno<<endl; cout<<"Name of student is:"<<s1.name<<endl; cout<<"Marks are:"<<setprecision(2)<<s1.marks<<endl; getch(); }
  • 7. Structure Initialization  A structure variable is initialized with values that are to be assigned to its members within the braces. Example- struct employee { int emp_no; char emp_name[20]; int dept_id; double salary; }; Defining and initialize structure variable emp1 of type employee as follow: employee emp1={101,”Aman”,1125,20000};
  • 8. Example of Structure Initialization #include<iostream.h> #include<conio.h> struct employee { int emp_no; char emp_name[20]; int emp_id; double salary; }; void main() { struct employee emp1={101,"Davinder",1125,20000}; clrscr(); cout<<"Employee Details are-"<<endl; cout<<"Employee number is "<<emp1.emp_no<<endl; cout<<"Employee name is "<<emp1.emp_name<<endl; cout<<"Employee Id is "<<emp1.emp_id<<endl;
  • 9. Structure Assignment  The value of one structure variable is assigned to another variable of same type using assignment statement. If s1 and s2 are structure variable of type student then the statement s2=s1; assign value of structure variable s1 to s2.
  • 10. Example of Structure Assignment #include<iostream.h> #include<conio.h> struct student { int rollno; char name[20]; float marks; }; void main() { struct student s1={101,"Simran",50.677654}; struct student s2; clrscr(); s2=s1; cout<<"Roll number is "<<s2.rollno<<endl; cout<<"Name is "<<s2.name<<endl; cout<<"Marks are "<<s2.marks<<endl; getch(); }
  • 11. Nesting of Structure (Structure within Structure)  When a structure contains another structure, it is called nested structure.  In other words, a member of a structure is a variable of another structure. This process in which a structure can appear within another structure is known as nesting of structure.
  • 12. Syntax for structure within structure or nested structure struct structure_name1 { datatype variable_name; datatype varaiable_name; }; struct structure_name2 { datatype variable_name; datatype variable_name; struct structure_name1 obj; };
  • 13. Example of Nesting Structure#include<iostream.h> #include<conio.h> struct date { int day; int month; int year; }; struct employee { int emp_code; char emp_name[20]; int dept_id; float sal; date doj; }; void main() { employee emp1; clrscr(); cout<<"Enter employee code, name of employee "; cin>>emp1.emp_code>>emp1.emp_name; cout<<"Enter dept id, salary"; cin>>emp1.dept_id>>emp1.sal; cout<<"Enter date,month and year of joining"; cin>>emp1.doj.day>>emp1.doj.month>>emp1.doj.year; cout<<endl; cout<<"Displaying information of Employee is:"<<endl; cout<<"Employee Code is:"<<emp1.emp_code<<endl; cout<<"Name of Employee is:"<<emp1.emp_name<<endl; cout<<"Department id is:"<<emp1.dept_id<<endl; cout<<"Salary is:"<<emp1.sal<<endl; cout<<"Joining date is:"<<emp1.doj.day<<"- "<<emp1.doj.month<<"-"<<emp1.doj.year; getch(); }
  • 14. Array of Structure  Array of structure refers to an array in which each array element is a structure variable of same type.  For Example- struct student { int rollno; char name[20]; float marks; }s[10]; //array of structure
  • 15. Initialization of Array of Structure An array of structures can be assigned some initial values just as any other build in types. For Example- struct student { int rollno; char name[20]; }; …………. ……….. Student s[3]={101,”Aman”, 102,”Vicky”, 103,”Rishi” };
  • 16. Example of Array of Structure #include<iostream.h> #include<conio.h> struct student { int rollno; char name[20]; float marks; }; void main() { student s[5]; int n; clrscr(); cout<<"Enter number of students"; cin>>n; for(int i=0;i<n;i++) { cout<<"Enter roll no,name, marks"; cin>>s[i].rollno>>s[i].name>>s[i].ma rks; } cout<<"Displaying Students Information "<<endl; for(i=0;i<n;i++) { cout<<"Rollno is "<<s[i].rollno<<endl; cout<<"Name is "<<s[i].name<<endl; cout<<"Marks is "<<s[i].marks<<endl; } getch(); }
  • 17. Structures & Functions  Individual members of a structure can be passed to a function as argument in the function call. This method of passing individual member is same as that of passing variable of any primitive type.
  • 18. Example of Passing Structure to function #include<iostream.h> #include<conio.h> struct employee { int emp_code; char name[20]; double sal; }; void main() { void display(employee); //Function Declaration employee emp1={101,"Ritu",12000}; clrscr(); cout<<"Details of Employee are "<<endl; display(emp1);//Function Call getch(); } void display(employee e) { cout<<"Code of employee is:"<<e.emp_code<<endl; cout<<"name of Employee is "<<e.name<<endl; cout<<"Salary is "<<e.sal; }
  • 19. Structure With Pointers  Like pointers to int, char and other data-types, pointers also pointing to structures. These pointers are called structure pointers.  Syntax is- struct structure_name { data-type member-1; data-type member-1; data-type member-1; data-type member-1; }; int main() { struct structure_name *ptr; }
  • 20. Example of structure with pointer #include<iostream.h> #include<conio.h> struct student { char name[20]; int rollno; }; void main() { struct student s={"Raman",123}; struct student *ptr; clrscr(); ptr=&s; cout<<"name and roll no. of student is "<<s.name<<"t"<<s.rollno; cout<<"nname and roll no is "<<ptr- >name<<"t"<<ptr->rollno; getch(); }
  • 21. Union  A union is a user-defined data type like structure. The union groups logically related variables into single unit.  The union data type allocate the space equal to space need to hold the largest data member of union.  The union allows different types of variable to share same space in memory.  Syntax is- union <union_name> { datatype variable_name; datatype variable_name; };
  • 22. Example of Union #include<iostream.h> #include<conio.h> #include<string.h> union book { char name[20]; double price; }bk; void main() { clrscr(); strcpy(bk.name,"Communication-I"); cout<<"name of the book is "<<bk.name<<endl; bk.price=234; cout<<"Price of book is "<<bk.price; getch(); }
  • 23. Difference between Structure & Union  Structure occupies memory for all its members whereas Union will not take memory for all its members. It will take the memory occupied by the highest memory occupying member.  In union, one block is used by all members of the union but in case of structure, each member has its own memory space.  Union is the best environment where memory is limited as it shares the allocated memory. But structure cannot be implemented in shared memory.  In union, only one member can be assigned a value at a time. But in structures, all the members can be assigned values at a time.  In structure, value assigned to one member cannot cause change in other members, where as in union it causes change in values of other members.