Bpops103 Module 5 Structures Text
Bpops103 Module 5 Structures Text
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
\ .\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.
'
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. }
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
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
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 '
' *•
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
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 ( )