SlideShare a Scribd company logo
1 of 23
Dr.G.Jasmine Beulah
Dept. Computer Science,
Kristu Jayanti College, Bengaluru
 Structure is a user defined data type. It is a collection of
different data type, to create a new data type.
 For example, You can define your custom type for
storing student record containing name, age and
mobile.
 Creating structure type will allow you to handle all
properties of student with single variable, instead of
handling it separately.
 In short it is a data structure in which we can collect
different types of data into one entity.
Declaration of Structure:
 To declare or define a structure, we
use struct keyword.
 It is a reserved word in the C .
struct structure_name
{
member1_declaration;
member2_declaration;
... ...
memberN_declaration;
} structure_variable;
So, if it is needed to declare student type variable along
with student structure definition we can use this
approach.
struct student
{
char name[40]; // Student name
int age; // Student age
unsigned long mobile; // Student mobile number
}s1;
 Structure members can be initialized using curly braces ‘{}’.
 For example, following is a valid initialization.
struct Point
{
int x, y;
};
int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
Structure members are accessed using dot (.) operator.
#include<stdio.h>
struct Point
{
int x, y;
};
int main()
{
struct Point p1 = {0, 1};
// Accessing members of point p1
p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);
return 0;
}
Output: x = 20, y = 1
 An array having structure as its base type is known as
an array of structure.
 To create an array of structure, first structure is
declared and then array of structure is declared just like
an ordinary array.
struct employee
{
int emp_id;
char name[20];
char dept[20];
float salary;
};
Then an array of structure can be created like:
struct employee emp[10]; /* This is array of structure */
#include<stdio.h>
/* Declaration of structure */
struct student
{
char name[30];
int roll;
float marks;
};
int main()
{ /* Declaration of array of structure */
struct student s[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter name, roll and marks of student:n");
scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks);
}
printf("Inputted details are:n");
for(i=0;i< 3;i++)
{
printf("Name: %sn",s[i].name);
printf("Roll: %dn", s[i].roll);
printf("Marks: %fnn", s[i].marks);
}
return 0;
}
 A structure can also contain array members just like normal
members such int, float
 We can declare an array if we need to store multiple values
inside structure.
 Structure may include as many array members as we
require.
 Syntax for declaring array within structure is not different
than the conventional syntax. The only difference is that it
is declared inside the structure.
 Consider the following example for storing student’s
information where we have declared an array of mark to
store marks of six subjects and display on the screen.
 Since we need to store marks for six subjects, we have to
use looping structure but the same is not true for character
array of one dimension.
struct student
{
int rno;
char name[20]; // Character array
int mark[6]; // Integer Array with six elements
float per; };
void main()
{
struct student s1; // structure variable declaration
int tot = 0;
clrscr(); // individual member initialization.
printf(“n Enter Student Roll No :”);
scanf(“%d”, &s1.rno);
printf(“n Enter Student Name :”);
gets(s1.name);
// read marks for six subjects using loop n
for(i = 0 ; i < 6 ; i++ )
{
printf(“n Enter Subject %d mark :”,i+1);
scanf(“%d”, &s1.mark[i]);
tot = tot + s1.mark[i];
}
// calculate percentage
s1.per = tot/6 ;
printf(“n Roll No : %dt Name : %s”,s1.rno, s1.name);
for( i = 0 ; i < 6 ; i++ ) // display marks
{
printf(“n%d”,s1.mark[i]);
}
printf(“nTotal : %dt Percentage : %.2f”,tot, s1.per );
getch(); }
 A union is a special data type available in C
that allows to store different data types in the
same memory location.
 You can define a union with many members,
but only one member can contain a value at
any given time.
union Data {
int i;
float f;
char str[20];
} data;
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %dn", sizeof(data));
return 0;
}
union Data {
int i;
float f;
char str[20];
};
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;
}
Structure Union
You can use a struct keyword to
define a structure.
You can use a union keyword to
define a union.
Every member within structure is
assigned a unique memory location.
In union, a memory location is
shared by all the data members.
Changing the value of one data
member will not affect other data
members in structure.
Changing the value of one data
member will change the value of
other data members in union.
The total size of the structure is the
sum of the size of every data
member.
The total size of the union is the size
of the largest data member.
You can retrieve any member at a
time.
You can access one member at a time
in the union.
It supports flexible array. It does not support a flexible array.
S.No Structure Union
1 Definition
Structure is heterogenous collection of
data items grouped together under a
single name
Definition
A union is a memory location that
is shared by several variables of
different datatypes
2 Syntax;
struct tagname
{
datatype member1;
datatype member2;
};
Syntax;
union tagname
{
datatype member1;
datatype member2;
};
3 Eg;
struct sample{
int a;
float b;
char c;
};
Eg;
union sample
{
int a;
float b;
char c;
};
4 keyword − struct keyword − union
5 Memory allocation Memory allocation
6 Memory allocated is the sum of sizes of
all datatypes in structure
(Here, 7bytes)
Memory allocated is the
maximum size allocated among
all the datatypes in union
(Here, 4bytes)
Structures

