SlideShare a Scribd company logo
1 of 16
Structure
Sometime, it may require to process multiple data stucture whose individual data elements can
be differ in type. In a single structure may contain integer element, floating point element and
character element. It may consist of arrays, pointers and other structures as element of the
structure.
So, a combination of data structure with various type of elements within the same storage class, is
known as structure in C.
Defining a structure
It is a little bit difficult to define a structure with comparing to an array. Since in a structure, it
may consist of various data elements and each data element is to be defined separately within the
structure such as:
struct tag {
member 1;
member 2;
member 3;
…………..
………….
member m;
};
where struct is a keyword which defines the following combination is a structure.
tag represents the name of structure of combined members included within compound statement.
and, member 1,member 2, member 3,……..member m are the individual declaration of elements
of current structure.
• The individual member can be ordinary variable, array, pointer or other structure.
• The name must be distinct from another structure.
• But the member name of the structure and outside the structure may be same but refers to
different identity.
• Storage class can not be defined for individual members and also cannot be initialized
individual members within the structure.
Once the composition of structure has been defined, individual structure type variables can be
declared as follows:
storage_class struct tag variable 1, variable 2, variable 3, ……., variable n;
where, storage class is optional.
struct is required keyword to declare following variables as structures.
tag is the name of the structure
and variable 1, variable 2, variable 3 are the structure variables.
e.g.
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
};
1
struct account oldcustomer, newcustomer;
It is also possible to combine the declaration of structure with structure variables as follows:
storage_class struct tag {
member 1;
member 2;
member 3;
…………..
………….
member m;
}variable 1, variable 2, variable 3, ……., variable n;
Note : tag is optional in this case.
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
} oldcustomer, newcustomer;
A structure may also consist of another structure as a member of structure but the embedded
structure must be declared before the outer structure.
eg.
struct date {
int month;
int day;
int year;
};
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
} oldcustomer, newcustomer;
The member of a structure can not be initialized within the structure. It can be initialized in the
same order as they are defined within the structure as follows:
storage_class struct tag variable={value 1, value 2, value 3......., value m};
e.g.
struct date {
int month;
int day;
int year;
};
2
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
};
static struct account customer = {101,’S’, “Anup”, 10000.50, 5, 15, 04};
array of structure
It can also be defined an array of structures upon which each element of the array represents a
structure.
e.g.
struct date {
int month;
int day;
int year;
};
struct account {
int acctno;
char acct_type;
char name[80];
float balance;
struct date lastpayment;
}customer[100];
In this declaration, each element of array represents a structure of a customer. So, we have 100
structures for 100 customers. That means, we can store 100 records of customer in this data
structure.
Processing a structure
The members of a structure are usually processed individually, as separate entities. So, each
member of a structure can be accessed individually as follows:
variable.member
where variable refers to name of a structure type variable
and, member refers to name of a member of the structure.
e.g.
customer.acctno
where, customer refers to name of structure
and accno refer to member of the structure
similarly,
3
customer.name
customer.balance
etc.....
let’s see some expressions
++customer.balance
customer.balance++
&customer.balance
Similarly, it can also be accessed sub-member of a structure as follows:
variable.member.submember
where variable refers to name of a structure type variable
member refers to name of a member within outer structure
and, submember refers to name of the member within the embedded structure.
e.g.
customer.lastpayment.month
/* to read input of a customer and write out it’s information again */
#include<stdio.h>
struct date {
int month;
int day;
int year;
};
struct account {
int acctno;
char acct_type;
char name[80];
int balance;
struct date lastpayment;
}customer[100];
main()
{
int i,n;
printf(“n How many no. of cusstomer?”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
readinput();
for(i=0;i<n;i++)
writeoutput();
}
4
void writeoutput(int i)
{
printf(“n Customer No.: %d”,i+1);
printf(“Name : %s”,customer[i].name );
printf(“Account Number : %d “,customer[i].acctno );
printf(“Account Type : %c “,customer[i].acct_type );
printf(“Balance : %d “,customer[i].balance );
printf(“Payment Date : %d/%d/%d “,customer[i].lastpayment.month,
customer[i].lastpayment.day, customer[i].lastpayment.year);
}
void readinput(int i)
{
printf(“n Customer No.: %d”,i+1);
printf(“Name : “);
scanf(“%[^n] “,customer[i].name );
printf(“Account Number : “);
scanf(“%d “,&customer[i].acctno );
printf(“Account Type : “);
scanf(“%c “,&customer[i].acct_type );
printf(“Balance : “);
scanf(“%d “,&customer[i].balance );
printf(“Payment Date : “);
scanf(“%d/%d/%d“,&customer[i].lastpayment.month, &customer.lastpayment.day,
&customer.lastpayment.year);
}
User Defined data types(typedef)
In c, the data type of any identity can be customized by the user. i.e. new data type can also be
made so that such type can be used to define any identities. typedef is the keyword, which enables
users to define new data type equivalent to existing data types. Such user defined data types can
be used any new variables, arrays, structures. New data type can be defined as follows:
typedef type new_type;
e.g.
typedef int age;
age male female;
and, is equivalent to
int male, female;
Similarly,
typedef float cust[100];
cust newcust,oldcust;
or,
typedef float cust;
cust newcust[100],oldcust[100];
By the same way, it can also be used to define a structure too. It removes the repeatition of struct
tag.
In general,
5
typdef struct{
member 1;
member 2;
...............
member m;
}new_type;
e.g.
typedef struct{
int acctno;
char acct_type;
name[80];
float balance;
}record;
record oldcustomer,newcustomer;
Here, record is defined as new structure data type and newly define data type is used to define
structure variables oldcustomer and newcustomer.
Different ways of declaration of structures
typedef struct {
int month;
int day;
int year;
}date;
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}record;
record customer[100];
typedef struct {
int month;
int day;
int year;
}date;
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}record[100];
record customer;
typedef struct {
int month;
int day;
int year;
}date;
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}customer[100];
Structures and Pointers
The beginning address of a structure can also be accessed in the same manner as other address,
using &(address) operator. So, a variable represents a structure, it can also be represented its
address as &variable and pointer to the structure can be denoted as *variable.
such as
type *ptvar;
A pointer to a structure can be defined as follows:
6
e.g.
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}account;
account customer, *pc=&customer;
typedef struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
} customer, *pc=&customer;
Here, customer is a structure variable of type account and pc is a pointer variable whose object is account type
structure. The beginning address of the structure can be accessed as
pc=&customer;
Generally, each member of structure can be accessed by using selection operator as
ptvar -> member
which is equivalent to
variable.member
The -> operator can be combined to period (.) operator and their associativity is left to right. Similarly, it can be used
for array too.
ptvar ->member[expn]
typedef struct {
int month;
int day;
int year;
}date;
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
} customer, *pc=&customer;
So, if we want to access customer’s account number, then we can write any one of these
customer.acctno pc->acctno (*pc).acct_no
Similary, for month of last payment,
customer.lastpayment.month
pc->lastpayment.month
(*pc).lastpayment.month
If the structure is defined as:
struct {
int *acctno;
char *acct_type;
char *name;
7
float *balance;
date lastpayment;
} customer, *pc=&customer;
So, if we want to access customer’s account number, then we can write any one of these
*customer.acctno *pc->acctno *(*pc).acct_no
struct2.cpp
/* To access data items from members of structure */
#include<stdio.h>
#include<conio.h>
void main()
{
int n=111;
char t='c';
float b=99.99;
char name[20]="srijan";
int d=25;
typedef struct {
int *month;
int *day;
int *year;
}date;
struct {
int *acctno;
char *acct_type;
char *name;
float *balance;
date lastpayment;
}customer,*pc=&customer;
pc->acctno=&n;
customer.acct_type=&t;
customer.name=name;
customer.balance=&b;
*customer.lastpayment.day=25;
clrscr();
printf("n%d %c %s %.2f %d", *customer.acctno, *customer.acct_type, customer.name,
*customer.balance, *customer.lastpayment.day);
printf("n%d %c %s %.2f %d",*(*pc).acctno,*pc->acct_type,
pc->name,*pc->balance,*pc->lastpayment.day);
8
getch();
}
struct3.cpp
/* To determine the size of a structure and it's address */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
typedef struct {
int month;
int day;
int year;
}date;
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}customer, *pc=&customer;
printf("nNumber of bytes %d",sizeof *pc);
printf("nstarting address : %d",pc);
printf("nstarting address : %d",++pc);
getch();
}
Passing structure to a function
A structure can generally be passed to a function by two ways. Either, individual members can be passed to a function
or entire structure can be passed to a function. By the same way a single member can be returned back to the function
reference or entire structure.
In general,
void main()
{
typedef struct {
int month;
int day;
int year;
}date;
9
struct {
int acctno;
char acct_type;
char name[80];
float balance;
date lastpayment;
}customer;
float modify(char name[], int acctno, float balance);
....................
customer.balance = modify(name, acctno, balance);
....................
}
float modify(char name[], int acctno, float balance)
{
float newbalance;
....................
newbalance = .........;
return(newbalance);
}
In this example, individual member is passed to a function and the new value is returned back to a member of a
structure.
struct4.cpp
/* To pass an entire structure to a function*/
#include<stdio.h>
#include<conio.h>
typedef struct {
int acctno;
char acct_type;
char *name;
float balance;
}record;
void main()
{
void modify(record *pc);
record customer={101,'c',"Anup",5000.00};
printf("n%d %c %s %.2f",customer.acctno,customer.acct_type,customer.name,customer.balance);
modify(&customer);
printf("nn%d %c %s %.2f", customer.acctno, customer.acct_type, customer.name, customer.balance);
10
getch();
}
void modify(record *pc)
{
pc->acctno=999;
pc->acct_type='d';
pc->name="Sabin";
pc->balance=99999.99;
}
In this example, it passes entire structure to the function with it's address, then modifies values of member
of the structure and finally returns back to the function reference with modified values of the structure.
struct5.cpp
/*to illustrate how an array of structure is passed to a function, and how a
pointer to a particular structure is returned */
#include<stdio.h>
#include<conio.h>
#define N 3
typedef struct {
int acctno;
char acct_type;
char *name;
float balance;
}record;
void main()
{
static record customer[N]={
{101,'c',"Anup",5000.00},
{102,'d',"Anil",9000.00},
{103,'o',"Sabina",7000.00}
};
int ano;
record *pc;
record *search(record table[N], int ano);
do{
printf("n Enter the record no. to be searched, type 0 to end");
scanf("%d",&ano);
pc=search(customer,ano);
if(pc!=0)
{
printf("n Name : %s",pc->name);
printf("n Account No. : %d",pc->acctno);
11
printf("n Account type : %c",pc->acct_type);
printf("n Balance : %.2f",pc->balance);
}
else
printf("n Error - Record not found");
} while(ano!=0)
}
record *search(record table[N], int ano)
{
int i;
for(i=0;i<N;i++)
if(table[i].acctno==ano)
return(&table[i]);
return(0);
}
Unions
It is similar to a structure which may contain individual data item may be different data types of same storage class.
Each member of the structure is assigned its own unique storage area in memory whereas all members of a union share
the same storage area in memory. It reserves the space equivalent to that of member which requires highest memory.
So, it is used to conserve memory. It is useful to such applications, where all members need not to be assigned value at
the same time. If assigned, it will produce meaningless result.
In general,
union tag {
member 1;
member 2;
...............
member m;
};
storage-class union tag variable1, variable2, ..........variable n;
or, combined form,
storage-class union tag {
member 1;
member 2;
...............
member m;
}variable1, variable2, ..........variable n;
e.g.
union id{
char color[12];
int size;
}shirt, blouse;
12
Here we've two union variables, shirt and blouse of type id and occupies 12 bytes in memory, however value is
assigned to any union variable.
e.g.
union id{
char color[12];
int size;
};
struct clothes{
char manufacturer[20];
float cost;
union id description;
}shirt, blouse;
Here, shirt and blouse are structure clothes type variables. Each variable contains manufacturer, cost and either
of color or size.
Each individual member can be accessed in the same way as structure using . and -> operators.
struct6.cpp
/* a program using union */
# include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
union id{
char color[12];
int size;
};
struct clothes{
char manufacturer[20];
float cost;
union id description;
}shirt, blouse;
printf("%d",sizeof(union id));
scanf("%s",shirt.description.color);
printf("n %s %d ", shirt.description.color, shirt.description.size);
shirt.description.size=12;
printf("n %s %d ", shirt.description.color, shirt.description.size);
getch();
}
struct7.cpp
13
#include<stdio.h>
#include<conio.h>
#include<math.h>
typedef union {
float fexp; // floating point exponent
int nexp; // integer exponent
}nvals;
typedef struct{
float x;
char flag;
nvals exp;
}values;
void main()
{
values a;
float power(values a);
int i;
float n,y;
printf("y=x^nn enter value of x:");
scanf("%f",&a.x);
printf("enter value for n: ");
scanf("%f",&n);
i=(int) n;
a.flag=(i==n) ?'i' : 'f';
if(a.flag == 'i')
a.exp.nexp = i;
else
a.exp.fexp=n;
if(a.flag=='f' && a.x<=0.0)
{
printf("ERROR cannot raise negative no. to a");
printf("floating point power");
}
else
{
y=power(a);
printf("n y=%.4f",y);
}
getch();
}
float power(values a)
{
int i;
float y=a.x;
14
if(a.flag=='i')
{
if(a.exp.nexp==0)
y=1.0;
else
{
for(i=1;i<abs(a.exp.nexp);i++)
{
y*=a.x;
if(a.exp.nexp<0)
y=1.0/y;
}
}
}
else
y=exp(a.exp.fexp*log(a.x)); //y=exp(n(log(x)))
return(y);
}
What is a structure? How does a structure differ from an array?
What is member? Write down the relation between member and structure?
What is the purpose of the typedef feature? How is this feature used in conjuction with structures?
What is a union? How does a union differ from a structure?
15
Self Referential Structures
It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type.
Generally,
struct tag {
member 1;
member 2;
...........
struct tag *name;
};
where name refers to the name of a pointer variable. Thus the structure of type tag will have a member that
points to another structure of type tag. Such structure is known as Self-referential structure.
eg.
struct list{
char item[40];
struct list *name;
};
16

