Enumerated, Structure, and Union: The Type Definition (Type def), Enumerated Types, Structure, Unions, Programming Application
Size: 491.5 KB
Language: en
Added: May 24, 2020
Slides: 18 pages
Slide Content
@2020 Presented By Y. N. D. Aravind 1
Presented By
Y. N. D. ARAVIND
M.Tech, Dept of CSE
Newton’s Group Of Institutions, Macherla
Session Objectives
Unions
Typedef
Enumerated Data Type
@2020 Presented By Y. N. D. Aravind
2
2
Structures
AStructurecanbedefinedtobeagroupoflogicallyrelateddataitems,
whichmaybeofdifferenttypes,storedincontiguousmemorylocations,
sharingacommonname,butdistinguishedbyitsmembers.
The decleration of a structure specifies the grouping of various data items into a
single unit without assigning any resources to them.
The syntax for declaring a structure in c is as follows
struct TAG
{
Data Type varaible-1;
Data Type variable-2;
……
……
Data Type variable-n;
};
Where,
struct is the keyword which tells the compiler that a structure is being defined.
Tag_name is the name of the structure.
variable1, variable2 … are called members of the structure.
The members are declared within curly braces.
The closing brace must end with the semicolon.
@2020 Presented By Y. N. D. Aravind
3
3
Example :
struct employee
{
int eno;
char name[80];
float sal;
};
Structure Definition
Thedeclerationofastructurewillnotserveanypurposewithoutitsdefinition.
Itonlyactsasabluprintforthecreationofvariablesoftypestruct.The
structuredefinitioncreatesstructurevariableandallocatesstoragespacefor
them.
Method 1 : struct Structurename var1, var2, . . . . . ;
Example : struct employee x;
Example : struct employee x, y, z ;
Method 2 :
@2020 Presented By Y. N. D. Aravind
4
4
Example :
struct employee
{
int eno;
char name[80];
float sal;
};
2 bytes
80 bytes
4 bytes
Example :
struct employee
{
int eno;
char name[80];
float sal;
}x;
The structure variable can be
created during the decleration
as follows
Accessing Structure Members
@2020 Presented By Y. N. D. Aravind
5
The members of a structure can be accessed by using dot(.) operator.
dot (.) operator
Structures use a dot (.) operator(also called period operator or member operator) to
refer its elements. Before dot, there must always be a structure variable. After the dot,
there must always be a structure element.
syntax :-structure_variable_name . structure_member_name
struct student
{
char name [5];
int roll_number;
float avg;
};
struct student s1;
The members can be accessed using the variables as shown below,
s1.name --> refers the string name
s1.roll_number --> refers the roll_number
s1.avg--> refers avg
5
Structure Initilization
@2020 Presented By Y. N. D. Aravind
6
Like any other data types, structure variables can be initialized at the point of their
definition.
Consider the following structure decleration.
struct student
{
char name [5];
int roll_number;
float avg;
};
Example :-
A variable of the structure employee can be
initialized during its defination as folloes:
struct student s1 = {“Ravi”, 10, 67.8};
6
name
roll no
avg
Array of Structures
@2020 Presented By Y. N. D. Aravind
7
Anarrayisacollectionofelementsofsamedatatypethatarestoredincontiguous
memorylocations.Astructureisacollectionofmembersofdifferentdatatypesstoredin
contiguousmemorylocations.Anarrayofstructuresisanarrayinwhicheachelementis
astructure.Thisconceptisveryhelpfulinrepresentingmultiplerecordsofafile,where
eachrecordisacollectionofdissimilardataitems.
Aswehaveanarrayofintegers,wecanhaveanarrayofstructuresalso.Forexample,
supposewewanttostoretheinformationofclassofstudents,consistingofroll_number,
nameandpercentage,Abetterapproachwouldbetouseanarrayofstructures.
Arrayofstructurescanbedeclaredasfollows,structtag_namearrayofstructure[size];
Let‟stakeanexample,tostoretheinformationof20students,wecanhavethefollowing
structuredefinitionanddeclaration,
structstudent
{
introllno;
charname[80];
floatper;
};
structstudents[20];
7
Program to illustrate an array of structures
@2020 Presented By Y. N. D. Aravind
8
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[80];
float per;
};
voidmain()
{
struct student s[20];
int i,n;
clrscr();
printf("\Enter no of students [ 1 –20 ] \n ");
scanf(“%d”,&n);
printf("\Enter %d students details \n ");
for(i = 0; i < n; i++)
scanf(“%d %s %f”,&s[i].rollno,s[i].name,&s[i].per);
printf("\n Student details: \n");
for(i=0; i<n; i++)
printf(“%3d %20s %9.2f \n”, s[i].rollno,s[i].name,s[i].per);
getch(();
}
8
Input-Output
Enter no of students [ 1 –20 ]
2
Enter 2 students details
1Ramesh 90
2Anusha 80
Student details:
1Ramesh 90.00
2Anusha 80 .00
Array Within Structures
@2020 Presented By Y. N. D. Aravind
9
It is also possible to declare an array as a member of structure, like declaring ordinary
variables. For example to store marks of a student in six subjects then we can have the
following definition of a structure.
Example :-
structstudent
{
introllno;
charname[80];
intmarks[6];
};
Then the initialization of the array marks done as follows,
struct student s1= {“ravi”, 34, {60,70,80,68,90,75}};
The values of the member marks array are referred as follows,
s1.marks [0] --> will refer the 0
th
element in the marks 60
s1.marks [1] --> will refer the 1st element in the marks 70
s1.marks [2] --> will refer the 2nd element in the marks 80
s1.marks [3] --> will refer the 3rd element in the marks 68
s1.marks [4] --> will refer the 4th element in the marks 90
s1.marks [5] --> will refer the 5th element in the marks 75
9
To create a list of students details and display them.
@2020 Presented By Y. N. D. Aravind 10
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[80];
int marks[6];
int sum;
float per;
};
voidmain()
{
struct student x[20];
int i,n,j;
clrscr();
printf("\Enter no of students [ 1 –20 ] \n ");
scanf(“%d”,&n);
for(i = 0; i < n; i++)
{
printf("\Enter rollno , name of students -%d \n “,i+1);
scanf(“%d %s ”,&x[i].rollno,x[i].name);
Printf(“ Enter marks in six subjects \n”):
for(j = 0; j < 6; j++)
scanf(“%d”, &x[i].marks[j]);
}
for(i = 0; i < n; i++)
{
x[i].sum = 0;
for(j = 0; j < 6; j++)
x[i].sum += x[i].marks[j];
x[i].per = (float) x[i].sum / 6;
}
printf(“ Roll no \t Name \t Percentage \n”);
for(i=0; i < n; i++)
printf(“%3f %20s %9.2f \n”,x[i].rollno,x[i].name,
x[i].per);
getch();
}
Input –Output
Enter no of students [ 1 –20 ]
2
Enter rollno , name of students –1
1Ramesh
Enter marks in six subjects
6879 77 60 91 75
Enter rollno , name of students –2
2Anusha
Enter marks in six subjects
8868 66 60 90 74
Roll no Name Percentage
1Ramesh75.00
2Anusha74.40
Structure Within Structure
@2020 Presented By Y. N. D. Aravind
11
Astructurewhichincludesanotherstructureiscallednestedstructureorstructurewithinstructure.
i.eastructurecanbeusedasamemberofanotherstructure.Therearetwomethodsfordeclaration
ofnestedstructures.
11
1. The syntax for the nesting of the structure is as
follows
struct tag_name1
{
type1 member1;
…….
…….
};
struct tag_name2
{
type1 member1;
……
……
struct tag_name1 var;
……
};
The syntax for accessing members of a nested
structure as follows,
outer_structure_variable .
inner_structure_variable . member_name
2. The syntax of another method for the nesting
of the structure is as follows
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
To illustrate the concept of structure within structure.
@2020 Presented By Y. N. D. Aravind 12
#include<stdio.h>
#include<conio.h>
Struct date
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[80];
float per;
struct date doa;
};
voidmain()
{
struct student x;
clrscr();
printf("\Enter Roll no Name DOB and Per \n ");
scanf(“%d %s %d %d %d %f”,&x.rollno,
x.name,&x.doa.day, &x.doa.month,
&x.doa.year,&x.per);
printf(“ Roll no : %d \n”,x.rollno);
printf(“ Name : %s \n”,x.name);
printf(“ Percentage =:%3.2f \n”,x.per);
printf(“ DOB : %d / %d /%d \n”,
x.doa.day,x.doa.month,x.doa.year);
getch();
}
Input –Output
Enter Rollno Name DOB and Per
1Ramesh20 10 2008 90
Roll no :1
Name : Ramesh
Percentage : 90.00
DOB : 20/10/2008
Self Referential Structure
@2020 Presented By Y. N. D. Aravind
13
Astructurecontaningapointertothesametypeisreferredtoasself-referentialstructure.Itis
usefulforimplementingdatastructuressuchaslinkedlist,queues,stacksandtreesetc..Alinkedlist
consistsofstructuresrelatedtoeachotherthroughpointers.Theselfreferentialpointerinthe
structurepointstothenextnodeofalist.
13
Syntax:-
struct tag_name
{
Type1 member1;
Type2 member2;
……….
struct tag_name *next;
};
Ex:-struct node
{
int data; node
struct node *next;
} n1, n2;
data next
UNION
@2020 Presented By Y. N. D. Aravind
14
Aunionisoneofthederiveddatatypes.Unionisacollectionofvariablesreferredunderasingle
name.Thesyntax,declarationanduseofunionissimilartothestructurebutitsfunctionalityis
different
14
Syntax:-
Union Union_name
{
Type1 member1;
Type2 member2;
……….
............
Typen membern;
}
Unionisakeyword,UnionnameisanyuserdefinednamewhichshouldbeavalidCidentifier.Data
typeisanyvaliddatatypesupportedbyCoruser-definedtype.Member-1,member-2,....,member-n
arethemembersofunion.
Thesyntaxofdeclaringavariableofuniontypeis
Syntax:-
Union Union_name var1,var2,.......................
ENUMERATED DATA TYPE
@2020 Presented By Y. N. D. Aravind
15
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names
to integral constants, the names make a program easy to read and maintain.
The syntax of defining an enumerated type is as follows:
The syntax of declaring a variable of enum type is similar to that used while declaring
variables of structure or union type
Example:-
enum boolean{true, false};
enum boolean t,f;
t= true;
f= false;
The compiler automatically assigns integer digits begining with 0 to all the enumerated
constants. „i.e‟ the enumerated constant true is assigned 0, false is assigned 1
15
Syntax:-
enum identifier{ value-1,varlue-2,......................value-n};
Syntax:-
enum identifier v1,v2,......................vn;
ENUMERATED DATA TYPE
@2020 Presented By Y. N. D. Aravind
16
However, the automatically assignments can be overridden by assigning values
explicitly to the enumerated constants.
enum State {Working = 1, Failed};
Here, the constant working is assigned the value of 1, the remaning constants are
assigned values that increase successively by 1.
16
#include<stdio.h>
#include<conio.h>
voidmain()
{
enum month{ Jan, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec};
enum month year_st, year_end;
clrscr();
year_st = Jan;
year_end = Dec;
printf(“Jan = %d \n”, year_st);
printf(“ Feb = %d \n “, year_end;
getch();
}
Input –Output
Jan = 0
Dec =11
Typedef
@2020 Presented By Y. N. D. Aravind
17
typedefisakeywordusedinClanguagetoassignalternativenamestoexisting
datatypes.Itsmostlyusedwithuserdefineddatatypes,whennamesofthedatatypes
becomeslightlycomplicatedtouseinprograms.Followingisthegeneralsyntaxfor
usingtypedef,
typedef<existing_name><alias_name>;
Letstakeanexampleandseehowtypedefactuallyworks.
typedefunsignedlongulong;
Theabovestatementdefineatermulongforanunsignedlongdatatype.Now
thisulongidentifiercanbeusedtodefineunsignedlongtypevariables.
ulongi,
typedefcanbeusedtogiveanametouserdefineddatatypeaswell.Letsseeitsusewith
structures.
typedefstruct
{typemember1;
typemember2;
typemember3;
}type_name;
Heretype_namerepresentsthestucturedefinitionassociatedwithit.Now
thistype_namecanbeusedtodeclareavariableofthisstucturetype.
type_namet1,t2;
17
Thank You
@2020 Presented By Y. N. D. Aravind
18
Presented By
Y. N. D. ARAVIND
M.Tech, Dept of CSE
Newton’s Group Of Institutions, Macherla