SlideShare a Scribd company logo
1 of 23
DISCOVER . LEARN . EMPOWER
Structure: Nested Structures, Array of
Structures
INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-2
Bachelor of Engineering (Computer Science & Engineering)
Subject Name: Fundamentals of Computer Programming
Subject Code: 21CSH-101
Fundamentals of
Computer
Programming
Course Objectives
2
The course aims to provide exposure to problem-
solving through programming.
The course aims to raise the programming skills
of students via logic building capability.
With knowledge of C programming language,
students would be able to model real world
problems.
3
• 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.
• Example:
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
Nested Structure
struct employee
{
char name[20];
struct address add;
};
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.phone);
printf("Printing the employee information....n");
printf("name: %snCity: %snPincode: %dnPhone:%s“,emp.name,emp.add.city, emp.add.pin,
emp.add.phone);
}
4
Output:
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
5
Ways of Nesting a Structure
• The structure can be nested in the following ways:
1.By separate structure
2.By Embedded structure
6
Nesting a Structure by 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;
• As you can see, 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. 7
Nesting a Structure by 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. Consider
the following example.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
8
Accessing Nested Structure
• We can access the member of the nested structure by
Outer_Structure.Nested_Structure.member as given below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
9
Nesting Structure Example
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal
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;
}
10
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
11
Array of Structures
• Declaring an array of structure is same as declaring an array of fundamental types.
• Since an array is a collection of elements of the same type.
• In an array of structures, each element of an array is of the structure type.
• Let's take an example:
struct car
{
char make[20];
char model[30];
int year;
};
12
Declaration of Array of Structures
Example: struct car arr_car[10];
• Here arr_car is an array of 10 elements where each
element is of type struct car.
• We can use arr_car to store 10 structure variables of
type struct car.
• To access individual elements we will use subscript
notation ([]) and to access the members of each
element we will use dot (.) operator as usual.
13
• arr_stu[0] : points to the 0th element of the array.
• arr_stu[1] : points to the 1st element of the array.
• arr_stu[0].name : refers to the name member of the 0th element of the array.
• arr_stu[0].roll_no : refers to the roll_no member of the 0th element of the array.
• arr_stu[0].marks : refers to the marks member of the 0th element of the array.
Note: the precedence of [] array subscript and dot(.) operator is same and they
evaluates from left to right. Therefore in the above expression first array
subscript([]) is applied followed by dot (.) operator. The array subscript ([]) and
dot(.) operator is same and they evaluates from left to right. Therefore in the above
expression first [] array subscript is applied followed by dot (.) operator.
14
Example:
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = 20;
printf("%d %d", arr[0].x, arr[0].y);
return 0;
}
Output:
10 20
15
Structure Vs Union
Sr. No. Key Structure Union
1
Definition Structure is the container defined in C to store data variables
of different type and also supports for the user defined
variables storage.
On other hand Union is also similar kind of container in C
which can also holds the different type of variables along with
the user defined variables.
2
Internal implementation Structure in C is internally implemented as that there is
separate memory location is allotted to each input member
While in case Union memory is allocated only to one member
having largest size among all other input variables and the
same location is being get shared among all of these.
3
Syntax Syntax of declare a Structure in C is as follow :struct
struct_name{ type element1; type element2; . . } variable1,
variable2, ...;
On other syntax of declare a Union in C is as follow:union
u_name{ type element1; type element2; . . } variable1,
variable2, ...;
4
Size As mentioned in definition Structure do not have shared
location for its members so size of Structure is equal or greater
than the sum of size of all the data members.
On other hand Union does not have separate location for each
of its member so its size or equal to the size of largest member
among all data members.
5
Value storage As mentioned above in case of Structure there is specific
memory location for each input data member and hence it can
store multiple values of the different members.
While in case of Union there is only one shared memory
allocation for all input data members so it stores a single value
at a time for all members.
6
Initialization In Structure multiple members can be can be initializing at
same time.
On other hand in case of Union only the first member can get
initialize at a time.
16
17
Summary
C provides us the feature of
nesting one structure within
another structure by using
which, complex data types are
created.
The structure can be nested in
the following ways.
a) By separate structure
b) By Embedded structure
We can access the member of
the nested structure by
Outer_Structure.Nested_Struct
ure.member
Declaring an array of structure
is same as declaring an array of
fundamental types.
In an array of structures, each
element of an array is of the
structure type.
We can also initialize the array
of structures using the same
syntax as that for initializing
arrays.
Frequently Asked Questions
Q1 What is the meaning of nested structure?
Ans: Nested structures as its name suggest in C is kind of defining one structure inside another structure. Any member variables can be
defined inside a structure and in turn, that structure can further be moved into another structure. The variables inside a structure can be
anything like normal or pointer or anything and can be placed anywhere within the structure
Q2 The correct syntax to access the member of the ith structure in the array of structures is?
struct temp
{
int b;
}s[50];
a) s.b.[i];
b) s.[i].b;
c) s.b[i];
d) s[i].b;
Ans: d
18
Q3: What will be the output of the C program?
void main()
{
struct bitfields {
int bits_1: 2;
int bits_2: 9;
int bits_3: 6;
int bits_4: 1;
}bit;
printf("%d", sizeof(bit));
}
A. 2
B. 3
C. 4
D. 0
Ans: Option: B
Explanation: 1 byte = 8 bits
In the above program we assign 2, 9, 6, 1 for the variables. Sum of the bits assigned is, 2 + 9 + 6 + 1
= 18, It is greater than 2 bytes, so it automatically takes 3 bytes.
19
Assessment Questions:
20
1. C Program to Calculate Size of Structure using Sizeof Operator
2. Write a C program to Sort Two Structures on the basis of any structure element and Display Information
Program Statement – Define a structure called cricket that will describe the following information
Player name
Team name
Batting average
Using cricket, declare an array player with 10 elements and write a program to read the information about all the 10
players and print a team wise list containing names of players with their batting average.
Discussion forum
PROBLEM: C Program to sort array of Structure
in C Programming
Write a C program to accept records of the different
states using array of structures. The structure should
contain char state, population, literacy rate, and
income. Display the state whose literacy rate is
highest and whose income is highest.
21
REFERENCES
Reference Books
1. Programming in C by Reema Thareja.
2. Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.
3. Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
4. The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson
education.
Websites:
1. https://www.javatpoint.com/nested-structure-in-c
2. https://www.geeksforgeeks.org/structures-c/
3. https://overiq.com/c-programming-101/array-of-structures-in-c/
YouTube Links:
1. https://www.youtube.com/channel/UC63URkuUvnugRBeTNqmToKg
2. https://www.youtube.com/watch?v=0x9EVpv1V0k
3. https://www.youtube.com/watch?v=3LQTxwKZAOY 22
THANK YOU