More Related Content

Similar to 9.structure & union

Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9patcha535
 
Str
StrStr
StrAcad
 
Structures in c++
Structures in c++Structures in c++
Structures in c++Swarup Boro
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and TypedefAcad
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And UnionsDhrumil Patel
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and UnionsDhrumil Patel
 
Definition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptxDefinition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptxAnithaTAssistantProf
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structuresKrishna Nanda
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structureshaibal sharif
 
Structures in c language
Structures in c languageStructures in c language
Structures in c languagetanmaymodi4
 
Structures in c language
Structures in c languageStructures in c language
Structures in c languageTanmay Modi
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RERajeshkumar Reddy
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing conceptskavitham66441
 

Similar to 9.structure & union (20)

Chapter 13.1.9
Chapter 13.1.9Chapter 13.1.9
Chapter 13.1.9
 
Ch7 structures
Ch7 structuresCh7 structures
Ch7 structures
 
Str
StrStr
Str
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
structures_v1.ppt
structures_v1.pptstructures_v1.ppt
structures_v1.ppt
 
Structure and Typedef
Structure and TypedefStructure and Typedef
Structure and Typedef
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Definition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptxDefinition, Declaration of Structures in C.pptx
Definition, Declaration of Structures in C.pptx
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Unit-V.pptx
Unit-V.pptxUnit-V.pptx
Unit-V.pptx
 
