SlideShare a Scribd company logo
1 of 22
Structures and Unions
Md. Imran Hossain Showrov (showrovsworld@gmail.com)
19
1
Outline
 What is a Structure?
 Defining a Structure
 General format of a Structure
 Arrays vs. Structure
 Accessing Structure Members
 Rules for initializing Structures
 What is a Union?
 Difference between Structure and Union
What is a Structure?
 We can not use an array if we want to represent a
collection of data items of different types using a
single name.
 Structures are a mechanism for packing data of
different types.
 A structure is a convenient tool for handling a group
of logically related data items.
What is a Structures? (cont..)
 Examples of structures:
time : seconds, minutes, hours
date : day, month, year
book : author, title, price, year
city : name, country, population
 Structures help to organize complex data in a more
meaningful way
Defining a Structure
 Consider a book database consisting of book name, author,
number of pages, and price.The structure to hold this
information as follows:
struct book_name
{
char title[20];
char author[15];
int pages ;
float price;
}
Defining a Structure (cont..)
 The keyword struct declares a structure to hold the
details of four data fields, namely title, author,
pages, and price.These fields are called structure
elements or members.
 Each member may belong to a different type of data.
 book_name is the name of the structure and is
called the structure tag.
Template of a Structure (cont..)
General format of a Structure
Arrays vs. Structure
1. An array is a collection of related data elements of
same types. Structure can have elements of different
types.
2. An array is derived data type whereas a structure is
a programmer-defined one.
3. Any array behaves like a built-in data type.All we
have to do is to declare an array variable and use it.
But in the case of a structure, first we have to
design and declare a data structure before the
variables of that type are declared and used.
Declaring a Structure
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
 Here book1, book2, book3 are declared as variables
of type struct book_bank .
Accessing Structure Members
 The link between a member and a variable is
established using the member operation ('.’)
 From the previous example:
Book1.price
 It is a variable representing the price of book1.
 We can use scanf to give the value through keyboard
scanf(“%s”, book1.title);
scanf(“%d”, &book1.pages);
Accessing Structure Members (Code)
struct personal
{
char name[20];
int day;
char month[10];
int year;
float salary;
};
int main()
{
struct personal person;
printf(“InputValue: ”);
Accessing Structure Members (Code)
scanf(“%s %d %s %d %f”,
person.name, &person.day, person.month
&person.year, &person.salary);
printf(“Output: %s %d %s %d %fn”,
person.name, person.day, person.month
person.year, person.salary);
}
Output:
Input values: Mackangee 10 june 1945 4500
Output: Mackangee 10 june 1945 4500.00
Rules for initializing Structures
1. We cannot initialize individual members inside the structure
template.
2. The order of values enclosed in braces must match the order of
members in the structure definition.
3. It is permitted to have a partial initialization.We can initialize only
the first few members and leave the remaining blank.The
uninitialized members should be only at the end of the list.
4. The uninitialized members will be assigned default values as
follows:
 Zero for integer and floating point numbers.
 ‘0’ for characters and strings.
What is a Union?
 Unions are a concept borrowed from structures and
therefore follow the same syntax as structures.
 The major distinction between structure and union is
the storage.
 In structure, each member has its own storage
location, whereas all the members of a union use the
same location.
 Although a union may contain many members o
different types, it can handle only one member at a
time.
Unions (Example1)
 For example in the following C program, both x and y share the same location. If we change x, we can
see the changes being reflected in y.
– union test {
– int x, y;
– };
– int main()
– {
– union test t;
– t.x = 2; // t.y also gets value 2
– printf("After making x = 2:n x = %d, y = %dnn", t.x, t.y);
– t.y = 10; // t.x is also updated to 10
– printf("After making y = 10:n x = %d, y = %dnn", t.x, t.y);
– return 0;
– }
Unions (Example1) (cont..)
 Output:
– After making x = 2:
– x = 2, y = 2
– After making y = 10:
– x = 10, y = 10
Unions (Example2)
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
Unions (Example2) (cont…)
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", data.str);
return 0;
}
Unions (Example2) (cont…)
Output:
data.i : 10
data.f : 220.500000
data.str : C Programming
Difference between Structure and Union
Lecture 19 - Struct and Union