More Related Content

Similar to Chapter 8 Structure Part 2 (1).pptx

Similar to Chapter 8 Structure Part 2 (1).pptx (20)

Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
CHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptxCHAPTER -4-class and structure.pptx
CHAPTER -4-class and structure.pptx
 
structure1.pdf
structure1.pdfstructure1.pdf
structure1.pdf
 
Programming in C session 3
Programming in C session 3Programming in C session 3
Programming in C session 3
 
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++
 
Data Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self ReferentialData Structure & Algorithm - Self Referential
Data Structure & Algorithm - Self Referential
 
Structures in C
Structures in CStructures in C
Structures in C
 
lec14.pdf
lec14.pdflec14.pdf
lec14.pdf
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
Structure & union
Structure & unionStructure & union
Structure & union
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
Structure in c language
Structure in c languageStructure in c language
Structure in c language
 
CP Handout#10
CP Handout#10CP Handout#10
CP Handout#10
 
C Programming - Refresher - Part IV
C Programming - Refresher - Part IVC Programming - Refresher - Part IV
C Programming - Refresher - Part IV
 
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
 
C programming session7
C programming  session7C programming  session7
C programming session7
 

More from Abhishekkumarsingh630054

More from Abhishekkumarsingh630054 (7)

UNIT 2 LOOP CONTROL.pptx
UNIT 2 LOOP CONTROL.pptxUNIT 2 LOOP CONTROL.pptx
UNIT 2 LOOP CONTROL.pptx
 