More Related Content

What's hot (20)

Encapsulation in C++
Encapsulation in C++Encapsulation in C++
Encapsulation in C++
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Structure in c
Structure in cStructure in c
Structure in c
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Cascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) helpCascading Style Sheets (CSS) help
Cascading Style Sheets (CSS) help
 
Java arrays
Java arraysJava arrays
Java arrays
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
Css
CssCss
Css
 
CSS ppt
CSS pptCSS ppt
CSS ppt
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Pointers - DataStructures
Pointers - DataStructuresPointers - DataStructures
Pointers - DataStructures
 
Dynamic Memory allocation
Dynamic Memory allocationDynamic Memory allocation
Dynamic Memory allocation
 
CSS notes
CSS notesCSS notes
CSS notes
 
Structure & union
Structure & unionStructure & union
Structure & union
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in C
 
C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 

Similar to Structures

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.pdfsudhakargeruganti
 
Presentation on structure,functions and classes
Presentation on structure,functions and classesPresentation on structure,functions and classes
Presentation on structure,functions and classesAlisha Korpal
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4YOGESH SINGH
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structuresKrishna Nanda
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing conceptskavitham66441
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.pptshivani366010
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structureDeepak Singh
 
STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING Gurwinderkaur45
 
Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)mrecedu
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and StructuresGem WeBlog
 
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...Smit Shah
 

Similar to Structures (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
 
Presentation on structure,functions and classes
Presentation on structure,functions and classesPresentation on structure,functions and classes
Presentation on structure,functions and classes
 
VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4VIT351 Software Development VI Unit4
VIT351 Software Development VI Unit4
 
Structures and Unions
Structures and UnionsStructures and Unions
Structures and Unions
 
Unit 5 (1)
Unit 5 (1)Unit 5 (1)
Unit 5 (1)
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
structures.ppt
structures.pptstructures.ppt
structures.ppt
 
Introduction to structures in c lang.ppt
Introduction to structures in c lang.pptIntroduction to structures in c lang.ppt
Introduction to structures in c lang.ppt
 
Chapter15 structure
Chapter15 structureChapter15 structure
Chapter15 structure
 
STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING STRUCTURES IN C PROGRAMMING
STRUCTURES IN C PROGRAMMING
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
 
Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)
 
Chap 10(structure and unions)
Chap 10(structure and unions)Chap 10(structure and unions)
Chap 10(structure and unions)
 
structure.ppt
structure.pptstructure.ppt
structure.ppt
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Pointers and Structures
Pointers and StructuresPointers and Structures
Pointers and Structures
 
637225564198396290.pdf
637225564198396290.pdf637225564198396290.pdf
637225564198396290.pdf
 
Structures
StructuresStructures
Structures
 
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...
 

More from DrJasmineBeulahG

More from DrJasmineBeulahG (9)

File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
 
Constants and Unformatted Input Output Functions.pptx
Constants and Unformatted Input Output Functions.pptxConstants and Unformatted Input Output Functions.pptx
Constants and Unformatted Input Output Functions.pptx
 
Software Testing.pptx
Software Testing.pptxSoftware Testing.pptx
Software Testing.pptx
 
Software Process Model.ppt
Software Process Model.pptSoftware Process Model.ppt
Software Process Model.ppt
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
 
STUDENT DETAILS DATABASE.pptx
STUDENT DETAILS DATABASE.pptxSTUDENT DETAILS DATABASE.pptx
STUDENT DETAILS DATABASE.pptx
 
Selection Sort.pptx
Selection Sort.pptxSelection Sort.pptx
Selection Sort.pptx
 
Arrays
ArraysArrays
Arrays
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