More Related Content

What's hot

What's hot (20)

Structure in c
Structure in cStructure in c
Structure in c
 
C Structures & Unions
C Structures & UnionsC Structures & Unions
C Structures & Unions
 
Lecture 04
Lecture 04Lecture 04
Lecture 04
 
How to implement joins in mongo db
How to implement joins in mongo dbHow to implement joins in mongo db
How to implement joins in mongo db
 
03 structures
03 structures03 structures
03 structures
 
Structure in c
Structure in cStructure in c
Structure in c
 
Structure in C
Structure in CStructure in C
Structure in C
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Structure c
Structure cStructure c
Structure c
 
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
Basic of Structure,Structure members,Accessing Structure member,Nested Struct...
 
Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)
 
Dynamic memory allocation and linked lists
Dynamic memory allocation and linked listsDynamic memory allocation and linked lists
Dynamic memory allocation and linked lists
 
Home Page Live(Www2007)
Home Page Live(Www2007)Home Page Live(Www2007)
Home Page Live(Www2007)
 
Lecture18 structurein c.ppt
Lecture18 structurein c.pptLecture18 structurein c.ppt
Lecture18 structurein c.ppt
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
CSMR: A Scalable Algorithm for Text Clustering with Cosine Similarity and Map...
CSMR: A Scalable Algorithm for Text Clustering with Cosine Similarity and Map...CSMR: A Scalable Algorithm for Text Clustering with Cosine Similarity and Map...
CSMR: A Scalable Algorithm for Text Clustering with Cosine Similarity and Map...
 
Structures
StructuresStructures
Structures
 
Programming in C session 3
Programming in C session 3Programming in C session 3
Programming in C session 3
 
Structures
StructuresStructures
Structures
 

Similar to Lecture 19 - Struct and Union

Similar to Lecture 19 - Struct and Union (20)

C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
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++
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
 
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdfSTRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
structure and union1.pdf
structure and union1.pdfstructure and union1.pdf
structure and union1.pdf
 
Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 
C structure and union
C structure and unionC structure and union
C structure and union
 
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 1_ADC.pptx
Unit 1_ADC.pptxUnit 1_ADC.pptx
Unit 1_ADC.pptx
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and Typedef
 
Union.ppt
Union.pptUnion.ppt
Union.ppt
 
Unit 3
Unit 3Unit 3
Unit 3
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 

More from Md. Imran Hossain Showrov

Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Md. Imran Hossain Showrov
 
Lecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesLecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesMd. Imran Hossain Showrov
 

More from Md. Imran Hossain Showrov (20)

Lecture 22 - Error Handling
Lecture 22 - Error HandlingLecture 22 - Error Handling
Lecture 22 - Error Handling
 
Lecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header FileLecture 21 - Preprocessor and Header File
Lecture 21 - Preprocessor and Header File
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Lecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional ArrayLecture 16 - Multi dimensional Array
Lecture 16 - Multi dimensional Array
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
Lecture 13 - Storage Classes
Lecture 13 - Storage ClassesLecture 13 - Storage Classes
Lecture 13 - Storage Classes
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Lecture 7- Operators and Expressions
Lecture 7- Operators and Expressions Lecture 7- Operators and Expressions
Lecture 7- Operators and Expressions
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language Lecture 5 - Structured Programming Language
Lecture 5 - Structured Programming Language
 
Lecture 4- Computer Software and Languages
Lecture 4- Computer Software and LanguagesLecture 4- Computer Software and Languages
Lecture 4- Computer Software and Languages
 
Lecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devicesLecture 3 - Processors, Memory and I/O devices
Lecture 3 - Processors, Memory and I/O devices
 
Lecture 2 - Introductory Concepts
Lecture 2 - Introductory ConceptsLecture 2 - Introductory Concepts
Lecture 2 - Introductory Concepts
 

Recently uploaded

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