lecture 10 Recursive Function and Macros.ppt
lecture 10 Recursive Function and Macros.pptlecture 10 Recursive Function and Macros.ppt
lecture 10 Recursive Function and Macros.ppt
 
NIFT-Sample-Paper-2020-btech-Programme-GAT.pdf
NIFT-Sample-Paper-2020-btech-Programme-GAT.pdfNIFT-Sample-Paper-2020-btech-Programme-GAT.pdf
NIFT-Sample-Paper-2020-btech-Programme-GAT.pdf
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
 
7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx
 
DT-2 Exp 2.3_2.pdf
DT-2 Exp 2.3_2.pdfDT-2 Exp 2.3_2.pdf
DT-2 Exp 2.3_2.pdf
 
ar vr mr certificate.pdf
ar vr mr certificate.pdfar vr mr certificate.pdf
ar vr mr certificate.pdf
 

Recently uploaded

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 

Recently uploaded (20)

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 

Chapter 8 Structure Part 2 (1).pptx

  • 1. DISCOVER . LEARN . EMPOWER Structure: Nested Structures, Array of Structures INSTITUTE - UIE DEPARTMENT- ACADEMIC UNIT-2 Bachelor of Engineering (Computer Science & Engineering) Subject Name: Fundamentals of Computer Programming Subject Code: 21CSH-101
  • 2. Fundamentals of Computer Programming Course Objectives 2 The course aims to provide exposure to problem- solving through programming. The course aims to raise the programming skills of students via logic building capability. With knowledge of C programming language, students would be able to model real world problems.
  • 3. 3 • 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. • Example: #include<stdio.h> struct address { char city[20]; int pin; char phone[14]; }; Nested Structure
  • 4. struct employee { char name[20]; struct address add; }; 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.phone); printf("Printing the employee information....n"); printf("name: %snCity: %snPincode: %dnPhone:%s“,emp.name,emp.add.city, emp.add.pin, emp.add.phone); } 4
  • 5. Output: Enter employee information? Arun Delhi 110001 1234567890 Printing the employee information.... name: Arun City: Delhi Pincode: 110001 Phone: 1234567890 5
  • 6. Ways of Nesting a Structure • The structure can be nested in the following ways: 1.By separate structure 2.By Embedded structure 6
  • 7. Nesting a Structure by 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; • As you can see, 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. 7
  • 8. Nesting a Structure by 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. Consider the following example. struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; }doj; }emp1; 8
  • 9. Accessing Nested Structure • We can access the member of the nested structure by Outer_Structure.Nested_Structure.member as given below: e1.doj.dd e1.doj.mm e1.doj.yyyy 9
  • 10. Nesting Structure Example #include <stdio.h> #include <string.h> struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; }doj; }e1; int main( ) { //storing employee information e1.id=101; strcpy(e1.name, "Sonoo Jaiswal 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; } 10
  • 11. Output: employee id : 101 employee name : Sonoo Jaiswal employee date of joining (dd/mm/yyyy) : 10/11/2014 11
  • 12. Array of Structures • Declaring an array of structure is same as declaring an array of fundamental types. • Since an array is a collection of elements of the same type. • In an array of structures, each element of an array is of the structure type. • Let's take an example: struct car { char make[20]; char model[30]; int year; }; 12
  • 13. Declaration of Array of Structures Example: struct car arr_car[10]; • Here arr_car is an array of 10 elements where each element is of type struct car. • We can use arr_car to store 10 structure variables of type struct car. • To access individual elements we will use subscript notation ([]) and to access the members of each element we will use dot (.) operator as usual. 13
  • 14. • arr_stu[0] : points to the 0th element of the array. • arr_stu[1] : points to the 1st element of the array. • arr_stu[0].name : refers to the name member of the 0th element of the array. • arr_stu[0].roll_no : refers to the roll_no member of the 0th element of the array. • arr_stu[0].marks : refers to the marks member of the 0th element of the array. Note: the precedence of [] array subscript and dot(.) operator is same and they evaluates from left to right. Therefore in the above expression first array subscript([]) is applied followed by dot (.) operator. The array subscript ([]) and dot(.) operator is same and they evaluates from left to right. Therefore in the above expression first [] array subscript is applied followed by dot (.) operator. 14
  • 15. Example: #include<stdio.h> struct Point { int x, y; }; int main() { // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; printf("%d %d", arr[0].x, arr[0].y); return 0; } Output: 10 20 15
  • 16. Structure Vs Union Sr. No. Key Structure Union 1 Definition Structure is the container defined in C to store data variables of different type and also supports for the user defined variables storage. On other hand Union is also similar kind of container in C which can also holds the different type of variables along with the user defined variables. 2 Internal implementation Structure in C is internally implemented as that there is separate memory location is allotted to each input member While in case Union memory is allocated only to one member having largest size among all other input variables and the same location is being get shared among all of these. 3 Syntax Syntax of declare a Structure in C is as follow :struct struct_name{ type element1; type element2; . . } variable1, variable2, ...; On other syntax of declare a Union in C is as follow:union u_name{ type element1; type element2; . . } variable1, variable2, ...; 4 Size As mentioned in definition Structure do not have shared location for its members so size of Structure is equal or greater than the sum of size of all the data members. On other hand Union does not have separate location for each of its member so its size or equal to the size of largest member among all data members. 5 Value storage As mentioned above in case of Structure there is specific memory location for each input data member and hence it can store multiple values of the different members. While in case of Union there is only one shared memory allocation for all input data members so it stores a single value at a time for all members. 6 Initialization In Structure multiple members can be can be initializing at same time. On other hand in case of Union only the first member can get initialize at a time. 16
  • 17. 17 Summary C provides us the feature of nesting one structure within another structure by using which, complex data types are created. The structure can be nested in the following ways. a) By separate structure b) By Embedded structure We can access the member of the nested structure by Outer_Structure.Nested_Struct ure.member Declaring an array of structure is same as declaring an array of fundamental types. In an array of structures, each element of an array is of the structure type. We can also initialize the array of structures using the same syntax as that for initializing arrays.
  • 18. Frequently Asked Questions Q1 What is the meaning of nested structure? Ans: Nested structures as its name suggest in C is kind of defining one structure inside another structure. Any member variables can be defined inside a structure and in turn, that structure can further be moved into another structure. The variables inside a structure can be anything like normal or pointer or anything and can be placed anywhere within the structure Q2 The correct syntax to access the member of the ith structure in the array of structures is? struct temp { int b; }s[50]; a) s.b.[i]; b) s.[i].b; c) s.b[i]; d) s[i].b; Ans: d 18
  • 19. Q3: What will be the output of the C program? void main() { struct bitfields { int bits_1: 2; int bits_2: 9; int bits_3: 6; int bits_4: 1; }bit; printf("%d", sizeof(bit)); } A. 2 B. 3 C. 4 D. 0 Ans: Option: B Explanation: 1 byte = 8 bits In the above program we assign 2, 9, 6, 1 for the variables. Sum of the bits assigned is, 2 + 9 + 6 + 1 = 18, It is greater than 2 bytes, so it automatically takes 3 bytes. 19
  • 20. Assessment Questions: 20 1. C Program to Calculate Size of Structure using Sizeof Operator 2. Write a C program to Sort Two Structures on the basis of any structure element and Display Information Program Statement – Define a structure called cricket that will describe the following information Player name Team name Batting average Using cricket, declare an array player with 10 elements and write a program to read the information about all the 10 players and print a team wise list containing names of players with their batting average.
  • 21. Discussion forum PROBLEM: C Program to sort array of Structure in C Programming Write a C program to accept records of the different states using array of structures. The structure should contain char state, population, literacy rate, and income. Display the state whose literacy rate is highest and whose income is highest. 21
  • 22. REFERENCES Reference Books 1. Programming in C by Reema Thareja. 2. Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill. 3. Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender Chhabra, Tata McGraw Hill. 4. The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson education. Websites: 1. https://www.javatpoint.com/nested-structure-in-c 2. https://www.geeksforgeeks.org/structures-c/ 3. https://overiq.com/c-programming-101/array-of-structures-in-c/ YouTube Links: 1. https://www.youtube.com/channel/UC63URkuUvnugRBeTNqmToKg 2. https://www.youtube.com/watch?v=0x9EVpv1V0k 3. https://www.youtube.com/watch?v=3LQTxwKZAOY 22