SlideShare a Scribd company logo
1 of 37
MODULE 5:STRUCTURE
AND UNION
CO4:Demonstrate
the use of arrays,
strings and
structures in C
language.
CONTENTS
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
NEED FOR STRUCTURE
Suppose, you want to store information about a person: his/her
name, citizenship number, and salary.
You can create different variables name, citNo and salary to
store this information.
What if you need to store information of more than one person?
Now, you need to create different variables for each information
per person: name1, citNo1, salary1, name2, citNo2, salary2,
etc.
A better approach would be to have a collection of all related
information under a single name Person structure and use it for
every person.
STRUCTURE
A structure is a user-defined data type available in C that allows to
combining data items of different kinds. Structures are used to
represent a record.
Defining a structure: To define a structure, you must use the struct
statement. The struct statement defines a new data type, with more
than or equal to one member. The format of the struct statement is
as follows:
struct [structure name]
{
member definition;
member definition;
...
member definition;
};
STRUCTURE
Example
struct employee
{
char name[50];
int empno;
float salary;
};
DECLARING STRUCTURE VARIABLE
You can declare structure variable in two ways:-
1. By struct keyword within main() function
2. By declaring variable at the time of defining structure.
DECLARING STRUCTURE VARIABLE
When a struct type is declared, no storage or memory is
allocated. To allocate memory of a given structure type
and work with it, we need to create variables.
struct employee
{
char name[50];
int id;
float salary;
};
int main()
{
struct employee e1, e2, e[20];
return 0;
}
DECLARING STRUCTURE VARIABLE
struct employee
{
char name[50];
int id;
float salary;
} e1, e2, e[20];
In both cases, two variables e1, e2, and an array variable e
having 20 elements of type struct employee are created.
DECLARING STRUCTURE VARIABLE
#include <stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[60];
}s1; //declaring s1 variable for structure
void main( )
{ //store first employee information
s1.rollno=1;
strcpy(s1.name, “nikhat”);//copying string into char array
//printing first employee information
printf( "Rollno : %dn", s1.rollno);
printf( "Name : %sn", s1.name);
}
ACCESS MEMBERS OF A
STRUCTURE
There are two types of operators used for accessing members of a
structure.
. Member operator
-> Structure pointer operator (to access the members of the
structure
that being referenced using pointer)
Suppose, you want to access the salary of e2 (Using member
operator)
e2.salary
To access the members of the structure referenced using the
pointer we use the operator “->”.This operator is called as arrow
operator. Using this we can access all the members of the
structure and we can further do all operations on them.
s->age=18;
KEYWORD typedef
We use the typedef keyword to create an alias name for data
types. It is commonly used with structures to simplify the
syntax of declaring variables.
struct distance
{
int feet;
float inch;
};
int main()
{
struct distance d1, d2;
}
Keyword typedef
typedef struct distance
{
int feet;
float inch;
} distance;
int main()
{
distance d1, d2;
}
NESTED STRUCTURES
C provides us the feature of nesting one structure within another
structure by using which, complex data types are created.
For example, we may need to store the address of an entity employee
in a structure. The attribute address may also have the subparts as
street number, city, state, and pin code.
Hence, to store the address of the employee, we need to store the
address of the employee into a separate structure and nest the
structure address into the structure employee.
NESTED STRUCTURES
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
NESTED STRUCTURES
void main ()
{
struct employee emp;
printf("Enter employee information?n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.a
dd.phone);
printf("Printing the employee informationn");
printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,e
mp.add.city,emp.add.pin,emp.add.phone);
}
NESTED STRUCTURES
The structure can be nested in the following ways.
1. By separate structure
2. By Embedded structure
NESTED STRUCTURES
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main
structure as a member. Consider the following example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
doj (date of joining) is the variable of type Date. Here doj is used as a member in
Employee structure. In this way, we can use Date structure in many structures.
NESTED STRUCTURES
2) Embedded structure
The embedded structure enables us to declare the structure inside the
structure. Hence, it requires less line of codes but it can not be used in
multiple data structures.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
ACCESSING NESTED STRUCTURE
We can access the member of the nested structure by Outer Structure
variable. Inner Structure variable .member of inner structure
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
ACCESSING NESTED STRUCTURE
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
ACCESSING NESTED STRUCTURE
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, “Nikhat");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %dn", e1.id);
printf( "employee name : %sn", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%dn", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}
ARRAY OF STRUCTURES
An array of structures can be defined as the collection of
multiple structures variables where each variable contains
information about different entities.
The array of structures in C are used to store information about
multiple entities of different data types.
The array of structures is also known as the collection of
structures.
To declare an array of structure, first the structure must be
defined and then an array variable of that type should be
defined.
For Example − struct book b[10]; //10 elements in an array of
structures of type ‘book’
ARRAY OF STRUCTURES
INITIALIZING ARRAY OF
STRUCTURES
struct car
{
char make[20];
char model[30];
int year;
};
struct car arrcar[2] = {
{"Audi", "TT", 2016},
{"Bentley", "Azure", 2002}
};
ARRAY OF STRUCTURES
Consider a case, where we need to store the data of 5 students.
We can store it by using the structure
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
ARRAY OF STRUCTURES
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("nEnter Name:");
scanf("%s",&st[i].name);
}
printf("nStudent Information List:");
for(i=0;i<5;i++){
printf("nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
PASSING STRUCTURE TO
FUNCTION
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void display(struct employee);
PASSING STRUCTURE TO
FUNCTION
void main ()
{
struct employee emp;
printf("Enter employee information?n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.pho
ne);
display(emp);
}
void display(struct employee emp)
{
printf("Printing the details....n");
printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
UNION
Union also stores the elements of different types i.e
heterogeneous elements. The union keyword is used to define
structure. Union takes the memory of largest member only so
occupies less memory than structures.
Structures allocate enough space to store all their members,
whereas unions can only hold one member value at a time.
We use the union keyword to define union.
union car
{
char name[50];
int price;
};
CREATE UNION VARIABLES
When a union is defined, it creates a user-defined type. However, no memory is
allocated. To allocate memory for a given union type and work with it, we need to
create variables.
1. Inside main function
union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2, *car3;
return 0;
}
CREATE UNION VARIABLES
2. During declaration
union car
{
char name[50];
int price;
} car1, car2, *car3;
In both cases, union variables car1, car2, and a union pointer
car3 of union car type are created.
ACCESS MEMBERS OF A UNION
We use the . operator to access members of a union.
To access pointer variables, we use the -> operator.
In the above example,
•To access price for car1, car1.price is used.
•To access price using car3, either (*car3).price or car3->price
can be used.
ACCESS MEMBERS OF A UNION
#include <stdio.h>
union Job
{
float salary;
int workerNo;
} j;
int main()
{
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1fn", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
SIMILARITIES BETWEEN
STRUCTURE AND UNION
1. Both are user-defined data types used to store data of different
types as a single unit.
2. Their members can be objects of any type, including other
structures and unions or arrays. A member can also consist of a bit
field.
3. Both structures and unions support only assignment = and sizeof
operators. The two structures or unions in the assignment must
have the same members and member types.
4. A structure or a union can be passed by value to functions and
returned by value by functions. The argument must have the same
type as the function parameter. A structure or union is passed by
value just like a scalar variable as a corresponding parameter.
5. ‘.’ operator is used for accessing members.
DIFFERENCE BETWEEN UNIONS
AND STRUCTURES
#include <stdio.h>
union unionJob
{ //defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{ printf("size of union = %d bytes", sizeof(uJob));
printf("nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
DIFFERENCE BETWEEN
STRUCTURES AND UNIONS
size of union = 32
size of structure = 40
Here, the size of sJob is 40 bytes because
•the size of name[32] is 32 bytes
•the size of salary is 4 bytes
•the size of workerNo is 4 bytes
However, the size of uJob is 32 bytes. It's because the size of a
union variable will always be the size of its largest element. In
the above example, the size of its largest element, (name[32]),
is 32 bytes.
With a union, all members share the same memory.
DIFFERENCE BETWEEN
STRUCTURES AND UNIONS

More Related Content

What's hot (20)

Functions in c
Functions in cFunctions in c
Functions in c
 
Array in C
Array in CArray in C
Array in C
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D array
 
Structure and union
Structure and unionStructure and union
Structure and union
 
Array in c language
Array in c languageArray in c language
Array in c language
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Unions in c
Unions in cUnions in c
Unions in c
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Unit 9. Structure and Unions
Unit 9. Structure and UnionsUnit 9. Structure and Unions
Unit 9. Structure and Unions
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Inline function
Inline functionInline function
Inline function
 
Typecasting in c
Typecasting in cTypecasting in c
Typecasting in c
 
Array in c#
Array in c#Array in c#
Array in c#
 
File handling in c
File handling in cFile handling in c
File handling in c
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Enums in c
Enums in cEnums in c
Enums in c
 

Similar to Module 5-Structure and Union

Similar to Module 5-Structure and Union (20)

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
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
Structures
StructuresStructures
Structures
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING
 
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
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
Oop lec 3(structures)
Oop lec 3(structures)Oop lec 3(structures)
Oop lec 3(structures)
 
Structures
StructuresStructures
Structures
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Structures
StructuresStructures
Structures
 
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
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
 
structure and union
structure and unionstructure and union
structure and union
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
 
Structures
StructuresStructures
Structures
 
Lab 13
Lab 13Lab 13
Lab 13
 
STRUCTURES_UNION.pptx
STRUCTURES_UNION.pptxSTRUCTURES_UNION.pptx
STRUCTURES_UNION.pptx
 
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.3 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.3 pointer, structure ,union and intro to file handling
 

More from nikshaikh786

Module 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptxModule 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptxnikshaikh786
 
Module 1_ Introduction.pptx
Module 1_ Introduction.pptxModule 1_ Introduction.pptx
Module 1_ Introduction.pptxnikshaikh786
 
Module 1_ Introduction to Mobile Computing.pptx
Module 1_  Introduction to Mobile Computing.pptxModule 1_  Introduction to Mobile Computing.pptx
Module 1_ Introduction to Mobile Computing.pptxnikshaikh786
 
Module 2_ GSM Mobile services.pptx
Module 2_  GSM Mobile services.pptxModule 2_  GSM Mobile services.pptx
Module 2_ GSM Mobile services.pptxnikshaikh786
 
MODULE 4_ CLUSTERING.pptx
MODULE 4_ CLUSTERING.pptxMODULE 4_ CLUSTERING.pptx
MODULE 4_ CLUSTERING.pptxnikshaikh786
 
MODULE 5 _ Mining frequent patterns and associations.pptx
MODULE 5 _ Mining frequent patterns and associations.pptxMODULE 5 _ Mining frequent patterns and associations.pptx
MODULE 5 _ Mining frequent patterns and associations.pptxnikshaikh786
 
Module 3_ Classification.pptx
Module 3_ Classification.pptxModule 3_ Classification.pptx
Module 3_ Classification.pptxnikshaikh786
 
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...nikshaikh786
 
Module 1_Data Warehousing Fundamentals.pptx
Module 1_Data Warehousing Fundamentals.pptxModule 1_Data Warehousing Fundamentals.pptx
Module 1_Data Warehousing Fundamentals.pptxnikshaikh786
 
Module 2_ Cyber offenses & Cybercrime.pptx
Module 2_ Cyber offenses & Cybercrime.pptxModule 2_ Cyber offenses & Cybercrime.pptx
Module 2_ Cyber offenses & Cybercrime.pptxnikshaikh786
 
Module 1- Introduction to Cybercrime.pptx
Module 1- Introduction to Cybercrime.pptxModule 1- Introduction to Cybercrime.pptx
Module 1- Introduction to Cybercrime.pptxnikshaikh786
 
MODULE 5- EDA.pptx
MODULE 5- EDA.pptxMODULE 5- EDA.pptx
MODULE 5- EDA.pptxnikshaikh786
 
MODULE 4-Text Analytics.pptx
MODULE 4-Text Analytics.pptxMODULE 4-Text Analytics.pptx
MODULE 4-Text Analytics.pptxnikshaikh786
 
Module 3 - Time Series.pptx
Module 3 - Time Series.pptxModule 3 - Time Series.pptx
Module 3 - Time Series.pptxnikshaikh786
 
Module 2_ Regression Models..pptx
Module 2_ Regression Models..pptxModule 2_ Regression Models..pptx
Module 2_ Regression Models..pptxnikshaikh786
 
MODULE 1_Introduction to Data analytics and life cycle..pptx
MODULE 1_Introduction to Data analytics and life cycle..pptxMODULE 1_Introduction to Data analytics and life cycle..pptx
MODULE 1_Introduction to Data analytics and life cycle..pptxnikshaikh786
 
MAD&PWA VIVA QUESTIONS.pdf
MAD&PWA VIVA QUESTIONS.pdfMAD&PWA VIVA QUESTIONS.pdf
MAD&PWA VIVA QUESTIONS.pdfnikshaikh786
 

More from nikshaikh786 (20)

Module 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptxModule 2_ Divide and Conquer Approach.pptx
Module 2_ Divide and Conquer Approach.pptx
 
Module 1_ Introduction.pptx
Module 1_ Introduction.pptxModule 1_ Introduction.pptx
Module 1_ Introduction.pptx
 
Module 1_ Introduction to Mobile Computing.pptx
Module 1_  Introduction to Mobile Computing.pptxModule 1_  Introduction to Mobile Computing.pptx
Module 1_ Introduction to Mobile Computing.pptx
 
Module 2_ GSM Mobile services.pptx
Module 2_  GSM Mobile services.pptxModule 2_  GSM Mobile services.pptx
Module 2_ GSM Mobile services.pptx
 
MODULE 4_ CLUSTERING.pptx
MODULE 4_ CLUSTERING.pptxMODULE 4_ CLUSTERING.pptx
MODULE 4_ CLUSTERING.pptx
 
MODULE 5 _ Mining frequent patterns and associations.pptx
MODULE 5 _ Mining frequent patterns and associations.pptxMODULE 5 _ Mining frequent patterns and associations.pptx
MODULE 5 _ Mining frequent patterns and associations.pptx
 
DWM-MODULE 6.pdf
DWM-MODULE 6.pdfDWM-MODULE 6.pdf
DWM-MODULE 6.pdf
 
TCS MODULE 6.pdf
TCS MODULE 6.pdfTCS MODULE 6.pdf
TCS MODULE 6.pdf
 
Module 3_ Classification.pptx
Module 3_ Classification.pptxModule 3_ Classification.pptx
Module 3_ Classification.pptx
 
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
Module 2_ Introduction to Data Mining, Data Exploration and Data Pre-processi...
 
Module 1_Data Warehousing Fundamentals.pptx
Module 1_Data Warehousing Fundamentals.pptxModule 1_Data Warehousing Fundamentals.pptx
Module 1_Data Warehousing Fundamentals.pptx
 
Module 2_ Cyber offenses & Cybercrime.pptx
Module 2_ Cyber offenses & Cybercrime.pptxModule 2_ Cyber offenses & Cybercrime.pptx
Module 2_ Cyber offenses & Cybercrime.pptx
 
Module 1- Introduction to Cybercrime.pptx
Module 1- Introduction to Cybercrime.pptxModule 1- Introduction to Cybercrime.pptx
Module 1- Introduction to Cybercrime.pptx
 
MODULE 5- EDA.pptx
MODULE 5- EDA.pptxMODULE 5- EDA.pptx
MODULE 5- EDA.pptx
 
MODULE 4-Text Analytics.pptx
MODULE 4-Text Analytics.pptxMODULE 4-Text Analytics.pptx
MODULE 4-Text Analytics.pptx
 
Module 3 - Time Series.pptx
Module 3 - Time Series.pptxModule 3 - Time Series.pptx
Module 3 - Time Series.pptx
 
Module 2_ Regression Models..pptx
Module 2_ Regression Models..pptxModule 2_ Regression Models..pptx
Module 2_ Regression Models..pptx
 
MODULE 1_Introduction to Data analytics and life cycle..pptx
MODULE 1_Introduction to Data analytics and life cycle..pptxMODULE 1_Introduction to Data analytics and life cycle..pptx
MODULE 1_Introduction to Data analytics and life cycle..pptx
 
IOE MODULE 6.pptx
IOE MODULE 6.pptxIOE MODULE 6.pptx
IOE MODULE 6.pptx
 
MAD&PWA VIVA QUESTIONS.pdf
MAD&PWA VIVA QUESTIONS.pdfMAD&PWA VIVA QUESTIONS.pdf
MAD&PWA VIVA QUESTIONS.pdf
 

Recently uploaded

COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersMairaAshraf6
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startQuintin Balsdon
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...soginsider
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stageAbc194748
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 

Recently uploaded (20)

COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 

Module 5-Structure and Union

  • 1. MODULE 5:STRUCTURE AND UNION CO4:Demonstrate the use of arrays, strings and structures in C language.
  • 2. CONTENTS ● Concept of Structure and Union ● Declaration and Initialization of structure and union ● Nested structures ● Array of Structures ● Passing structure to functions
  • 3. NEED FOR STRUCTURE Suppose, you want to store information about a person: his/her name, citizenship number, and salary. You can create different variables name, citNo and salary to store this information. What if you need to store information of more than one person? Now, you need to create different variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2, etc. A better approach would be to have a collection of all related information under a single name Person structure and use it for every person.
  • 4. STRUCTURE A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record. Defining a structure: To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than or equal to one member. The format of the struct statement is as follows: struct [structure name] { member definition; member definition; ... member definition; };
  • 6. DECLARING STRUCTURE VARIABLE You can declare structure variable in two ways:- 1. By struct keyword within main() function 2. By declaring variable at the time of defining structure.
  • 7. DECLARING STRUCTURE VARIABLE When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables. struct employee { char name[50]; int id; float salary; }; int main() { struct employee e1, e2, e[20]; return 0; }
  • 8. DECLARING STRUCTURE VARIABLE struct employee { char name[50]; int id; float salary; } e1, e2, e[20]; In both cases, two variables e1, e2, and an array variable e having 20 elements of type struct employee are created.
  • 9. DECLARING STRUCTURE VARIABLE #include <stdio.h> #include <string.h> struct student { int rollno; char name[60]; }s1; //declaring s1 variable for structure void main( ) { //store first employee information s1.rollno=1; strcpy(s1.name, “nikhat”);//copying string into char array //printing first employee information printf( "Rollno : %dn", s1.rollno); printf( "Name : %sn", s1.name); }
  • 10. ACCESS MEMBERS OF A STRUCTURE There are two types of operators used for accessing members of a structure. . Member operator -> Structure pointer operator (to access the members of the structure that being referenced using pointer) Suppose, you want to access the salary of e2 (Using member operator) e2.salary To access the members of the structure referenced using the pointer we use the operator “->”.This operator is called as arrow operator. Using this we can access all the members of the structure and we can further do all operations on them. s->age=18;
  • 11. KEYWORD typedef We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables. struct distance { int feet; float inch; }; int main() { struct distance d1, d2; }
  • 12. Keyword typedef typedef struct distance { int feet; float inch; } distance; int main() { distance d1, d2; }
  • 13. NESTED STRUCTURES C provides us the feature of nesting one structure within another structure by using which, complex data types are created. For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code. Hence, to store the address of the employee, we need to store the address of the employee into a separate structure and nest the structure address into the structure employee.
  • 14. NESTED STRUCTURES #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; };
  • 15. NESTED STRUCTURES void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.a dd.phone); printf("Printing the employee informationn"); printf("name: %snCity: %snPincode: %dnPhone: %s",emp.name,e mp.add.city,emp.add.pin,emp.add.phone); }
  • 16. NESTED STRUCTURES The structure can be nested in the following ways. 1. By separate structure 2. By Embedded structure
  • 17. NESTED STRUCTURES 1) Separate structure Here, we create two structures, but the dependent structure should be used inside the main structure as a member. Consider the following example. struct Date { int dd; int mm; int yyyy; }; struct Employee { int id; char name[20]; struct Date doj; }emp1; doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.
  • 18. NESTED STRUCTURES 2) Embedded structure The embedded structure enables us to declare the structure inside the structure. Hence, it requires less line of codes but it can not be used in multiple data structures. struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; }doj;
  • 19. ACCESSING NESTED STRUCTURE We can access the member of the nested structure by Outer Structure variable. Inner Structure variable .member of inner structure e1.doj.dd e1.doj.mm e1.doj.yyyy
  • 20. ACCESSING NESTED STRUCTURE #include <stdio.h> #include <string.h> struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; }doj; }e1;
  • 21. ACCESSING NESTED STRUCTURE int main( ) { //storing employee information e1.id=101; strcpy(e1.name, “Nikhat");//copying string into char array e1.doj.dd=10; e1.doj.mm=11; e1.doj.yyyy=2014; //printing first employee information printf( "employee id : %dn", e1.id); printf( "employee name : %sn", e1.name); printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%dn", e1.doj.dd,e1.doj.mm,e1.doj.yyyy); return 0; }
  • 22. ARRAY OF STRUCTURES An array of structures can be defined as the collection of multiple structures variables where each variable contains information about different entities. The array of structures in C are used to store information about multiple entities of different data types. The array of structures is also known as the collection of structures. To declare an array of structure, first the structure must be defined and then an array variable of that type should be defined. For Example − struct book b[10]; //10 elements in an array of structures of type ‘book’
  • 24. INITIALIZING ARRAY OF STRUCTURES struct car { char make[20]; char model[30]; int year; }; struct car arrcar[2] = { {"Audi", "TT", 2016}, {"Bentley", "Azure", 2002} };
  • 25. ARRAY OF STRUCTURES Consider a case, where we need to store the data of 5 students. We can store it by using the structure #include<stdio.h> #include <string.h> struct student{ int rollno; char name[10]; };
  • 26. ARRAY OF STRUCTURES int main(){ int i; struct student st[5]; printf("Enter Records of 5 students"); for(i=0;i<5;i++) { printf("nEnter Rollno:"); scanf("%d",&st[i].rollno); printf("nEnter Name:"); scanf("%s",&st[i].name); } printf("nStudent Information List:"); for(i=0;i<5;i++){ printf("nRollno:%d, Name:%s",st[i].rollno,st[i].name); } return 0; }
  • 27. PASSING STRUCTURE TO FUNCTION #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; struct employee { char name[20]; struct address add; }; void display(struct employee);
  • 28. PASSING STRUCTURE TO FUNCTION void main () { struct employee emp; printf("Enter employee information?n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.pho ne); display(emp); } void display(struct employee emp) { printf("Printing the details....n"); printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone); }
  • 29. UNION Union also stores the elements of different types i.e heterogeneous elements. The union keyword is used to define structure. Union takes the memory of largest member only so occupies less memory than structures. Structures allocate enough space to store all their members, whereas unions can only hold one member value at a time. We use the union keyword to define union. union car { char name[50]; int price; };
  • 30. CREATE UNION VARIABLES When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a given union type and work with it, we need to create variables. 1. Inside main function union car { char name[50]; int price; }; int main() { union car car1, car2, *car3; return 0; }
  • 31. CREATE UNION VARIABLES 2. During declaration union car { char name[50]; int price; } car1, car2, *car3; In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.
  • 32. ACCESS MEMBERS OF A UNION We use the . operator to access members of a union. To access pointer variables, we use the -> operator. In the above example, •To access price for car1, car1.price is used. •To access price using car3, either (*car3).price or car3->price can be used.
  • 33. ACCESS MEMBERS OF A UNION #include <stdio.h> union Job { float salary; int workerNo; } j; int main() { j.salary = 12.3; // when j.workerNo is assigned a value, // j.salary will no longer hold 12.3 j.workerNo = 100; printf("Salary = %.1fn", j.salary); printf("Number of workers = %d", j.workerNo); return 0; }
  • 34. SIMILARITIES BETWEEN STRUCTURE AND UNION 1. Both are user-defined data types used to store data of different types as a single unit. 2. Their members can be objects of any type, including other structures and unions or arrays. A member can also consist of a bit field. 3. Both structures and unions support only assignment = and sizeof operators. The two structures or unions in the assignment must have the same members and member types. 4. A structure or a union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable as a corresponding parameter. 5. ‘.’ operator is used for accessing members.
  • 35. DIFFERENCE BETWEEN UNIONS AND STRUCTURES #include <stdio.h> union unionJob { //defining a union char name[32]; float salary; int workerNo; } uJob; struct structJob { char name[32]; float salary; int workerNo; } sJob; int main() { printf("size of union = %d bytes", sizeof(uJob)); printf("nsize of structure = %d bytes", sizeof(sJob)); return 0; }
  • 36. DIFFERENCE BETWEEN STRUCTURES AND UNIONS size of union = 32 size of structure = 40 Here, the size of sJob is 40 bytes because •the size of name[32] is 32 bytes •the size of salary is 4 bytes •the size of workerNo is 4 bytes However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In the above example, the size of its largest element, (name[32]), is 32 bytes. With a union, all members share the same memory.