0% found this document useful (0 votes)
2 views

Bpops103 Module 5 Structures Text

The document discusses the structure, union, and enumerated data types in programming, particularly in C. It covers structure declaration, initialization, member access, and the differences between structures and arrays, as well as the use of unions and typedefs. The document provides examples and programming tips for effectively using these data types.

Uploaded by

yuvarajravi456
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Bpops103 Module 5 Structures Text

The document discusses the structure, union, and enumerated data types in programming, particularly in C. It covers structure declaration, initialization, member access, and the differences between structures and arrays, as well as the use of unions and typedefs. The document provides examples and programming tips for effectively using these data types.

Uploaded by

yuvarajravi456
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

15

Structure, Union, and


Enumerated Data Type
TAKEAWAYS
• Stru cture declaration, • Structures and functio ns • Arrays of st ru ct ures • Enumerated
initial ization, and access • Se lf-referentia l struct ures • Unions within structures data type
• Nested structures • Unions • Structure wit hin un ions
• Arrays of unions

i&f ■ INTRODUCTION
char cou rs e[20];
float fees;
};
.-\ structure is a user-defined data type that can store related
information (even of different data types) together. It is Now, the structure has become a user-defined data type.
similar ro records and can be used to store information Each variable name declared within a structure is called
about an entity. The maj or difference between a structure a member of the structure. The structure declaration,
and an array is that an array contains related information however, does not allocate any memory or consume
of the same data type. storage space. It just gives a template that conveys to the C
A suucture is, therefore, a collection of variables under compiler how the structure should be laid out in memory
a single name. The variables within a structure are of and gives details of the member names. L ike any other
different data types and each has a name that is used to data type, memory is allocated for the structure when we
select it from the structure. declare a variable of the structure. For example, we can
define a variable by writing
15.1.1 Structure Declaration struct student studl;
A structure is declared using the keyword struct followed Here, struct student is a data type and studl is a
by the structure name. All the variables of the structure are variable. Look at another way of declaring variables. In
declared within the structure. A structure type is generally the following syntax, the variable is declared at the time
declared 'by using the fo llowing syntax: of structure declaration.
struct struct-name struct student
Programming Tip: { {
Do not forget t o data_type var-name; int r_no;
place a semicolon data_type var'- name; char name[20];
after the definition of
char course[20];
structures and unions. }; float fees;
For example, if we have to define a structure for a }studl, stud2;
student, then the related information probably would be: In this declaration we declare two variables studl
roll_number, name, cour se, and fees, This structure and stud2 of the type student . So if you want to declare
can be decl ared as : more than one variable of the structure, then separate the
struct student variables using a comma.
{ When we declare variables of the structure, separate
int r_no; memory is allocated for each variable. This is shown in
Figure 15 .L
char name[20];
,1H1
Structuro, Union, 11n<I [ numcr.itt!d O.H.J
Type

1- ~ --
solution
, t ruc t \ tuden t st ud l ;
Protrammln1 Tip: 1tru c t 000K
J r;; l ~ Use different member
names for different cl'lar tlllP .[20 ],
~
C-
c =='.7~,--co_u_r~-c-) structures for darlly. char autl1 0r[2 0/;
lnt pages;

~ noat prlc e;
lnt yr_o F_publlcat lon ;
struct student stud 2) };

- -~ ~
~~ Enmple JS.S
d
Decla re a structure to create an inventory recor
Solution
struct inve ntory

varia bles char prod_name(20 ];


Figure 15.1 Memory alloca tion fo r structure
noat prlc e;
int s tock;
Lt't us St'C some more slniclurc declarations.
};
Example 1S.1
point in the
Decla re a structure to store inform ation about a
coord inate syste m. m lture type and variable declaration of a structure can
Struc
Solution ment in
struc t poi nt be either local or globa l depending on their place
{ the code.
int x, y;
and nam es
Last but not the least, structure mem ber names
};
laid down for the
of the structure follow the same rules as
Example 15.Z shou ld be taken
names of ordinary variables. However, care
name of a struc rure
Declare a structure to store customer informatio
n. to ensure that the name of structure and the
name
member should not be the same. Moreover, struc ture
Solution
and its variable name should also be different.
st ruct customer
{
i nt cust_i d; 15.1.2 Typ ede f Declarations
char name(20] ; The type def (derived from type
char address (20] ; Programming Tip: definition) keyword enables the
l ong i nt phone_num ; C does not allow programmer to create a new
int DOB; decla ration of data type name from an existing
}; variables at the data type. By using typedef ,
time of creating a no new data is created. rather
Example 15.3 typedef definition. an alternate name is given to a
So variables must known data type .
ular date.
Declare a structure to store information of a partic be declared in The general syntax of using
Solution an independent the type def keyword is given
stru ct date statement. as:
{ e
int day; t ypedef exis ting dat a_ty pe new data _typ
int month; any memory.
. ~ote that typedef statement does not occupy
int yea r ; exam ple, if we write
1t simply defines a new type. For
};
typedef int I NTEGER;
Example 15.4 To declare
then INTEG ERis the new name of data type int.
data type name , prec ede the
Declare a structure to store information of a partic
ular book. varia bles using the new
Comp11IP1 I undamentals and Programming In C