C programing -Structure
C programing -StructureC programing -Structure
C programing -Structure
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA REC UNIT-4 PREPARED BY M V BRAHMANANDA RE
C UNIT-4 PREPARED BY M V BRAHMANANDA RE
 
data structure and c programing concepts
data structure and c programing conceptsdata structure and c programing concepts
data structure and c programing concepts
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
 
Programming in C
Programming in CProgramming in C
Programming in C
 

More from Shankar Gangaju (20)

Tutorial no. 8
Tutorial no. 8Tutorial no. 8
Tutorial no. 8
 
Tutorial no. 7
Tutorial no. 7Tutorial no. 7
Tutorial no. 7
 
Tutorial no. 6
Tutorial no. 6Tutorial no. 6
Tutorial no. 6
 
Tutorial no. 3(1)
Tutorial no. 3(1)Tutorial no. 3(1)
Tutorial no. 3(1)
 
Tutorial no. 5
Tutorial no. 5Tutorial no. 5
Tutorial no. 5
 
Tutorial no. 4
Tutorial no. 4Tutorial no. 4
Tutorial no. 4
 
Tutorial no. 2
Tutorial no. 2Tutorial no. 2
Tutorial no. 2
 
Tutorial no. 1.doc
Tutorial no. 1.docTutorial no. 1.doc
Tutorial no. 1.doc
 