Structures

  • 1. Dr.G.Jasmine Beulah Dept. Computer Science, Kristu Jayanti College, Bengaluru
  • 2.  Structure is a user defined data type. It is a collection of different data type, to create a new data type.  For example, You can define your custom type for storing student record containing name, age and mobile.  Creating structure type will allow you to handle all properties of student with single variable, instead of handling it separately.  In short it is a data structure in which we can collect different types of data into one entity.
  • 3. Declaration of Structure:  To declare or define a structure, we use struct keyword.  It is a reserved word in the C .
  • 4. struct structure_name { member1_declaration; member2_declaration; ... ... memberN_declaration; } structure_variable; So, if it is needed to declare student type variable along with student structure definition we can use this approach.
  • 5. struct student { char name[40]; // Student name int age; // Student age unsigned long mobile; // Student mobile number }s1;
  • 6.  Structure members can be initialized using curly braces ‘{}’.  For example, following is a valid initialization. struct Point { int x, y; }; int main() { // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = {0, 1}; }
  • 7. Structure members are accessed using dot (.) operator. #include<stdio.h> struct Point { int x, y; }; int main() { struct Point p1 = {0, 1}; // Accessing members of point p1 p1.x = 20; printf ("x = %d, y = %d", p1.x, p1.y); return 0; } Output: x = 20, y = 1
  • 8.  An array having structure as its base type is known as an array of structure.  To create an array of structure, first structure is declared and then array of structure is declared just like an ordinary array.
  • 9. struct employee { int emp_id; char name[20]; char dept[20]; float salary; }; Then an array of structure can be created like: struct employee emp[10]; /* This is array of structure */
  • 10. #include<stdio.h> /* Declaration of structure */ struct student { char name[30]; int roll; float marks; };
  • 11. int main() { /* Declaration of array of structure */ struct student s[3]; int i; for(i=0;i<3;i++) { printf("Enter name, roll and marks of student:n"); scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks); }
  • 12. printf("Inputted details are:n"); for(i=0;i< 3;i++) { printf("Name: %sn",s[i].name); printf("Roll: %dn", s[i].roll); printf("Marks: %fnn", s[i].marks); } return 0; }
  • 13.  A structure can also contain array members just like normal members such int, float  We can declare an array if we need to store multiple values inside structure.  Structure may include as many array members as we require.  Syntax for declaring array within structure is not different than the conventional syntax. The only difference is that it is declared inside the structure.  Consider the following example for storing student’s information where we have declared an array of mark to store marks of six subjects and display on the screen.  Since we need to store marks for six subjects, we have to use looping structure but the same is not true for character array of one dimension.
  • 14. struct student { int rno; char name[20]; // Character array int mark[6]; // Integer Array with six elements float per; }; void main() { struct student s1; // structure variable declaration int tot = 0; clrscr(); // individual member initialization. printf(“n Enter Student Roll No :”); scanf(“%d”, &s1.rno); printf(“n Enter Student Name :”); gets(s1.name);
  • 15. // read marks for six subjects using loop n for(i = 0 ; i < 6 ; i++ ) { printf(“n Enter Subject %d mark :”,i+1); scanf(“%d”, &s1.mark[i]); tot = tot + s1.mark[i]; } // calculate percentage s1.per = tot/6 ; printf(“n Roll No : %dt Name : %s”,s1.rno, s1.name); for( i = 0 ; i < 6 ; i++ ) // display marks { printf(“n%d”,s1.mark[i]); } printf(“nTotal : %dt Percentage : %.2f”,tot, s1.per ); getch(); }
  • 16.  A union is a special data type available in C that allows to store different data types in the same memory location.  You can define a union with many members, but only one member can contain a value at any given time. union Data { int i; float f; char str[20]; } data;
  • 17. #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; printf( "Memory size occupied by data : %dn", sizeof(data)); return 0; }
  • 18.
  • 19. union Data { int i; float f; char str[20]; }; 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. Structure Union You can use a struct keyword to define a structure. You can use a union keyword to define a union. Every member within structure is assigned a unique memory location. In union, a memory location is shared by all the data members. Changing the value of one data member will not affect other data members in structure. Changing the value of one data member will change the value of other data members in union. The total size of the structure is the sum of the size of every data member. The total size of the union is the size of the largest data member. You can retrieve any member at a time. You can access one member at a time in the union. It supports flexible array. It does not support a flexible array.
  • 21. S.No Structure Union 1 Definition Structure is heterogenous collection of data items grouped together under a single name Definition A union is a memory location that is shared by several variables of different datatypes 2 Syntax; struct tagname { datatype member1; datatype member2; }; Syntax; union tagname { datatype member1; datatype member2; };
  • 22. 3 Eg; struct sample{ int a; float b; char c; }; Eg; union sample { int a; float b; char c; }; 4 keyword − struct keyword − union 5 Memory allocation Memory allocation 6 Memory allocated is the sum of sizes of all datatypes in structure (Here, 7bytes) Memory allocated is the maximum size allocated among all the datatypes in union (Here, 4bytes)