Lecture 19 - Struct and Union

  • 1. Structures and Unions Md. Imran Hossain Showrov (showrovsworld@gmail.com) 19 1
  • 2. Outline  What is a Structure?  Defining a Structure  General format of a Structure  Arrays vs. Structure  Accessing Structure Members  Rules for initializing Structures  What is a Union?  Difference between Structure and Union
  • 3. What is a Structure?  We can not use an array if we want to represent a collection of data items of different types using a single name.  Structures are a mechanism for packing data of different types.  A structure is a convenient tool for handling a group of logically related data items.
  • 4. What is a Structures? (cont..)  Examples of structures: time : seconds, minutes, hours date : day, month, year book : author, title, price, year city : name, country, population  Structures help to organize complex data in a more meaningful way
  • 5. Defining a Structure  Consider a book database consisting of book name, author, number of pages, and price.The structure to hold this information as follows: struct book_name { char title[20]; char author[15]; int pages ; float price; }
  • 6. Defining a Structure (cont..)  The keyword struct declares a structure to hold the details of four data fields, namely title, author, pages, and price.These fields are called structure elements or members.  Each member may belong to a different type of data.  book_name is the name of the structure and is called the structure tag.
  • 7. Template of a Structure (cont..)
  • 8. General format of a Structure
  • 9. Arrays vs. Structure 1. An array is a collection of related data elements of same types. Structure can have elements of different types. 2. An array is derived data type whereas a structure is a programmer-defined one. 3. Any array behaves like a built-in data type.All we have to do is to declare an array variable and use it. But in the case of a structure, first we have to design and declare a data structure before the variables of that type are declared and used.
  • 10. Declaring a Structure struct book_bank { char title[20]; char author[15]; int pages; float price; } book1, book2, book3;  Here book1, book2, book3 are declared as variables of type struct book_bank .
  • 11. Accessing Structure Members  The link between a member and a variable is established using the member operation ('.’)  From the previous example: Book1.price  It is a variable representing the price of book1.  We can use scanf to give the value through keyboard scanf(“%s”, book1.title); scanf(“%d”, &book1.pages);
  • 12. Accessing Structure Members (Code) struct personal { char name[20]; int day; char month[10]; int year; float salary; }; int main() { struct personal person; printf(“InputValue: ”);
  • 13. Accessing Structure Members (Code) scanf(“%s %d %s %d %f”, person.name, &person.day, person.month &person.year, &person.salary); printf(“Output: %s %d %s %d %fn”, person.name, person.day, person.month person.year, person.salary); } Output: Input values: Mackangee 10 june 1945 4500 Output: Mackangee 10 june 1945 4500.00
  • 14. Rules for initializing Structures 1. We cannot initialize individual members inside the structure template. 2. The order of values enclosed in braces must match the order of members in the structure definition. 3. It is permitted to have a partial initialization.We can initialize only the first few members and leave the remaining blank.The uninitialized members should be only at the end of the list. 4. The uninitialized members will be assigned default values as follows:  Zero for integer and floating point numbers.  ‘0’ for characters and strings.
  • 15. What is a Union?  Unions are a concept borrowed from structures and therefore follow the same syntax as structures.  The major distinction between structure and union is the storage.  In structure, each member has its own storage location, whereas all the members of a union use the same location.  Although a union may contain many members o different types, it can handle only one member at a time.
  • 16. Unions (Example1)  For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y. – union test { – int x, y; – }; – int main() – { – union test t; – t.x = 2; // t.y also gets value 2 – printf("After making x = 2:n x = %d, y = %dnn", t.x, t.y); – t.y = 10; // t.x is also updated to 10 – printf("After making y = 10:n x = %d, y = %dnn", t.x, t.y); – return 0; – }
  • 17. Unions (Example1) (cont..)  Output: – After making x = 2: – x = 2, y = 2 – After making y = 10: – x = 10, y = 10
  • 18. Unions (Example2) #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; };
  • 19. Unions (Example2) (cont…) int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", data.str); return 0; }
  • 20. Unions (Example2) (cont…) Output: data.i : 10 data.f : 220.500000 data.str : C Programming