What is a computer
What is a computerWhat is a computer
What is a computer
 
Pointer
PointerPointer
Pointer
 
Array
ArrayArray
Array
 
6.array
6.array6.array
6.array
 
5.program structure
5.program structure5.program structure
5.program structure
 
4. function
4. function4. function
4. function
 
3. control statement
3. control statement3. control statement
3. control statement
 
2. operator
2. operator2. operator
2. operator
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
Ads lab
Ads labAds lab
Ads lab
 
Electromagnetic formula
Electromagnetic formulaElectromagnetic formula
Electromagnetic formula
 
Electromagnetic formula
Electromagnetic formulaElectromagnetic formula
Electromagnetic formula
 

Recently uploaded

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

9.structure & union

  • 1. Structure Sometime, it may require to process multiple data stucture whose individual data elements can be differ in type. In a single structure may contain integer element, floating point element and character element. It may consist of arrays, pointers and other structures as element of the structure. So, a combination of data structure with various type of elements within the same storage class, is known as structure in C. Defining a structure It is a little bit difficult to define a structure with comparing to an array. Since in a structure, it may consist of various data elements and each data element is to be defined separately within the structure such as: struct tag { member 1; member 2; member 3; ………….. …………. member m; }; where struct is a keyword which defines the following combination is a structure. tag represents the name of structure of combined members included within compound statement. and, member 1,member 2, member 3,……..member m are the individual declaration of elements of current structure. • The individual member can be ordinary variable, array, pointer or other structure. • The name must be distinct from another structure. • But the member name of the structure and outside the structure may be same but refers to different identity. • Storage class can not be defined for individual members and also cannot be initialized individual members within the structure. Once the composition of structure has been defined, individual structure type variables can be declared as follows: storage_class struct tag variable 1, variable 2, variable 3, ……., variable n; where, storage class is optional. struct is required keyword to declare following variables as structures. tag is the name of the structure and variable 1, variable 2, variable 3 are the structure variables. e.g. struct account { int acctno; char acct_type; char name[80]; float balance; }; 1
  • 2. struct account oldcustomer, newcustomer; It is also possible to combine the declaration of structure with structure variables as follows: storage_class struct tag { member 1; member 2; member 3; ………….. …………. member m; }variable 1, variable 2, variable 3, ……., variable n; Note : tag is optional in this case. struct account { int acctno; char acct_type; char name[80]; float balance; } oldcustomer, newcustomer; A structure may also consist of another structure as a member of structure but the embedded structure must be declared before the outer structure. eg. struct date { int month; int day; int year; }; struct account { int acctno; char acct_type; char name[80]; float balance; struct date lastpayment; } oldcustomer, newcustomer; The member of a structure can not be initialized within the structure. It can be initialized in the same order as they are defined within the structure as follows: storage_class struct tag variable={value 1, value 2, value 3......., value m}; e.g. struct date { int month; int day; int year; }; 2
  • 3. struct account { int acctno; char acct_type; char name[80]; float balance; struct date lastpayment; }; static struct account customer = {101,’S’, “Anup”, 10000.50, 5, 15, 04}; array of structure It can also be defined an array of structures upon which each element of the array represents a structure. e.g. struct date { int month; int day; int year; }; struct account { int acctno; char acct_type; char name[80]; float balance; struct date lastpayment; }customer[100]; In this declaration, each element of array represents a structure of a customer. So, we have 100 structures for 100 customers. That means, we can store 100 records of customer in this data structure. Processing a structure The members of a structure are usually processed individually, as separate entities. So, each member of a structure can be accessed individually as follows: variable.member where variable refers to name of a structure type variable and, member refers to name of a member of the structure. e.g. customer.acctno where, customer refers to name of structure and accno refer to member of the structure similarly, 3
  • 4. customer.name customer.balance etc..... let’s see some expressions ++customer.balance customer.balance++ &customer.balance Similarly, it can also be accessed sub-member of a structure as follows: variable.member.submember where variable refers to name of a structure type variable member refers to name of a member within outer structure and, submember refers to name of the member within the embedded structure. e.g. customer.lastpayment.month /* to read input of a customer and write out it’s information again */ #include<stdio.h> struct date { int month; int day; int year; }; struct account { int acctno; char acct_type; char name[80]; int balance; struct date lastpayment; }customer[100]; main() { int i,n; printf(“n How many no. of cusstomer?”); scanf(“%d”,&n); for(i=0;i<n;i++) readinput(); for(i=0;i<n;i++) writeoutput(); } 4
  • 5. void writeoutput(int i) { printf(“n Customer No.: %d”,i+1); printf(“Name : %s”,customer[i].name ); printf(“Account Number : %d “,customer[i].acctno ); printf(“Account Type : %c “,customer[i].acct_type ); printf(“Balance : %d “,customer[i].balance ); printf(“Payment Date : %d/%d/%d “,customer[i].lastpayment.month, customer[i].lastpayment.day, customer[i].lastpayment.year); } void readinput(int i) { printf(“n Customer No.: %d”,i+1); printf(“Name : “); scanf(“%[^n] “,customer[i].name ); printf(“Account Number : “); scanf(“%d “,&customer[i].acctno ); printf(“Account Type : “); scanf(“%c “,&customer[i].acct_type ); printf(“Balance : “); scanf(“%d “,&customer[i].balance ); printf(“Payment Date : “); scanf(“%d/%d/%d“,&customer[i].lastpayment.month, &customer.lastpayment.day, &customer.lastpayment.year); } User Defined data types(typedef) In c, the data type of any identity can be customized by the user. i.e. new data type can also be made so that such type can be used to define any identities. typedef is the keyword, which enables users to define new data type equivalent to existing data types. Such user defined data types can be used any new variables, arrays, structures. New data type can be defined as follows: typedef type new_type; e.g. typedef int age; age male female; and, is equivalent to int male, female; Similarly, typedef float cust[100]; cust newcust,oldcust; or, typedef float cust; cust newcust[100],oldcust[100]; By the same way, it can also be used to define a structure too. It removes the repeatition of struct tag. In general, 5
  • 6. typdef struct{ member 1; member 2; ............... member m; }new_type; e.g. typedef struct{ int acctno; char acct_type; name[80]; float balance; }record; record oldcustomer,newcustomer; Here, record is defined as new structure data type and newly define data type is used to define structure variables oldcustomer and newcustomer. Different ways of declaration of structures typedef struct { int month; int day; int year; }date; typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }record; record customer[100]; typedef struct { int month; int day; int year; }date; typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }record[100]; record customer; typedef struct { int month; int day; int year; }date; struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }customer[100]; Structures and Pointers The beginning address of a structure can also be accessed in the same manner as other address, using &(address) operator. So, a variable represents a structure, it can also be represented its address as &variable and pointer to the structure can be denoted as *variable. such as type *ptvar; A pointer to a structure can be defined as follows: 6
  • 7. e.g. typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }account; account customer, *pc=&customer; typedef struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; } customer, *pc=&customer; Here, customer is a structure variable of type account and pc is a pointer variable whose object is account type structure. The beginning address of the structure can be accessed as pc=&customer; Generally, each member of structure can be accessed by using selection operator as ptvar -> member which is equivalent to variable.member The -> operator can be combined to period (.) operator and their associativity is left to right. Similarly, it can be used for array too. ptvar ->member[expn] typedef struct { int month; int day; int year; }date; struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; } customer, *pc=&customer; So, if we want to access customer’s account number, then we can write any one of these customer.acctno pc->acctno (*pc).acct_no Similary, for month of last payment, customer.lastpayment.month pc->lastpayment.month (*pc).lastpayment.month If the structure is defined as: struct { int *acctno; char *acct_type; char *name; 7
  • 8. float *balance; date lastpayment; } customer, *pc=&customer; So, if we want to access customer’s account number, then we can write any one of these *customer.acctno *pc->acctno *(*pc).acct_no struct2.cpp /* To access data items from members of structure */ #include<stdio.h> #include<conio.h> void main() { int n=111; char t='c'; float b=99.99; char name[20]="srijan"; int d=25; typedef struct { int *month; int *day; int *year; }date; struct { int *acctno; char *acct_type; char *name; float *balance; date lastpayment; }customer,*pc=&customer; pc->acctno=&n; customer.acct_type=&t; customer.name=name; customer.balance=&b; *customer.lastpayment.day=25; clrscr(); printf("n%d %c %s %.2f %d", *customer.acctno, *customer.acct_type, customer.name, *customer.balance, *customer.lastpayment.day); printf("n%d %c %s %.2f %d",*(*pc).acctno,*pc->acct_type, pc->name,*pc->balance,*pc->lastpayment.day); 8
  • 9. getch(); } struct3.cpp /* To determine the size of a structure and it's address */ #include<stdio.h> #include<conio.h> void main() { clrscr(); typedef struct { int month; int day; int year; }date; struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }customer, *pc=&customer; printf("nNumber of bytes %d",sizeof *pc); printf("nstarting address : %d",pc); printf("nstarting address : %d",++pc); getch(); } Passing structure to a function A structure can generally be passed to a function by two ways. Either, individual members can be passed to a function or entire structure can be passed to a function. By the same way a single member can be returned back to the function reference or entire structure. In general, void main() { typedef struct { int month; int day; int year; }date; 9
  • 10. struct { int acctno; char acct_type; char name[80]; float balance; date lastpayment; }customer; float modify(char name[], int acctno, float balance); .................... customer.balance = modify(name, acctno, balance); .................... } float modify(char name[], int acctno, float balance) { float newbalance; .................... newbalance = .........; return(newbalance); } In this example, individual member is passed to a function and the new value is returned back to a member of a structure. struct4.cpp /* To pass an entire structure to a function*/ #include<stdio.h> #include<conio.h> typedef struct { int acctno; char acct_type; char *name; float balance; }record; void main() { void modify(record *pc); record customer={101,'c',"Anup",5000.00}; printf("n%d %c %s %.2f",customer.acctno,customer.acct_type,customer.name,customer.balance); modify(&customer); printf("nn%d %c %s %.2f", customer.acctno, customer.acct_type, customer.name, customer.balance); 10
  • 11. getch(); } void modify(record *pc) { pc->acctno=999; pc->acct_type='d'; pc->name="Sabin"; pc->balance=99999.99; } In this example, it passes entire structure to the function with it's address, then modifies values of member of the structure and finally returns back to the function reference with modified values of the structure. struct5.cpp /*to illustrate how an array of structure is passed to a function, and how a pointer to a particular structure is returned */ #include<stdio.h> #include<conio.h> #define N 3 typedef struct { int acctno; char acct_type; char *name; float balance; }record; void main() { static record customer[N]={ {101,'c',"Anup",5000.00}, {102,'d',"Anil",9000.00}, {103,'o',"Sabina",7000.00} }; int ano; record *pc; record *search(record table[N], int ano); do{ printf("n Enter the record no. to be searched, type 0 to end"); scanf("%d",&ano); pc=search(customer,ano); if(pc!=0) { printf("n Name : %s",pc->name); printf("n Account No. : %d",pc->acctno); 11
  • 12. printf("n Account type : %c",pc->acct_type); printf("n Balance : %.2f",pc->balance); } else printf("n Error - Record not found"); } while(ano!=0) } record *search(record table[N], int ano) { int i; for(i=0;i<N;i++) if(table[i].acctno==ano) return(&table[i]); return(0); } Unions It is similar to a structure which may contain individual data item may be different data types of same storage class. Each member of the structure is assigned its own unique storage area in memory whereas all members of a union share the same storage area in memory. It reserves the space equivalent to that of member which requires highest memory. So, it is used to conserve memory. It is useful to such applications, where all members need not to be assigned value at the same time. If assigned, it will produce meaningless result. In general, union tag { member 1; member 2; ............... member m; }; storage-class union tag variable1, variable2, ..........variable n; or, combined form, storage-class union tag { member 1; member 2; ............... member m; }variable1, variable2, ..........variable n; e.g. union id{ char color[12]; int size; }shirt, blouse; 12
  • 13. Here we've two union variables, shirt and blouse of type id and occupies 12 bytes in memory, however value is assigned to any union variable. e.g. union id{ char color[12]; int size; }; struct clothes{ char manufacturer[20]; float cost; union id description; }shirt, blouse; Here, shirt and blouse are structure clothes type variables. Each variable contains manufacturer, cost and either of color or size. Each individual member can be accessed in the same way as structure using . and -> operators. struct6.cpp /* a program using union */ # include <stdio.h> #include<conio.h> void main() { clrscr(); union id{ char color[12]; int size; }; struct clothes{ char manufacturer[20]; float cost; union id description; }shirt, blouse; printf("%d",sizeof(union id)); scanf("%s",shirt.description.color); printf("n %s %d ", shirt.description.color, shirt.description.size); shirt.description.size=12; printf("n %s %d ", shirt.description.color, shirt.description.size); getch(); } struct7.cpp 13
  • 14. #include<stdio.h> #include<conio.h> #include<math.h> typedef union { float fexp; // floating point exponent int nexp; // integer exponent }nvals; typedef struct{ float x; char flag; nvals exp; }values; void main() { values a; float power(values a); int i; float n,y; printf("y=x^nn enter value of x:"); scanf("%f",&a.x); printf("enter value for n: "); scanf("%f",&n); i=(int) n; a.flag=(i==n) ?'i' : 'f'; if(a.flag == 'i') a.exp.nexp = i; else a.exp.fexp=n; if(a.flag=='f' && a.x<=0.0) { printf("ERROR cannot raise negative no. to a"); printf("floating point power"); } else { y=power(a); printf("n y=%.4f",y); } getch(); } float power(values a) { int i; float y=a.x; 14
  • 15. if(a.flag=='i') { if(a.exp.nexp==0) y=1.0; else { for(i=1;i<abs(a.exp.nexp);i++) { y*=a.x; if(a.exp.nexp<0) y=1.0/y; } } } else y=exp(a.exp.fexp*log(a.x)); //y=exp(n(log(x))) return(y); } What is a structure? How does a structure differ from an array? What is member? Write down the relation between member and structure? What is the purpose of the typedef feature? How is this feature used in conjuction with structures? What is a union? How does a union differ from a structure? 15
  • 16. Self Referential Structures It is sometimes desirable to include within a structure one member that is a pointer to the parent structure type. Generally, struct tag { member 1; member 2; ........... struct tag *name; }; where name refers to the name of a pointer variable. Thus the structure of type tag will have a member that points to another structure of type tag. Such structure is known as Self-referential structure. eg. struct list{ char item[40]; struct list *name; }; 16