\ .\m\bl<.' "'""'-' 111th lht· J111t1 t) pl' 1w111c (11cw). l'hcrcforc. data_type membe
r
lo tkf111c n11 intqwr , 111rnblc. 11 c 11111y m1w write Programming Tip:
dat a_type membe - name1;
It Is an error to assign r nam
data_type membe - ei ;
lNTl.GER num-'i ; a structure of one
. . . . . . .. . . . . ...r _name3.
. . '
type to a structure of
\\ hl'n II c p1~ccJI.' 11 s l r uc t nu111e wi th typedef };
kl'~" nn_l. thcn thl.' struc t hcco111cs n 11cw type. II i~ used another type.
''.' make the Ct111~1111c1sh11rtcr with 111orc 111eo11i11gl'u l nunics struct struct _name struct_var = {constanti
11,r \~pcs olrcndy dctincd hy (' or fu r types thut you huvc constant 2, constant 3, ... }; '
~c,:l:,rc,I. A typedef dcd 11rntk111 is n sy11011y111 for the type.
hw c, amplc. writing For example. we can in itialize a student stru t
c urc b
writi ng Y
t ypedef st1'uct student
{ st ruct student
i nt 1·_no; {
char name[20) ; int r_no ;
char cour se [ 20]; char name(20];
floa t fees; char course(20];
}; float fees;
}studl = {01, "Rahul", "BCA", 45000};
Now that you have preceded the structure 's name with
the keyword typedef, student becomes a new data type. or by writing
T~e~fore, now you can straightaway declare variables
struct student studl = {01, "Rahul", "BCA",
ot this new data type as you declare variables of type
45000};
int , float, char, double, etc. To declare a variable of
structure student you will just write Figure 15.2 illustrates how the values will be assigned
student studl; to the individual fields of the structure.

Note that we have not written struct student studl.


struct student stud
= {01, "Rahul", "BCA", 45000};
15.1.3 Initialization of Structures
A structure can be initialized in the same way as other
01 I I Rahul I I BCA I I 45000 )
r_no name course fees
data types are initialized. Initializing a structure means
assigning some constants to the members of the structure. struct student stud2 = {07, "Rahul"};
When the user does not explicitly initialize the structure ,
then C automatically does that. For int and float members,
the values are initialized to zero and character and string 07 I I Rahul I I \0 II 0.0
members are initialized to '\0' by default (in the absence r_no name course fees
of any initialization done by the user).
The initializers are enclosed in braces and are separated Figure 15.2 Assigning values to structure members
by commas . However, care must be taken to see that the
initializers match their corresponding types in the structure When all the members of a structure are not initialized, it
definition. is called partial initialization. In case of partial initialization,
The general syntax to initialize a structure variable is first few members of the structure are initialized and those
given as follows: that are uninitialized are assigned default values.
struct struct_name
{
15.1.4 Accessing the Members of a Structure
data_type member_namel; Programming Tip: Each member of a structure
data_type member_name2; Amember of the can be used just like a normal
data_type member_name3; structure cannot be variable, but its name will be a
accessed directly using bit longer. A structure member
}struct_ var = {consta ntl, constant2, its name. Rather you variable is generally accessed
constant 3, ... }; must use the structure using a ' . ' (dot) operator. The
name followed by syntax of accessing a structure
OR
the dot operator or a member of a structure can
struct struct_name before specifying the be given as follows:
{ member name.
struct_var.member_name
~Wt ; rs I

'
Struct1 1r,:, Unio n, ,ind En11mc>r,1 t11d O.;ita Type
•ruto r is used to sel ect a pa rticula r me h
I1it oPL: . • r, r cxnmp Ic. to uss1g . n va lue 111 e r
. •• 1 0 1o 11,e s t ruct studen t studl
111 •1n1~t111 l,;. f I " (01, "Rahul", "BCA" , 4~000} ;
. 111i: ~ i
d• t:t ,ne mbc rs o t 1e struc ture variabl e 5 t udl
,,1 , •ll· tu :11
I1
1111 , 11

ri ti.:
,
[ 01 I I R11h ul j [ J [ 4~r)l'JfJ ]
E,('A
, 11111~ r _no f ee -:;
no = 01 ; name course
1, 1
tud 1 · r - "Ra hul ";
s dl name = = "BCA"; struct studen' t stud2 "' stud1 ;
tli .
s dl course
stU · fees = 45000 ;
t udl. [ 01 I I Rnhul j I B CA [ 45()()() ]

s . JUI values for data me mbe rs o f the structu re r_no name course fees
, ,, 1111 dl we may write
. tile stu ,
I ;lfl:l Figure 15.3 Copying values of structu re variab les
f("%d" , &stud l.r_no );
scan f("%s " , s tu d l .name ) ,.
5 can C does not pe rmit compa rison of o ne s tructu re
. . , rl)' 10 print the va lues o f structu re variabl e
s1111•.11 • . va riable with anot her. Howev er. ind ividua l memb ers o f
we 111 ay w nte one structu re can be com pa red wit h indi v idual memb ers
5cudl,
. tf("%s ", studl . course ); of anothe r structu re. When we compa re o ne struct ure
Po . ntf("%f " , studl. fees); membe r with anothe r s tructu re·s me mber. the comp arison
pr1n
will beha ve like any other o rdinary variab le compa rison.
M.e(llory is allocat ed only when we declare variabl es For examp le, to compa re the fee s of two studen ts. we
1
• e cture. In other words, memor y is allocat ed only will write
ot t1l 51111 .
"•hen we instant iate th~ ~tru~~ re. In the absenc e of any
variable, structu re defimt ion 1s Just ~ templa te that will be if(stu dl.fee s > stud2 .fees )
used to reserve memo ry when a vanabl e of type struct is / / Fees of st udl i s gr eat e r t han stud2
declared.
Once the variabl es of a structu re are defined, we can 15.1.6 Finding the Size of a Struc ture
perform a few operat ions on them. For examp le, we can In this section, we will read about three differ ent w ays
use the assignm ent operat or · = • to assign the values of one through which we can find the numbe r of bytes a structu re
variable to anothe r. will occupy in the memor y.

Ill
Of all the operato rs -> ,.,(), and [] have the highest
Simple Addit ion
In this techniq ue, we w ill make a list of all data types
priority. This is eviden t from the following statem ent:
and add the memor y require d by each. For ex am ple, let' s
studl.f ees++ will be interp reted as (studl . conside r a simple structu re of an emplo yee.
fees)+ + struct Employee
{ intemp _ID;
15.1.5 Copying and Comp aring Structures char name[2 0];
double salary ;
We can assign a structu re to anothe r structu re of the char design ation[ 20] ;
same type. For examp le, if we have two structu re float experi ence;
variables studl and stud2 of type struct studen t };
given as
Now, Size = size of emp_ID + size of name + size o f
struct studen t studl salary + size of design ation + size of exper ience
Programming Tip:
{01, "Rahu l", "BCA",
An error will be Size of emp_ID = 2
45000} ;
generated if you Size of name = 20 x size of charac ter
struct studen t stud2;
try to compar e two Size of salary = 8
structure variables. Then to assign one structure Size of design ation = 20 x size of charac te r
variabl e to another we will write, Size of experi ence= 4
stud2 = studl.,
Theref ore, Size =
· · · · zes the membe rs o f stud2 w1'th
theThis statemen t m1tiah x l +4
f h = 2 + .20 x I + 8 + 20
Yalu Values O membe rs of studl. Theref ore, now t e = 2 + 20 + 8 + 20 + 4
es of s t ud1 and stud2 can be 01ven as shown •m
.
Fio..,. 0 = 54 bytes
.,.... e 15 .3. •
\I
gramming in C
Computer Fundamentals an d Pro * address of the first element of secorid
/
employee *I
Using sizeof Operator end = &e[l].emp_ID;
· d to ca lculate
As discussed earlier. sizeof opera tor 1s use . To use l en = end - start;
. , ·css1on
the size of a data type. va rn1ble, or an cx pi ·. pr i ntf( "\n Size of the structure = %d",
this operator simpl y write. sizeof ( struct _name), . 0 r
th l en);
For examp le. the code given below pri nts c size
structure Empl oyee. }

#in clude cs td i o. h> Outpu t


#include <conio. h> Si ze of t he structure = 54
t ypedef struct Employee
using structures to read a n d ~
{ i nt emp_ID; 1 Write a program p ay th e
char name[ 20] ; · info rmation abo ut a student.
dou ble salary;
#i ncl ude cstdi o.h >
char designation[ 20] ;
float exper·ience; #i nclude cconio.h >
\ .
J ,
i nt mai n()
{
void main() st ruct student
{
{
struct Employee e;
int roll_no;
print f ("\ n %d", si zeof (e) );
}
char name[80];
float fees;
Output char D0B[80];
54 };
struct student studl;
clrscr();
Syntax of sizeof operator is similar to that of a function printf("\n Enter the roll number : ");
but sizeof is not a library function. It is an operator in C. scanf("%d", &studl.roll _no);
printf ( "\n Enter the name: ");
scanf("%s", studl.name) ;
Subtracting the Addresses printf( "\n Enter the fees: ");
scanf("%f", &studl.fees );
In this technique, we use an array of structure variables.
Then we subtract the address of first element of next printf( "\n Enter the DOB: ");
consecutive variable from the address of the first element scanf("%s", studl.DOB);
of preceding structure variable. For example, the code printf("\n *******STUDENT'S DETAILS
below finds the size of structure Employee. ******* .. );
printf("\n ROLL No. = %d", studl.roll_n o);
#include <stdio.h>
printf("\n NAME = %s", studl.name) ;
#i nclude <conio.h>
printf("\n FEES= %f", studl.fees) ;
typedef struct Employee
printf("\n DOB= %s", studl.DOB);
{ int emp_ID;
getch();
char name[20);
return 0;
double salary;
}
char designation[20);
float experience; Output
};
Enter the roll number: 01
void main() Enter the name : Rahul
{ Enter the fees: 45000
struct Employee e[S); Enter the DOB : 25-09-1991
int start, end, len; *******STUDENT'S DETAILS*******
ROLL No. = 01
/* address of the first element of first
NAME= Rahul
employee*/
FEES= 45000.00
start= &e[0].emp_ID;
DOB= 25-09-1991
Stru cture • Unon,
I
;ind Enumer,Hed Dau Type
arn using structures to find the la
. a pro gr ' rges t of
write befS. ,. a :;p l :
i, ee oofll
tJ'll' <stdio.h> Pr l ntf( "\n Fn , ,..r r· ho r.n,, I Mid JmagJ:l'tc1ry
1ude p,) r t -; nf t h;, l'tr ,; I r() mp l .,.,, n u ml'J.,f' : ") ;
11inc <conio. h>
5
11inclU~e () Ci1nf ("%<1 :'M " , R. r l . rf'-J I, P. r: J . lm.:i ~),
int rna1n pr l nU( "\ n rnt <1r th "' ,... .. .,.1 ,inrl im,;i~ln..:t r /
p.:i rtc; o F th., <.Prnn rl rfltn p ' "'"' n 111nt1"'r ") ,
{ t numbers sc .:inf ("%d %(1 " , 11. r J .r.,,il, 11,,.-J , Lm.:i~J,
st rue
break;
{ b
int a , , ~
c Ci1 Se 2 :
. t 1argest,
1n pr i ntF( "\ n Th e Fir s t complP,c numb""r t-; :
%d ► %dl " , c l.r e al, c l . i mag );
}; ict numbers num; pr :lntF( "\ n Th e seco nd compl ex numb~r i:; :
5trL
%d + %d l", c2.re a l, c2.l mag);
clrscr();
. tf( "\n Enter the three numbers.· ")., break ;
pr1n case 3 :
scanf(" %d %d %d", &num.a, &num.b, &num.c);
s um_c. real ~ c l . real ► c 2 . real ;
if (num.a > num.b && num.a > num.c)
s um_c.i mag ~ cl .i mag + c2.l mag ;
num . largest = num.a;
pr i nt f (" \ n The s um of t wo compl ex number s
if ( num.b > num.a && num.b > num.c) is : %d + %di" , sum_c. real, sum_c.i mag );
num.largest = num.b; break;
if (num.c > num.a && num.c > num.b) case 4 :
num.largest = num.c; sub_c.real = c l .real - c2.real;
printf ( "\n The largest number is: %d", num. sub_c . imag ~ cl .l mag - c 2 . i mag;
largest); printf( "\ n The d iffere nce between t wo
getch(); complex number s is: %d + %d i",
return O; sub_c.real, sub_c .i ma g );
break;
}
Output }while(option != 5);
getch();
Enter the three numbers: 7 9 1 return O;
The largest number is: 9 }

3. Write a program to read, display, add, and subtract two Output


complex numbers.
***** MAIN MENU******
#include <stdio. h> 1. Read the complex nos
#include <conio.h> 2. Display the complex nos .
int main() 3. Add the complex nos.
{ 4. Subtract the complex nos.
typedef struct comp_lex 5. EXIT
{ Enter your option: 1
int real; Enter the real and imaginary parts of the first
int imag; complex number: 2 3
}COMPLEX; Enter the real and imaginary parts of the
COMPLEX cl, c2, sum_c, sub_c; second complex number : 4 5
int option· ***** MAIN MENU******
clrscr(); ' 1. Read the complex nos.
do 2. Display the complex nos.
{ 3. Add the complex nos.
Printf("\n ***** MAIN MENU *****"); 4. subtract the complex nos.
Printf("\n 1. Read the complex nos."); 5. EXIT
Printf("\n 2. Display the complex nos."); Enter your option: 3
Printf("\n 3 . Add the complex nos."); The sum of two complex numbers is : 6 + 8i
Printf("\n 4. Subtract the complex nos.");
Printf("\n 5. EXIT"); 4. Write a program to enter two points and then calculate
Printf("\ n Enter your option: "); the distance between them.
scanf("%d"
s . , &option); #include <stdio.h>

.....:....__ W1tch(option) #include <conio.h>


:wz Computer Fundamcnt.il<. and r wRr,1mm 1nR111 f

• includ e , ma\h h• typed f'f s tr uct


il'lt 111aifl( , (
{ I nt dd;
l t1t mm;
in t yy;
}DA rE;
'i "'' ' . ' .
'~C•l 1\11 •
" N ~'l 1\l , r:. typede f str uct st udent
-1,,.,.t ,'h ~ t ~nc- e . {
dr s,q, . lnt r _no;
l'rint f('\n Enter the coordl nat es of t he fi r st NAME name;
N ln't " ', char course(20 );
scanL1,.'' \.d \.d ", &.p l. x , &pl.y ); DATE DOB;
c,rint f("\n Enter the coordinates of the noat fees;
seconJ point . "); };
s.:: anfC \.d \.d' . &_p 2. , , StJ2. y ) ;
di st ance = sqrt(p ow((p l . x - p2.x) , 2) + In this exampl e, we see that the structure st
pow(( pl. \ - p2.y) , 2)) ; contains two other ~tructures- NAME and DATE . Both uden
the~

c, r1ntf ("\n The coordinates of t he firs t point structures ha ve their own fie lds. The structure NAME ,
ar e . \d, \dy ·, pl . x, pl. y); three fields: first_name, m1. d_name, an d l ast _name. The
nas
~r1nt fl·\n The coord inates of the second structure DATE also has three fields: dd, mm, and yy, which
porn~ ar-e : \d x Xdy ", p2 .x, p2 .y); specify the day, month , and year of the date. To assign
orin'tf ( "\n Dista nc e between pl and p2 = %f", values to the structure fields, we will write V

di stanc e) ; stude nt studl ;


getch (}; studl.name.first_name = "Janak";
r eturn O; studl.name.mid_name = "Raj";
}
stud 1. name. last_name = "Thareja";
OutpUI studl. cours e = "BCA";
studl.DOB.dd = 15;
Enter t he coordinates of the first point: 2 3 studl.DOB.mm = 09;
Enter t he coord inates of the second point: 9 9
studl.DOB.yy = 1990;
The coor-clinat es of the first point are: 2x 3y
studl .fees = 45000;
The coord inate s of the second point are: 9x 9y
Distanc e betwee n pl and p2 = 9.219544 In case of nested structures, we use the dot operator
in conjunction with the structure variables to access
the members of the innermost as well as the outennosr
iif j NESTED STRUCTURES structures. The use of nested structures is illustrated in th~
following program:
A structure can be placed within another structure, i.e., a
structure may contain another structure as its member. A 5. Write a program to read and display infonnation of a
structure that contains anothe r structure as its member is student using a structure within a structure.
called a nested structure.
#include <stdio.h>
Let us now see how we declare nested structures or
structures that contain structures. Although it is possible #include <conio.h>
int main()
to declare a nested structure with one declaration, it is not
{
recommended. The easier and clearer way is to declare
the structures separately and then group them in a high- struc t DOB
{
level structure. When you do this, take care to check that
nesting is done from inside out (from lowest level to the int day;
most inclusive level), i.e., to say, declare the innermost int month;
structure, then the next level structure, working towards int year;
};
the outer (most inclusive) structure.
typed ef struc t struc t studen t
{
{
char first_name[20]; int roll_n o;
char mid_name[20]; char name[lOO];
char last_name[20]; float fees;
struc t DOB date;
}NAME; };
T e
Structure, Union, and Enumerated Data VP

struc t student stud l ; s truct s truct _name


c1rscr(};
print f( "\ n Enter the r'ol l number : ") : data_type member_name l;
sc:rnf ( "\d " . &studl.roll _no): data_t ype membe r _name2:
printf(" \ n Enter the name : "); data_type mcmbcr_name 3;
, can f(" \ s". studl.name) ; . . .... . .... . .. .. . .. .. . .
~r intf (" \n Enter the fees : "); };
,canf("\f", &studl .fees) ; s truc t s truct_name s tru ct _var[i ndex);
-,rintf(" \n Enter the DOB : "); Cons ider thl· ~,,-rn s1mc1un: 1.kti11111,,n
~sc anf( "\d \d ~~d " , &s tu d l.date.day,
&studl.date.m onth , &studl.date .year ); s truct s tudent
printf( "\n ••••• STUDENT'S DETAILS ..... .. ) ;
print f(" \ n ROLL No. = Xd" , studl . roll_no) ; int r _no;
print f(" \n NAME = Xs ", studl.name) ; char name [ 20] ;
printf (" \n FEES= %f" , studl.fees) ; char cour se(20);
printf ( "\n DOB= %d - %d - %d", studl.date. noat fees ;
day , studl.date.mo nth , studl.date.ye ar ); };
get ch(); r\ student nrroy con be dednrcd simpl~ by writing
return O;
student stud( 30);
}
Now. t0 nssign ,·nlues 10 t.hc i'h student 0f the clnss. \\'\:'
Output
will write.
Enter the roll number: 01
Enter the name: Rahul stud[i].r_no = 09 ;
Enter the fees: 45000 stud[i].name = "RASH!";
Enter the DOB : 25 09 1991 stud[i].cours e = "MCA";
***** STUDENT'S DETAILS***** stud[i].fees = 60000 ;
ROLL No. = 01 In order to initialize t.he u.rrJy of structure \'Uriables at
NAME = Rahul t.he time of declaration. you should \'Hite as follows:
FEES = 45000. 00
DOB= 25-09-1991 student stud[3] = { {01, "Aman", "BCA",
45000},{02, "Aryan", "MCA", 60000}, {03,
"John", "BCA", 45000}};

, , , . ARRAYS OF STRUCTURES 6. Write a program to read and display the infommtion of


all the students in the class.
In the aforegiven examples, we have seen how to declare a
#include <stdio.h>
structure and assign values to its data members. Now we will
#include <conio.h>
discuss how to declare an array of a structure. For this pUipOse.
int main()
let us first analyse, where we would need array of strnctures.
{
In a class, we do not have just one student. But there
struct student
may be at least 30 students. So the same definition of the
{
structure can be used for all
Programming Tip: int roll_no;
t.he 30 students. This would
It is an error to omit char name[80);
be possible when we create
array subscripts when int fees;
an array of the structure. An
refe'rring to individual char DOB[SO];
array of a structure is declared
structures of an array };
of structures. in the same way as we declare
an array of a built-in data type. struct student stud[SO];
int n, i;
. _Another example where an array of structures is desirable
clrscr();
is m case of an organization. An organization has a number
printf("\n Enter the number of students: ");
of employees. So, defining a separate structure for every
scanf("%d", &n);
employee is not a viable solution. So here we can have a
for(i = O;i < n;i++)
~o~on structure definition for all the employees. This can
{
gam be done by declaring an array of the structure employee.
The general syntax for declaring an array of a structure printf("\n Enter the roll number: ");
can be given as sc~nf("~d", &stud[i).rol l_no);
pr1ntf( '\n Enter the name: ");
......__
Structure, Union, and Enumerated Data Type

011t p11t 15.4.1 Passing Individual Members


Enter t he number of s tudent s : 2 To pass any indi vidua l member of the ~tructure to a
Enter the roll number: 1 function we must use the di rect selection operator to
E11te1· the name : kirti refe r to the indi vidual members for the actual parameter~.
Enter the fees : 5678 The called program does not know if the two vartables
Enter the DOB: 9 9 91 are ordinary variables or structure members. Look at the
Ent er t he rol l number : 2 following code that il lustrates this concept.
Enter the name : kangana
Enter the fees : 5678 #inc l ude <s tdio . h>
Enter the DOB: 27 8 91 t ypede-f struct
•* •* •• ••DETAI LS OF STUDENT 1•• •• • • • • {
ROLL No. = 1 int x;
NAME = ki r ti i nt y;
FEES = 5678 }POINT;
DOB = 9 9 91 voi d di splay (int , int) ;
** ******DETAILS OF STUDENT 2******** i nt main( )
{
ROLL No. = 2
POINT pl = {2, 3};
NAME= kangana
display(pl.x, pl.y );
FEES = 5678
return o;
DOB= 27 8 91
Enter the roll no. of the student whose record }
void display(int a, int b)
has to be edited: 2
Enter the new roll number: 2 {
printf("The coordinates of the point are : %d
Enter the new name: kangana khullar
Enter the new fees : 7000 %d", a, b);
}
Enter the new date of birth: 27 8 92
********DETAILS OF STUDENT l******** Output
ROLL No. = 1
NAME= kirti The coordinates of the point are : 2 3
FEES= 5678
DOB= 9 9 91 15.4.2 Passing the Entire Structure
********DETAILS OF STUDENT 2******** Just like any other variable, we can pass an entire structure
ROLL No. = 2 as a function argument. When a structure is passed as an
NAME= kangana argument, it is passed using the call by value method, i.e.,
FEES= 7000 a copy of each member of the structure is made. This is
DOB= 27 8 92 a very inefficient method especially when the structure
is very big or the function is called frequently. In such a
situation, passing and working with pointers may be more
f fjj STRUCTURES AND FUNCTIONS efficient.
The general syntax for passing a structure to a function
and returning a structure can be given as
For structures to be fully useful, we must have a mechanism
to pass them to functions and return them. A function may struct struct_name func_name(struct struct_
access the members of a structure in three ways as shown name struct_var);
in Figure 15.4. This syntax can vary as per need. For example, in some
situations we may want a function to receive a structure
but return a void or value of some other data type. The
Passing individual
members · following code passes a structure to the function using the
call-by-value method.

Passing structures Passing the #include <stdio.h>


to functions entire structure typedef struct
{
Passing the address int x;
of the structure int y;
}POINT;
Figure 15.4 Passing structures to functions void display(POINT);
Computer Fundamentals and Programming in C
printf("\n The sum of two distances
ma in() is: %d kms %d metres", d3.kms, d3.metres );
{
POINT pl= {2, 3}; break;
display(p l ); case 4:
d4 = subtract_ distance( dl, d2);
return O;
printf ( "\n The differe~c e betwe:n two
}
distances is: %d kms %d metres, d4. kms,
void display(POINT p)
{ d4.metres );
printf("%d %d", p.x, p.y); break;
}
}while(op tion != 5);
8. Write a program to read. di splay, add, and subtract two getch();
distances . Distance must be defined using kms and return o;
metTes. }
DISTANCE add_distance(DISTANCE dl, DISTANCE d2)
#include <s tdio . h>
#include <conio.h > {
t ypedef struct distance DISTANCE sum;
sum.metre s= dl.metres + d2. metres;
{
int kms ; sum.kms = dl.kms + d2 .kms;
int metres ; if(sum.me tres >= 1000)
}DISTANCE; {
DISTANCE add_distance(DISTANCE, DISTANCE); sum.metre s= sum.metres%1000;
DISTANCE subtract_distance(DISTANCE, sum.kms += 1;
DISTANCE); }
DISTANCE dl, d2, d3, d4; return sum;
int main() }
{ DISTANCE subtract_distance(DISTANCE dl,
int option; DISTANCE d2)
clrscr(); {
do DISTANCE sub;
{ if(dl.kms > d2.kms)
printf("\n ***** MAIN MENU*****"); {
printf("\n 1. Read the distances "); sub.metre s= dl.metres - d2. metres;
printf("\n 2. Display the distances "); sub.kms = dl.kms - d2.kms;
printf("\n 3. Add the distances "); }
printf("\n 4. Subtract the distances "); else
printf{"\n 5. EXIT"); {
printf("\n Enter your option: "); sub.metre s= d2.metres - dl. metres;
scanf("%d", &option); sub.kms = d2.kms - dl.kms;
switch(op tion) }
{ if(sub.me tres < O)
case 1: {
printf("\n Enter the first distance in sub.kms = sub.kms - 1;
kms and metres: "); sub.metre s= sub.metre s+ 1000;
scanf("%d %d", &dl.kms, &dl.metre s); }
printf("\n Enter the second distance in return sub;
kms and metres: "); }
scanf("%d %d", &d2.kms, &d2.metres);
Output
break;
case 2: ***** MAIN MENU*****
printf("\n The first distance is: %d 1. Read the distances
kms %d metres", dl.kms, dl.metres ); 2 · Display the distances
printf("\n The second distance is : %d 3. Add the distances
kms %d metres", d2.kms, d2.metres ); 4. Subtract the distances
break; 5. EXIT
case 3: Enter your option: 1
d3 = add_dista nce(dl, d2); Enter the first distance in kms and metres: 5 300
Structure, Union, and En umerated Data Type .._,...
397

Enter the second dista nce i n km s and met res : prlntf( "\ n The ~um of t he two time
3 400 value s l s : %d hr %d mln Xd sec", t3.h r,
.. •·•• MAIN MENU • H • • t3 . mi n, t 3 . sec) ;
1. Read the di sta nces break;
2. Display the distances case 4:
3. Add t he distances t4 = subtract_ti me(tl, t2);
4. subtract the distance s pr i ntf( "\ n The difference in time
s. EXIT is: %d hr %d mi n %d sec " , t4.hr, t 4 . min ,
Enter you r option: 3 t4 . sec);
The sum of two distances is: 8 kms 700 metr es break ;
}
9. Write a program to read. display. add , and subtract }while(option != 5) ;
two time variables defi ned using hours, minutes, and get ch();
seconds. return O;
#include <stdio.h>
#include <conio . h> TIME add_time(TIME tl, TIME t 2)
t ypedef struct {
TIME sum;
{
sum.sec= tl.sec + t2.sec;
int hr;
while(sum.sec >= 60 )
int min;
{
int sec;
sum . sec -=60;
}TIME;
sum.min++;
TIME tl, t2, t3, t4;
TIME subtract_time(TIME, TIME); }
sum.min= tl.min + t2.min;
TIME add_time(TIME, TIME);
while(sum.min >= 60)
int main()
{
{
sum . min -=60;
int option;
sum.hr++;
clrscr();
}
do
sum.hr= tl.hr + t2.hr ;
{
return sum;
printf("\n *** * MAIN MENU ****");
}
printf("\n 1. Read time ");
TIME subtract_time(TIME tl, TIME t2)
printf("\n 2. Display time");
{
printf("\n 3. Add");
TIME sub;
printf("\n 4. Subtract");
if(tl.hr > t2.hr)
printf("\n 5. EXIT");
{
printf("\n Enter your option: ");
if(tl.sec < t2.sec)
scanf("%d", &option);
{
switch(option)
tl.sec += 60;
{
tl.min--;
case 1:
}
printf("\n Enter the first time in
sub.sec= tl.sec - t2.sec;
hrs, mins, and secs: ");
if(tl.min < t2.min)
scanf("%d %d %d", &tl.hr, &tl.min, &tl.sec);
{
printf("\n Enter the second time in
tl. min += 60;
hrs, mins, and secs: ");
tl.hr- -;
scanf("%d %d %d", &t2 . hr , &t2.min, &t2 .sec);
}
break;
sub.min= tl.min _ t2.min;
case 2:
sub.hr= tl . hr - t2.hr;
printf("\n The first time is : %d hr %d min
}
%d sec", tl.hr, tl.min, ti.sec);
else
printf("\n The second time is: %d hr %d
{
min %d sec", t2.hr, t2.min, t2.sec);
if(t2.sec < tl.sec)
break;
{
case 3:
t2.sec += 60;
t3 = add_time(tl, t2);
Computer Fundame ntals and Progra mm ing in C

t2 .min --; through pointers. rt i~ possible to create a poin~er to atino


e in c including user-defined types. It 1s extr st
} nn Y typ , . . . erne1y
. non to c reate pointers to structures. As m other
sub.sec e t 2. sec - t l .s e c; co m• . If cases
if(t 2. min, tl.min) 0
pointer to a stru cture is never 1tse a structure, but rnerel,
{ u va riabl e that ho lds the address of a struc~re. The synt Y
t2.min + ~ t,Q ; to declare a pointer to a structure can be gwen as follow:~
t.::..111- - - ; st ruct str uct name
}
{
sub.min= t 2 .min - tl.min; data_type member_ namel;
sub.hr = t2.h1' - tl.111·; data_type member_name2;
} data _type member_name3;
return sub ; .. . . . .................
}*ptr;
Output
OR
• • •· .. MAIN MENU • .. • •
struct struct_name *ptr;
1. Read time
2 . Displ ay time For our student structure, we can declare a pointer
3. Add variable by writing
4. Subtract
5. EXIT
struct student *ptr_stud, stud;
Enter your option: 1 The next thing to do is to assign the address of stud to
Enter the first time in hrs, mins, and secs: the pointer using the address operator (&) as we would do
2 30 20 in case of any other pointer. So to assign the address, we
Ente r t he second time in hrs, mins, and secs: will write
3 20 30
**** MAIN MENU****
ptr_stud = &stud;
1. Read time To access the members of the structure, one way is to
2. Display time write
3. Add
4. Subtract /* get the structure, then select a member*/
5. EXIT (*ptr_stud).roll_no;
Enter your option: 3
Programmi~g Tip:: Since parentheses have
The sum of the two time values is: 5 hr 50 min
The sefection ,.- : · a higher precedence than *,
50 sec
.. iiperator (->) is 'a writing this statement would
Let us summarize some points that must be considered ~single token, so,do work well. But this statement
while passing a structure to a function. · not piace any white is not easy for a beginner to
• If the called function is returning a copy of the entire space between them: work with. So C introduces a
._,_ · ..: new operator to do the same
structure then its return type must be declared as struct
task. This operator is known as the pointing-to operator
followed by the structure name.
( ->) . Here it is being used:
• The structure variable used as parameter in the function
declaration must be the same as that of the actual /* the roll_no in the structure ptr_stud
argument in the called function ( and that should be the points to*/
name of the struct type). ptr_stud -> roll_no = 01;
• When a function returns a structure then in the calling
function the returned structure must be assigned to a This statement is far easier than its alternative.
structure variable of the same type.
10. Write a program, using a pointer to a structure to
15.4.3 Passing Structures initialize the members of the structure.
Programming Tip:
Using pointers to Through Pointers #include <stdio.h>
pass a structure to #include <conio.h>
Passing large structures to struct student
.a function is m·ore .
functions using the call-
F' efficient tlian using . by-value method is very
{
the ·cal!-by-.v alue int r_no;
inefficient. Therefore, it is char name[20];
m·e thod .. preferred to pass structures char course[20];
Structure, Un ion, and Enumerated Data Type 399

int fees; DETAILS OF SECOND STUDENT


}; ROLL NUMB ER = 02
NAME = AdJ. tya
int main() COUR SE = MCA
FEES = 60000
struct stude nt studl, stud2, •ptr_studl,
11 . Write a program, usi ng a pointer to a stru cture, to
•ptr_stud2 ;
initialize the membe rs of the structure using an
clr·scr();
ptr_st udl &studl ; alterna ti ve technique.
ptr_s tud 2 &stud2 ; ttinclude cstdio . h>
ptr_s tudl -> r_no = 01 ; tt i ncl ude cconio.h >
strcpy(ptr_s tudl - > name , "Rahul"); struct stude nt
strcpy(ptr_s tudl - > course, "BCA");
ptr·_studl -> fees = 45000; int r _no;
char name[20] ;
printf("\n Enter the details of the second char course[20];
student:"); float fees;
printf("\n Enter the Roll Number="); };
scanf ( "%d ", &ptr_stud2 - > r_no);
printf("\n Enter the Name="); int main()
gets(ptr_stud2 -> name); {
printf("\n Enter the Course="); struct student *ptr_studl;
gets(ptr_stud2 -> course); struct student studl = {01, "Rahul", "BCA",
printf("\n Enter the Fees="); 45000};
scanf("%d", &ptr_stud2 -> fees); clrscr();
ptr_studl = &studl;
printf("\n DETAILS OF FIRST STUDENT"); printf("\n DETAILS OF STUDENT");
printf("\n ROLL NUMBER= %d", ptr_studl -> printf("\n ROLL NUMBER= %d", ptr_studl - >
r_no); r _no);
printf( "\n NAME= %s", ptr_studl -> name); printf("\n NAME= %s ", ptr_studl -> name);
printf("\n COURSE= %s", ptr_studl - > printf("\n COURSE= %s", ptr_studl
course); -> course);
printf("\n FEES= %d", ptr_studl -> fees); printf("\n FEES= %.2f", ptr_studl -> fees);
printf("\n\n\n\n DETAILS OF SECOND return O;
STUDENT"); }
printf("\n ROLL NUMBER= %d", ptr_stud2 ->
Output
r _no);
printf("\n NAME= %s", ptr_stud2 -> name); DETAILS OF STUDENT
printf("\n COURSE= %s", ptr_stud2 -> ROLL NUMBER= 01
course); NAME= Rahul
printf("\n FEES= %d", ptr_stud2 -> fees); COURSE= BCA
FEES = 45000.00
return o;
} 12. Write a program, using an array of pointers to a
structure, to read and display the data of a student.
Output
#include <stdio.h>
Enter the details of the second student: #include <conio.h>
Enter the Roll Number= 02 #include calloc.h>
Enter the Name= Aditya typedef struct student
Enter the Course= MCA {
Enter the Fees= 60000 int r_no;
char name[20];
DETAILS OF FIRST STUDENT char course(20];
ROLL NUMBER= 01 int fees;
NAME= Rahul };
COURSE= BCA struct student *ptr(lO];
FEES= 45000
Computer Fundamentals and Programming in C

int main () I 3. Write a program to read, dis.play, _add, and s~btract t\v
{ heights. Height should be given in feet and Inches. o
i nt i;
#i nclude cstdio.h>
for(i =O;i c2;i++)
{
#i nclude cconio.h>
typedef st ruct
pt1•[i] "' (struct s t udent *)malloc( si ze
{
of(stn1 ct st udent));
i nt ft;
printf( "\ n Ente r· t he data fo r st udent
i nt i nch;
\c1 ", i+l);
}HEIGHT;
Pl'intf( "\n ROLL NO. : "};
sca nf("%d", &ptr·[i) - > r_no) ;
HEIGHT hl, h2, h3;
Pl'intf(" \ n NAME: ") ;
HEIGHT add_height(HEIGHT *, HEIGHT *);
gets(ptr[i] -> name ) ;
HEIGHT subtract_height(HEIGHT *, HEIGHT *);
printf( "\ n COURSE : ");
int main()
gets(ptr[i] -> course) ;
p1·intf(" \ n FEES : "); {
int option;
scanf("%d" , &ptr[i] -> fees);
} clrscr();
do
printf( "\n DETAILS OF STUDENTS");
for(i=O;i<2 ; i++) {
{ printf("\n *** MAIN MENU ***");
printf("\n 1. Read height");
pr intf ( "\n ROLL NUMBER= %d",
ptr_stud[i] -> r_no); printf("\n 2. Display height");
printf("\n 3. Add");
pr intf ( "\n NAME= %s", ptr_stud[i] ->
name); printf("\n 4. Subtract");
printf("\n COURSE= %s", ptr_stud[i] -> printf("\n 5. EXIT");
course); printf("\n Enter your option: ");
printf("\n FEES= %d", ptr_stud[i] -> scanf("%d", &option);
fees); switch(option)
} {
return O; case 1:
} printf("\n Enter the first height in feet
and inches: ");
Output
scanf("%d %d", &hl.ft, &hl.inch);
Enter the data for student 1 printf("\n Enter the second height in feet
ROLL NO.: 01 and inches: ");
NAME: Rahul scanf("%d %d", &h2.ft, &h2.inch);
COURSE: BCA break;
FEES: 45000 case 2:
Enter the data for student 2 printf("\n The first height is: %d ft %d
inch", hl.ft, hl . inch);
ROLL NO. :02
printf("\n The second height is: %d ft %d
NAME:Priya inch", h2.ft, h2.inch);
COURSE:BCA break;
FEES:25000 case 3:
h3 = add_height(&hl, &h2);
DETAILS OF STUDENTS
printf ( "\n The sum of two heights is: %d
ROLL NUMBER= 01 ft %d inch", h3.ft, h3.inch);
NAME= Rahul break;
case 4:
COURSE= BCA
h3 = subtract_height(&hl, &h2);
FEES= 45000 printf("\n The difference of two heights
ROLL NUMBER= 02 is: %d ft %d inch", h3.ft, h3.inch);
NAME Priya break;}
}
COURSE= BCA }while(option l= 5);
FEES= 25000 getch();
Structure, Union, and Enumerated Data Type 401~\
return O; 14. Write a program that passes a pointer to a structure to
} a function.
HEIGHT add_height(HEIGHT *hl, HEIGHT *h2)
{ #include <stdio.h>
HEIGHT sum; #include <conio.h>
sum.inch= hl ->inch+ h2 -> inch; #include <alloc.h>
whi le (sum .inch > 12) typedef struct student
{ {
sum. inch -= 12; int r_no;
sum.ft++; char name[20];
} char course[20];
sum.ft= hl ->ft+ h2 -> ft; int fees;
return sum; };
}
HEIGHT subtract_height(HEIGHT *hl, HEIGHT *h2) void display(struct student*);
{ int main()
HEIGHT sub; {
if(hl - > ft > h2 -> ft) struct student *ptr;
{ ptr = (struct student *)malloc(sizeof
if(hl ->inch< h2 -> inch) (struct student));
{ printf("\n Enter the data for the student");
hl ->inch+= 12; printf("\n ROLL NO.: ");
hl - > ft--; scanf("%d", &ptr -> r_no);
} printf("\n NAME: ");
sub . inch= hl -> inch - h2 - > inch;
gets(ptr -> name);
sub.ft= hl -> ft - h2 -> ft;
printf("\n COURSE: ");
}
gets(ptr -> course);
else
printf("\n FEES: ");
{
scanf("%d", &ptr -> fees);
if(h2 ->inch< hl -> inch)
{
display(ptr);
h2 ->inch+= 12; get ch();
h2 - > ft--; return O;
} }
sub.inch= h2 -> inch - hl -> inch;
sub.ft= h2 -> ft - hl -> ft; void display(struct student *ptr)
} {
return sub; printf("\n DETAILS OF STUDENT ");
} printf("\n ROLL NUMBER= %d", ptr -> r_no);
printf("\n NAME= %s", ptr -> name);
Output
printf("\n COURSE= %s", ptr -> course);
*** MAIN MENU*** printf("\n FEES= %d", ptr -> fees);
1. Read height }
2. Display height
3. Add Output
4. Subtract Enter the data for the student
5. EXIT ROLL NO.: 01
Enter your option : 1 NAME : Rahul
Enter the first height in feet and inches: 2 3 COURSE: BCA
Enter the second height in feet and inches: 4 5
FEES: 45000
*** MAIN MENU***
1 . Read height
DETAILS OF STUDENT
2. Display height
ROLL NUMBER= 01
3. Add
NAME= Rahul
4. Subtract
COURSE= SCA
5. EXIT
Enter your option: 3 FEES= 45000.00
The sum of two heights is : 6 ft 8 inch
Computer Fundamentals and Pro
gramming in C
15. Write a program to illu strate Enter the marks obt ain ed in
the use of arrays within n thr ee sub jec ts by
structure.
st udent 2: 90 lOO 89
#in clu de <s tdi o.h > ***** DETAILS** ** *
#in clu de <co nio .h > NAME = Goransh
#in clu de <al loc .h > ROLL NO = 01
t ypedef str uct stu den t MARKS = 99 100 99
{ NAME Pra nja l
char name[20]; ROLL NO 02
int 1-oll_no; MARKS 90 100 89
int ma1-ks(3);
\ .
J '

voi d dis pla y(s tru ct stu den


11D SELF-REFERENTIAL STRUCTURES
t * s)
Self-referential structures are tho
int i ; se structures that contain
a reference to data of its same
pri nt f(" \n NAME= %s \n ROL type, i.e., in addition to
L NO= other data, a self-referential stru
%d\n ", s - > name , s - > rol l_n cture contains a pointer
o); to a data that is of the same typ
pr int f (" \n MARKS="); e as that of the structure.
For example, consider the structur
for (i = 0;i < 3;i++) e node given as follows:
stru ct node
pri ntf (" %d", s -> ma rks (i]) {
;
} int val ;
int main() stru ct node •ne xt;
{ };
str uct stu den t *s[ 2]; Here the structure node will con
int i,j ; tain two types of dat a-a n
integer val and nex t, which is
clr scr ();
, Programming Tip: _
a pointer to a node. You must
for (i = 0;i < 2;i++)
It is an .error to use · be wondering why we need
{
a structure/union suc h a structure. Actually,
s[i ]=( str uct stu den t*)
ma llo c(s ize of( stru ct stu den variable as a member self -ref erential structure is
t)); the fou ndation of other data
pri ntf ("\ n\n Enter the name of its own struct
of stu den t stru ctur es. Their purpose will
%d: ", i+l ); type structure or
get s(s [i] -> name); union type union, be clear to you when you study
pri ntf ("\ n Enter the rol l num respectively. linked list representation of
ber of data structures.
stu den t %d: ", i+l );
scanf("%d", &s[i] -> rol l_n
o);
pri ntf ("\ n Enter the marks
obtained in
thr ee sub jec ts by stu den t %d: i4j:j UNIONS
", i+l );
for (j = 0;j < 3;j++)
Similar to structures, a union is
scanf("%d",&s[i] -> ma rks [j]) a collection of variables
; of different data types. The onl
} y difference between a
structure and a union is that in
pri ntf ("\ n \n\n *****DETA case of unions, you can
ILS*****"); only store information in one field
for (i= 0;i <2; i++ ) at any one time .
To better understand a union, thin
dis pla y(s [i]) ; k of it as a chunk of
memory that is used to store var
get ch( ); iables of different types.
When a new value is assigned to
ret urn 0; a field, the existing data
is replaced with the new data.
}
Thus unions are used to save mem
ory. They are useful
Output for applications that involve mu
ltiple members, where
values need not be assigned to all
Ent er the name of stu den t 1: the members at any one
Goransh time.
Ent er the rol l number of stu
den t 1: 01
Ent er the marks obtained in
thr ee sub jec ts by 15.6.1 Declaring a Union
stu den t 1: 99 100 99
Ent er the name of stu den t The syntax for declaring a unio
2: Pra nja l n is the same as that of
Ent er the rol l number of stu declaring a structure. The only
den t 2: 02 difference is that instead
nfrm S iTP

Strncturc, Un,on, and Enumerated Data Type AOJ

prlnl f ("\ n Thi' ( O•Ol"dlnJtO !i of Pl are Sd


and td ", Pl . x, Pl .y);
prlnt f ("\n Th~ ro-ordlnJt r\ of P2 arc i d
and ' d" , P2. ~, P2 . y ) ,
:3: J_, ) c~ , ar -, a-~: return O:
;3: 3_:,:~ ,ar -~a-e :
Output
lhe co-ordinates of Pl are 2 and 3
.\gam. the typedef ken, d lhe co-ordi nates of P2 are 5 and 5
~mm~ Tip: can be metl ICl - or
simplify the In th,, code. POIN'T 1 is a wucture name and POIN'T 2 1c; a
, ,.-,.a..."1c cl a ~ dl."\·laratlCln of union , an~ble,
• - •..._,.-; can be union name. Ho\~ever. both the declarations are almost same
~~ ~ The nH.)S\ imponant thi~g (ncept the keywords-struc t and union): in main () , you
.:i'2..,;:-E\l ..t tt;.e tme to remembe r abo ut a union l', ,ee a point of diffe rence while ini tializi ng values. The fields
:·~~Ci..:~ .,...~(Jr t~at th~-size of a union is th;
~':ti(!,• ::-, N.:vl@
of a union cannot be initialized all at once .
stze ot its la11req
" ~ field · Th IS IS Look at the out put ca re full y. For the structu re variable
~,~-~=-="'d~a'ter because sufficient number of the output is fine but fo r t.he union variable the answer
~,:x:s~t:-,.,re and b~1 ~ mu5t be resm·ed to store
~ :r€ ~colon. does not seem to be correct.
th e largest sized field . To understand the concept
Programming Tip: of union, execute the following
The size of a union code. The code gi ven below
15.6.2 Accessing a Member of a Union
is equal to the just re-arranges the printf
..\ ::ron1:cr - 0 :· 3. union T
can be accessed usinoe the same syntax size of its largest statements. You will be
~ ±,.;.: 0: l 0UC~e. 10 acee:ss the fields of a union, use the member. surprised to see the result
~._-. .: ~~..c:or ~ -) ~- LL ~ e uruon Yariable name followed by
~ u:-. 0~-or 10110" ed by the member name. #include <stdio.h>
typedef struct POINTl
{
15.6.3 Initializing Unions int x, y;
?rograJ'll]lling T"rp: A striking difference between };
: s =11 error to a structure and a union is
:--_:-.;ze afl'f ift.her that in case of a union, the typedef union POINT2
uroon mem~r except fields share the same memory {
the first member. space, so fresh data replaces int x;
any existing data. Look at int y;
ilii: following code and observe the difference between a };
5ID1C1UI'e and union when their fields are to be _initialized. int main()
{
h nclude <stdio. h> POINTl Pl= {2,3};
typedef struct POINTl POINT2 P2;
printf("\n The co-ordinates of Pl are %d and
i nt x, y; %d", Pl.x, Pl.y);
P2. X = 4;
printf("\n The x co-ordinate of P2 is %d",
"::tpedef un ion POHIT2 P2. x);
P2.y = 5;
i nt x; printf("\n They co-ordinate of P2 is %d"1
i nt y; P2. y);
}; return O;
int main () }
{
POIIITl Pl -= {2,3}; Output
I I POIIIT2 P2 ={4, 5}; Illegal with union The co-ordinates of Pl are 2 and 3
POHIT2 P2; The x co-ordinate of P2 is 4
P2.x = 4; They co-ordinate of P2 is 5
P2 .y = 5;
~~~e~l\!o:!~~;_output is correct, the data is still over-
Computer Fundame ntals and Programming in C

,,n ARRAYS OF UNION VARIABLES struc t st udent stud;


char cho i ce ;
Like structures " c can :ii~,, h11vc 1111 rm oy of u11 io11 printf ("\ n vou can enter the name or roll
, :iriabks. I lo" n l'l'. hccu11~l· of the proble m or new dntn numbe r of t he stude nt");
O\'crwri tm g. c, 1~t111 ~ data 111 the other lic lds, the progn11ll print f( "\ n oo you want to enter the name? ('I
ma~ lh't di~pla~ th,: :lCl'11rntc resu lt s. or N) : " );
#include ~s tdio. 11 , get s (c hoice );
H (c ho ice= =, y ' 11 choic e==' Y')
Ut~ion POI NT
{
int x, y; pri nt f ( "\ n Enter the name: ") ,·
\ .
J ,
gets (st ud . name);
}
int main() els e
{
int i ; print f(" \ n Enter the roll numbe r: ");
union POI NT points (3 ) ; scanf("%d", &stud .roll_ no ) ;
points (O].x 2; }
print k : ")
points[O] .y = 3; f("\n Enter the mars ;
point s(l].x = 4; scanf("%d", &stud.marks);
point s( l ] .y = 5; if(cho ice== 'y ' 11 choice=='Y')
point s(2].x = 6; print f("\n Name: %s ", stud.name );
point s(2] .y = 7; else
printf ("\n Roll Number: %d ", stud.roll_no);
for( i=O ; i <3;i++) print f("\n Marks: %d", stud.marks);
print f("\n Co-ordinates of Point[%d] return O;
are %d and %d", i, point s[i].x , }
point s[i].y );
r eturn O; Now in this code, we have a union embedded within
}
a structure. We know, the fields of a union will share
memory, so in the main program we ask the user which
Outpu t data he/she would like to store and depending on his/her
Co-or dinate s of Point[O] are 3 and 3 choice the appropriate field is used.
Co-or dinate s of Point [l] are 5 and 5
Co-or dinate s of Point[ 2] are 7 and 7
Pointing to unions, passing unions to functions, and
passing pointers to unions to functions are all done in the
1,f:j UNIONS INSIDE ST~U~TU~~S same way as that of structures.

' *•
You must be wondering, why do we need unions? In
general, unions can be very useful when declared inside a
structure. Consider an example in which you want a field
of a structure to contain a string or an integer, depending STRUCTURES INSIDE UNIONS
on what the user specifies. The following code illustrates
C also allows users to have a structure within a union. The
such a scenario.
program given below illustrates the use of structures within
#include <stdio.h> a union. There are two structure variables in the union. The
struc t stude nt size of the union will be the size of the structure variable
{ which is larger of the two. During run-time, programmer
union will choose to enter name or roll number of the student and
{ the corresponding action will thus be taken.
char name[20];
#include <stdio .h>
int roll_n o;
typed ef struc t a
};
{ int marks;
int marks;
char name [20];
}; };
int main() typed ef struc t b
Structure, Union, and Enumerated Data Type
40? ~
~
{ int marks; ol' a set or named integer constant s. In other words,
int roll_no ; in an enumera ted type, each intege r value is assigned
}; an identifier. This identifier (whi ch is also known as an
enumeration constant) can be used as a symbolic name to
t ypedef union Student make the program more readable .
{ struct a A; To define enumerated data types, we use the keyword
Stl'U Ct b B; enum, which is the abbre viation fo r ENUMERATE.
}; Enumeration s create new data types to contain values that
main () are not limited to the values that fundamental data types
{ may take. The syntax of creati ng an enumerated data type
union Studen ts; can be given as fo ll ows:
char' ch ;
printf(" \n Do you want to enter name or roll enum enumeration_name {identif ier 1 ,
number' of the student (N/R )- "); identifi er 21 ... , identifi er 0 } ;
scanf(" %c", &ch); The enum keyword is basically used to declare and initialize
if(ch == 'R') a sequence of integer constants. Here, enumeration_name
{ is optional. Consider the following example, which creates
printf(" \n Enter the roll number ");
a new type of variable called COLORS to store colour
scanf ( "%d", &s.B.ro ll_no); constants.
printf ( "\n Enter the marks : ");
scanf("%d", &s.B.marks); enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW,
} PURPLE, WHITE};
else
{
Note that no fundamental data type is used in the
printf(" \n Enter the name : "); declaration of COLORS. After this statement, COLORS has
gets(s.A .name); become a new data type. Here, COLORS is the name given
printf(" \n Enter the marks : "); to the set of constants. In case you do not assign any
scanf("%d", &s.A.marks); value to a constant, the default value for the first one in
} the list-RED (in our case) has the value of 0. The rest
printf(" \n ****** STUDENT'S DETAILS of the undefined constants have a value 1 more than
**** **"); its previous one. That is, if you do not initialize the
if(ch == 'N') constants, then each one would have a unique value. The
{ first would be zero and the rest would count upwards. So,
printf(" \n NAME : "); in our example,
puts(s.A.name);
printf(" \n MARKS : %d", s.A.marks); RED= O, BLUE= 1, BLACK= 2, GREEN= 3,
} YELLOW= 4, PURPLE= 5, WHITE= 6
else
If you want to explicitly assign values to these integer
{
constants then you should specifically mention those
printf(" \n ROLL NO: %d", s.B.rol l_ no);
values shown as follows:
printf(" \n MARKS : %d", s.B.mar ks);
} enum COLORS {RED= 2, BLUE, BLACK= 5, GREEN
} = 7, YELLOW, PURPLE, WHITE= 15};
Output
As a result of this statement, now RED = 2, BLUE
Do you want to enter name or roll number of 3, BLACK= 5, GREEN= 7, YELLOW= 8, PURPLE= 9,
the student : (N/R)- R WHITE= 15.
Enter the roll number : 12 Look at the code which illustrates the declaration and
Enter the marks : 99 access of enumerated data types.
****** STUDENT'S DETAILS******
#includ e <stdio.h >
ROLL NO : 12
int main()
MARKS : 99
{ enum {RED=2, BLUE, BLACK=5, GREEN=7, YELLOW,
PURPLE, WHITE=l5};
itJt,1 ENUMERATED DATA TYPE printf( "\n RED= %d", RED);
printf( "\n BLUE= %d", BLUE);
The enumerated data type is a user-defined type based printf( "\n BLACK= %d", BLACK);
on the standard integer type. An enumeration consists printf( "\n GREEN= %d", GREEN);

h,,,,,
Computer Fundamentals and Programming in C

printf("\n YELLOW = %d" , YELLOW) ; fo r decl aring a variable of an enumerated data type can be
printf("\n PURPLE = %d", PUR PLE ); given as
printf ( "\n l✓H ITE = %d", WHITE);
retu1·n O; enumeration_name variable_name;
So lo creale a variable of COLORS, we may write
Output enum COLORS bg_color;
RED = 2 Thi s dec lares a variable called bg_color, which is of the
BLUE = 3 enumerated data type, COLORS. Another way to declare
BLACK = 5 a variable can be as illustrated in the following statement.
GRE EN = 7
YELLOW= 8 enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW,
PURPLE = 9 PURPLE, WHITE}bg_color, fore_color;
l~ ITE = 15

15.10.2 Using the Typedef Keyword


C also permits to use the typedef keyword for enumerated
The value of an enumerator constant is always of the data types. For example, if we write
type int. Therefore, the storage associated with ari .. . ·... typedef enum COLORS color;
enumeration variable is the storage required for a single · ·
Then, we can straightaway declare variables by writing
int value. The enumeration constant or a value ofthe ...
enumerated type can be used anyw_here in the pr~gram · color forecolor = RED;
where the C language permits an .intJger expression,' .
-'-'' ',_. -. -

15.10.3 Assigning Values to Enumerated


The following rules apply to the members of an Variables
enumeration list:
Once the enumerated variable has been declared, values
• An enumeration list may contain duplicate constant can be stored in it. However, an enumerated variable can
values. Therefore, two different identifiers may be hold only declared values for the type. For example, to
assigned the same value, say 3. assign the colour black to the background colour, we will
• The identifiers in the enumeration list must be different write,
from other identifiers in the same scope with the
same visibility including ordinary variable names and bg_color = BLACK;
identifiers in other enumeration lists.
An important thing to note here is that once an
• Enumeration names follow the normal scoping rules. So
enumerated variable has been assigned a value, we can
every enumeration name must be different from other
store its value in another variable of the same type. The
enumeration, structure, and union names with the same
following statements illustrate this concept.
visibility.
enum COLORS bg_color, border_color;
bg_color = BLACK;
If we create an enumerated type without entJme~tie>n,:;::. ::~ border_color = bg_color;
name, it is known as an anonymous enumerated type.
For example, enum {OFF, ON}; declares an enumerated 15.10.4 Enumeration Type Conversion
type that has two constants OFf with a value 0 and ON
with a value 1. Enumerated types can be implicitly or explicitly cast. For
example, the compiler can implicitly cast an enumerated
type to an integer when required. However, when we
implicitly cast an integer to an enumerated type, the
15.10.1 enum Variables compiler will either generate an error or a warning
We have seen that enumerated constants are basically message.
integers, so programs with statements such as int . fore_ To understand this, answer one question. If we write
color = RED; is considered to be a legal statement m C. enum C0L0RS{RED, BLUE, BLACK, GREEN, YELLOW,
In extension to this, C also permits the user to declare PURPLE, WHITE};
variables of an enumerated data type in the same way as enum COLORS c;
we create variables of other basic data types. The syntax c =BLACK+ WHITE;
\l n 1, tur,• Utlhlf\ " rypc
in,t t llllt'flM,I Q(l(l .,;HJ ~117

l k f\' , l I' ,Ul t'lllll\\Cf,lll',I ,t,1., I\ l'lt' \ .H1.1t,Jt' ,, \ I \' \ \ flt,'


, ~L.\C\ ~ -..,n H • Ihm 1,,~,,.,11, . ,1 ,h,, 111,1 "'' i , ,, •
1•111111w, 11,·d t;1w II t· r,•,1d wrth' ,, .,-. .1n 1nlt'l(t'r fhr
~- \\ hllh ,, ~) , tl'.l lh ,, , ,, hh' 111 I\J"' \ n \ 11,"'''' <'f. Ill\'
I '""l'"•'f \\ 111d.l t1t1plt1 111\, d.i 1h1..• r~p,· \ 11 11 •n: r ~ tOtl (I~
c1, 11.rnd '11k ,,t 1lw ''"''!nnw 111 Pi_,.,, 11,,1 ,~ ,,, tlw 11 p,' ,11 ., 11~<11· .t t' 1tl1 ,· 1 t ht• tiill,111 Ill ~ -c t,ll 1' 1!h.' l\l i dt11 '1 ltlll( tht'I
,1 111,q1t
,. ,., .. l l'L l'~' ~ ,, thl' , l\h' llh'I\I \\ \\11111 h'I"'' ' Ml 1'1f1\I l ,1
n·t1h'' l' 1lw l'lll't . , I' ll , ,1n '11 1 t' llh1'1 Pl I\\ ,, l hlll\l~ I 11 ~1 ,, , H1111 f1 111m ,1 Rf t1, 11111r , n1Mw . t ,fH t M, vri t nw,
,1,,,1.ii.·, II' t"· ,,11 ml ' 1', 111111 . , .,,1 tlw fli\ht h.rnd ~u \,, 11 ; ~'IIIH'I r. WI II rr: ).
,;,• 11, lh'" Ill~ 1)\,\ 1\1\l' I
r, 111 111 11 11 flR, r,
'<t 11 11 ( ' \ d ', .. , I ,
i•i' lni f ("'\ 11 l ,il n r

If\ . \v r1l 1' ., pnii.tf,ll ll i.1 rli ipl .i-r lh1• 11.rn11 111 rtw 1111!,l! r~
1, , 1,m 1.\'Ll'R'-.\Rlfl, lllt l(, lll •\ l ,. G~fl N, 'lfll (lW,
11~1111! 111 C' flll111l'F 1h·d IVpl'
l'l t; l' \ l . ,~~~,, l l.
l' 11 1m 1 ,'ll'R" , , It lnfludf" , ~t tl 111 h,
\ Jlltl in l ,-mun crn nR '- fRFO. Bl 1/f. 01 t\ CK, r,R FF N, , r110w ,
i l h•~ ,l l \ 11 r11RPI r, WH[fF},
RIRhl W,l V lnt /11 ,d n ( )

f'nu m COLOR <;<: ,


15.10,5 Compari ng Enumerated Types (' h,1r •co lc1r n,,rnd I • ("RED" , "BLUE",
., th"'~ ,,~mg. 1· ,1111p:11 IM'I\ 11pC'mh,r:- l'II C' llllllll' ntlC'd
1..' :iJ-.1, " AL ACK" , "GREE M", " YFL LOW", "PURP LE" ,
~istJ \~l"-' l 1'1.1\-. at \hC' fothrn 111 ~ s tll!C'llll' III S. "hir h " WH[ rE"};
1llustrntl.' ,lw: ,.,,,11·q,1. (or (c • RED . c <• WHtfE; C ►► )

1:,g__cokr " ( enum COLORS)6; prlntf ( "\ n ls" , co lor _name[ c j) ;


if~ bg__ color === l~HITE) r eturn O;
h~rt>_co lor = BLUE;
fore_co lo1· = BLACK;
1f t bg_color == fore_color) OR
pr i ntf("\n NOT VISIBLE");
#include <stdio . h>
Smee enumerJted types are derived from integer type. #i nclude <stdlib . h>
the~ 1.· an be used in :1 switch case statement. The following #include <co nio .h >
C"C'de demonstrates the use of the enumerated type in u enum COLORS {red, blue, black, green, yel l ow,
S\\ itch case statement.
purple, wh ite};
int main()
enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, {
WHITE}bg_color; enum COLORS c;
switch(bg_color) c = rand()%7;
{ switch(c)
case RED: {
case BLUE: case red : printf ("\n RED") ; break ;
case GREEN: case blue : printf( "\n BLUE "); break ;
printf ( "\n It is a primary color"); case black : printf("\n BLACK" ); break ;
break; case green: printf("\n GREEN"); break;
case default: case yellow: printf( "\n YELLOW");
printf("\n It is not a primary color"); break;
break; case purple : printf("\n PURPLE") ;
break;
case white : printf("\n WHITE") ; break;
}
15.10.6 Input/Output Operations on
return O;
Enumerated Types
Output
Since enumerated types arc derived types, they cannot
be read or wrillen using formatted input/outpul fun ctions GREEN
available in the C language. When we read or write nn

You might also like