SlideShare a Scribd company logo
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

PPTX
CPU : Structures And Unions
PDF
Lecture19 unionsin c.ppt
PPTX
Programming in C
DOCX
Str
PPTX
Unit 9. Structure and Unions
PPTX
Presentation on c programing satcture
PPTX
C programing -Structure
DOCX
Structure in c sharp
CPU : Structures And Unions
Lecture19 unionsin c.ppt
Programming in C
Str
Unit 9. Structure and Unions
Presentation on c programing satcture
C programing -Structure
Structure in c sharp

What's hot (20)

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

Similar to Lecture 19 - Struct and Union (20)

PPTX
Structures
PDF
slideset 7 structure and union (1).pdf
PPT
structure and union from C programming Language
PPT
structure and union from c programming language.ppt
PPTX
C Structures and Unions
PPTX
Unit6STRUCTUREANDUNIONpptx__2024_11_18_12_20_46.pptx
DOCX
C programming structures &amp; union
DOC
Structures unions
PPTX
Structure & union
PDF
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
PDF
Principals of Programming in CModule -5.pdf
PPTX
C Programming: Structure and Union
PPTX
Structure&amp;union
DOCX
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
PPT
Structures-in-C programming with examples
DOC
Unit 5 (1)
PPTX
U5 SPC.pptx
PDF
Unit 4 qba
Structures
slideset 7 structure and union (1).pdf
structure and union from C programming Language
structure and union from c programming language.ppt
C Structures and Unions
Unit6STRUCTUREANDUNIONpptx__2024_11_18_12_20_46.pptx
C programming structures &amp; union
Structures unions
Structure & union
STRUCTURE AND UNION IN C MRS.SOWMYA JYOTHI.pdf
Principals of Programming in CModule -5.pdf
C Programming: Structure and Union
Structure&amp;union
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
Structures-in-C programming with examples
Unit 5 (1)
U5 SPC.pptx
Unit 4 qba
Ad

More from Md. Imran Hossain Showrov (20)

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

Recently uploaded (20)

PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Cell Structure & Organelles in detailed.
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Trump Administration's workforce development strategy
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Final Presentation General Medicine 03-08-2024.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Module 4: Burden of Disease Tutorial Slides S2 2025
Cell Structure & Organelles in detailed.
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
GDM (1) (1).pptx small presentation for students
A systematic review of self-coping strategies used by university students to ...
Abdominal Access Techniques with Prof. Dr. R K Mishra
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Trump Administration's workforce development strategy
Supply Chain Operations Speaking Notes -ICLT Program
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Orientation - ARALprogram of Deped to the Parents.pptx
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx

Lecture 19 - Struct and Union

  • 1. Structures and Unions Md. Imran Hossain Showrov ([email protected]) 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