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

PPS2-UNIT-1 (1)

The document explains the concept of structures in C programming, which allows grouping of different data types under a single name for easier data management. It covers defining structures, declaring structure variables, accessing members, initializing structures, and operations such as copying and comparing structure variables. Additionally, it discusses nested structures and provides various examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

PPS2-UNIT-1 (1)

The document explains the concept of structures in C programming, which allows grouping of different data types under a single name for easier data management. It covers defining structures, declaring structure variables, accessing members, initializing structures, and operations such as copying and comparing structure variables. Additionally, it discusses nested structures and provides various examples to illustrate these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit-1

STRUCTURES AND UNIONS


As we have seen earlier, Arrays can be used to represent a group of data items that belong to
the same data type, such as int (or) float. However we cannot use an array if we want to represent a
collection of data items of different types using a single name. Fortunately, c supports a constructed
data type known as structures which is a mechanism for packing of data belong to different data
types. A structure is a convenient tool for handling a group of logically related data items. For
example is an employee record that consists of the name, date of birth, address, salary, ID
number etc. of the person involved. A structure allows the programmer to group all these
properties into one unit. Structures help to organize complex data in a more meaningful way.
Examples:
1. time : seconds,minutes,hours
2. date : day,month,year
3. book : author,title,price,year
4. address : name,doornumber,street,city
5. customer : name,telephone,city,catagory
Features of Structures:
1. To copy elements of one array to another array of same data type elements are copied one by
one. It is not possible to copy elements at a time. Where as in structure it is possible to copy
the contents of all structure elements of different data types to another structure variable of its
type using assignment (=) operator. It is possible because structure elements are stored in
successive memory locations.
2. Nesting of structures is possible i.e. one can create structure within the structure. Using this
feature one can handle complex data types.
3. It is possible to pass structure elements to a function. This is similar to passing an ordinary
variable to a function. One can pass individual structure elements (or) entire structure by
value (or) address.
4. It is also possible to create structure pointers. We can also create a pointer pointing to
structure elements. For this we require “->‟ operator.

Define a structure:
Definition: A structure is a collection of one or more variables grouped together under a single name
for convenient handling. Here the variables that are grouped together can have different types.
(or)
A structure is a collection of heterogeneous data elements.

Page 1
(or)
C Structure is a collection of different data types which are grouped together and each element in a C
structure is called member.
1. If you want to access structure members in C, structure variable should be declared.
2. Many structure variables can be declared for same structure and memory will be allocated for each
separately.
3. It is a best practice to initialize a structure to null while declaring, if we don’t assign any values to
structure members.
Defining a structure: structure must be defined first their format and that may be used later to
declare structure variables. Structure is defined using a keyword struct followed by the name of the
structure (optional) followed by the body of the structure. The members of the structure are declared
within the structure body. The general format of defining a structure is
Syntax: struct struct-name
{
data_type var-name1;
data_type var-name2;
.
.
data_type var-nameN;
};
Example: struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of structure members(or)structure
elements .Each member may belong to a different type .structure name is the identifier which
represents the name of the structure and is also called as structure tag. The tag name may be used
subsequently to declare variables that have the tags structure. The structure body contains structure
members(or)structure elements .For example
Example: struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
Declaring structure variables: After defining a structure format we can declare variables of that
type. we can declare structure variables using the structure-tag anywhere in the program. A structure
variable declaration is similar to the declaration of variables of any other data types. It includes the
following elements.

Page 2
1. The keyword struct
2. The structure tag name
3. List of variable names separated by commas
4. A terminating semicolon
Syntax: struct structure_tag structure_var1, structure _var2,........structure _varN;
Example: struct book_bank book1,book2,book3;
Each one of the variables has four members as specified by the template.
The complete declaration may look like this
Declaring Structure variables separately:
syntax: struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};struct book_bank book1,book2,book3;
Remember that the members of a structure themselves are not variables. They do not occupy any
memory until they are associated with the structure variables.
Declaring Structure Variables with Structure definition (or) Tagged structure:
Tagged structure: It is also allowed to combine both the template declaration and variable
declaration in one statement.

Syntax: struct book_bank


{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
variable structure: The use of tag name is optional
syntax: struct
{
char title[20];
char author[15];
int pages;
float price;
} book1,book2,book3;
The above declares book1,book2, book3 as structure variables representing three books, but does not
include a tag name. However, this approach is not recommended for two reasons.
1. Without a tag name, we cannot use it for future declarations
2. Normally, structure definitions appear at the time of beginning of the program file, before any
variables (or) functions are defined. They may also appear before the main, along with macro

Page 3
definitions, such as #define. In such cases, the definition is global and can be used by other
functions as well.
Accessing the Members of a structure: we can access and assign values to the members of
structure in a number of ways. As we mentioned earlier, the members of the structure themselves are
not the variables. They should be linked to the structure variable in order to make them meaningful
members. The link between a member and a variable is established using the member operator '.'
which is also known as 'dot operator'(or) period operator.
For example, book1.price is the variable representing the price of book1.
Here we can see how we would assign values to the members of book1
strcpy(book1.title,”basic”);
strcpy(book1.author,”balagurusamy”);
book1.pages=240;
book1.price=120.36;
We can also use scanf to give the values through the keyboard
scanf(“%s”,book1.title);
scanf(“%d”,&book1.pages);
Example: Define a structure type, struct personal that would contain person name, date of
joining and salary, using this structure, write a c program to read this information for one
person from the keyboard and print the same on the screen.
#include<stdio.h>
struct personal
{
char name[20];
int day;
char month [10];
int year;
float salary;
};
main()
{
struct personal person;
printf(“input values”);
scanf(“%s%d%s%d%f”,person.name,&person.day, person.month,
&person.year,&person.salary);
printf(“Person Name: %s\n Daay:%d\n Month:%d\n Year:%d\n Salary:
%f”,person.name,person.day,person.month,person.year,person.salary);
}

Page 4
Example #include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
} record;
main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Example: #include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
}
Output: Book 1 title : C Programming

Page 5
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

Structure Initialization: Like other variables, a structure variable also can be initialized at compile
time.
Syntax: main()
{
struct
{
int age;
float height;
} student={50,150.96};
-------------------------------
-------------------------------
}
The above syntax assigns the value 50 to student.age and 150.96to student.height. There is one to
one correspondence between the members and their initializing values.
Suppose you want to initialize more than one structure variable
syntax: main()
{
struct st_record
{
int age;
float height;
};
struct st_record student1={50,150.96};
struct st_record student2={30,120.16};
-------------------------------
-------------------------------
}
we have another method to initialize a structure variable outside of the function.\
syntax: struct st_record
{
int age;
float height;
}student1={50,150.96};
main()
{
struct st_record student2={30,120.16};
-------------------------------
-------------------------------
}
Note that compile time initialization of a structure variable must have the following elements.

Page 6
1. The keyword struct
2. The structure tag name
3. The name of the variable to be declared
4. The assignment operator '='
5. A set of values for the members of the structure variable, separated by commas and enclosed
in braces.
6. A terminating semicolon.

Rules for initializing structures:


1. We cannot initialize individual members inside the structure template.
2. The order of values enclosed in braces must match the order of members in the structure
definition.
3. It is permitted to have partial initialization. we can initialize only the first few members and
leave the remaining blank. The uninitialized members should be only at the end of the list.
4. The uninitialized members will be assigned default values as follows.
1. zero for integer and floating point numbers.
2. '\0' for character strings.
Example: write program for demonstrating structure member initialization
#include<stdio.h>
void main()
{
struct student /*Declaraing the student structure*/
{
int marks1,marks2,parks3;
};
struct student std1=(55,66,80):/*initializing ,marks for student 1*/
struct student std2=(60,85,78):/initializing marks for student 2*/
clrscr();
/*Displaying marks for student 1*/
print(“marks obtained by 1st student: %d and %d”,std1.marks1,std1.marks2.std1.marks3);
/*Displaying marks for student 2*/
printf(*\nMarks obtained by 2nd student: %d.%d”,std2.marks1.std2.marks2.std2.marks3);
getch();
}
Copying & Comparing Structure Variables: Two variables of the same structure type can be
copied the same way as ordinary variables. If person1 and person2 belongs to the same structure,
then the fallowing assignment operations are valid:
person1 = person2; ------ assigns person1 to person2
person2 = person1; ------ assigns person2 to person1
However, the statements such as,
person1 = = person2
person1! = person 2 are not permitted.
Page 7
C does not permit any logical operations on structure variables. In such cases, we need to compare
them by comparing the members individually.
Example: program to illustrate the comparison & copying of structure variables
#include<stdio.h>
struct class
{
int no;
char name[20];
float per;
};
main()
{
int x;
struct class stu1={111,”Ramu”,72.50};
struct class stu2={222,”Reddy”,67.00};
struct class stu3;
stu3=stu2;
x=(stu2.no==stu3.no&&stu2.per==stu3.per)?1:0;
if(x==1)
printf(“\n student2 and student3 are same\n”);
else
printf(“\n student2 and student3 are different\n”);
}
Operations on Individual Members of the Structure: As pointed earlier, the individual members
are identified using the member operator (.). A member with the dot operator along with its structure
variable can be treated like any other variable name and therefore it can be manipulated using
expressions and operators. Consider the previous example program; we can perform the following
operations.
if( stu1.no = = 111)
stu1.per +=10.00;
float sum =stu1. per + stu2.per;
stu2.per *= 0.5;
We can also apply the increment and decrement operators to numeric type members. For example,
the following statements are valid:
stu1.no++;
++ stu2.no;
Example: C Program to Store Information (name, roll and marks) of a Student Using Structure
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};
main()
Page 8
{
struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
}
Output: Enter information of students:
Enter name: Adele
Enter roll number: 21
Enter marks: 334.5
Displaying Information
name: Adele
Roll: 21
Marks: 334.50
Structures within Structures [Nested Structures]: A structure within a structure means nesting of
structures. Nesting of structures is permitted in C. Let us consider the fallowing structure defined to
store information about the salary of employees.
struct salary
{
char name[20];
char dept[20];
int basic_pay;
int dearness_allowance;
int house_rent_allowance;
int city_allowance;
} employee;
This structure defines name, department, basic pay and three kinds of allowances. We can group all
the items related to allowances together and declare them under a substructure as shown below:
struct salary
{
char name[20];
char dept[20];
struct
{
int dearness;
int house_rent;
int city;
} allowance;
} employee;

Page 9
The “salary‟ structure contains a member named „allowance‟, which itself is a structure with three
members. The members contained in the inner structure namely, dearness, house_rent, and city.
These members can be referred to as:
employee.allowance.dearness;
employee.allowance.house_rent;
employee.allowance.city;
An inner-most member in a nested-structure can be accessed by chaining all the concerned structure
variables (from outer-most to inner-most) with the member using the dot operator. The fallowing
statements are invalid:
employee.allowance ------------- actual member is missing
employee.house_rent ------------- inner structure variable is missing
We can also use tag names to define inner structures. For example,
struct pay
{
int da;
int hra;
};
struct salary
{
char name[10];
struct pay allowance;
struct pay arrears;
};
struct salary employee [100];
Here, pay template is defined outside the salary template and is used to define the structure of
allowance and arrears inside the salary structure. C permits nesting up to 15 levels
The pay structure members can be referred to as:
employee.allowance.da;
employee.allowance.hra;
employee.arrears.da;
employee.arrears.hra;
Example: #include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
Page 10
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
int main()
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee SSN : %d",emp.ssn);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d",
emp.doj.date,emp.doj.month,emp.doj.year);
}
Output : Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
Example: implement following student information fields using nested structures
#include<stdio.h>
#include<conio.h>
void main()
{
struct student;
{
int roll_no;
struct name
{
char First[20];
char Middle[20];
char Last[20];
}st_name;
struct dob
{
int day ,month,year;
}std_dob;
struct course
{
char elective 1[20];
char elective2[20];
}st_course;
};
struct student std1;
clrscr();
std.roll_no=34;
strcpy(sdt1.st_name.First,”Krishna”);
strcpy(sdt1.st_name.Middle,”sai”);
strcpy(sdt1.st_name.Last,”reddy”);
std1.st_dob.day=21;
std1.st_dob.month=12;
std1.st_dob.year=1993;
strcpy(std1.st_course.elective1,”Mechanics”);
strcpy(std1.st_course.elective2,”Animation”);
Printf(“\nRoll No.:%d”,std1.Roll _No);
Printf(“\n Name: %s%s%s”,
std1.st_name.First,std1.st_name.Middle,std1.st_name.Last);
Page 11
Printf(“\n Date of birth(DD MM YYYY):%d%d%d”,
std1.st_dob.day,std1.st_dob.Month,std1.st_dob.Year);
Printf(“\ncourse electives:%s&%s”,
std1.st_course.elective1,std1.st_course.elcetive2);
getch();
}

Example: Implement the following employee information fields using nested structures
#include<stdio.h>
#include<conio.h>
void main()
{
struct employee
{
int emp_id;
struct name
{
char First[20];
char Mibble[20];
char Last[20];
}emp_name;
char doj[20];
struct G_sal
{
float basic,HRA;
float spl_allow;
}emp_sal;
};
struct employee emp1l
clrscr();
emp1.emp_id=37;
strcpy(emp1.emp_name.first,”M”);
strcpy(emp1.emp_name.middle,”Mahesh”);
strcpy(emp1.emp_name.last,”reddy”);
strcpy(emp1.doj,”22/10/2004”);
emp1.emp_sal.basic=17432.00;
emp1.emp_sal.HRA=10032.00;
emp1.emp_sal.spl_allow=5000.00;
Printf(“\n emp id:%d”, emp1.emp_id);
Printf(“\n name:%s%s%s”,emp1.emp_name.First ,emp1.emp_name.Middle
,emp1.emp_name.Last);
Printf(“\n date of joining (DD MM YYYY): %s”,emp1.doj);
Printf(“\n Gross salary:%.2f”,
emp1.emp_sal.basic+emp1.emp_sal.HRA+emp1.emp_sal.spl_allow);
getch();
}

Page 12
Arrays of Structures: As you know, C Structure is a collection of different data types ( variables )
which are grouped together. Whereas, an array of structures is nothing but a collection of structures.
Arrays of structures represent each element of an array must be structure type. For example, in
analyzing the marks obtained by a class of students, we may use a template to describe student name
and marks obtained in various subjects and then declare all the students as structure variables. In
such cases, we may declare an array of structures, each element of the array representing a structure
variable.

Syntax: struct structurename


{
datatype var1;
datatype var2;
.
.
datatype varN;
}structurevariable[size];
(or)
struct structurename structurevariable[size];
Example: struct class student [100];
The above defines an array called „student‟ that consists of 100 elements. Each element is defined
to be of the type struct class.
Consider the following declaration:
struct marks
{
int eng;
int tel;
int sci;
};
main( )
{
struct marks student[3]={45,76,87},{78,68,79},{34,23,14};
................
................
}
This declares the student as an array of three elements student [0], student [1],student [2] and
initializes the members as follows:
student[0].eng=45;
student[0].tel=76;
.......................
.......................
student[2].sci=14;

Page 13
Example: write a program to calculate the subject-wise and student-wise totals and store as a
part of the structure
#include<stdio.h>
struct marks
{
int eng;
int tel;
int sci;
int tot;
};
main( )
{
int i;
struct marks student[3]={{45,67,81,0},{75,53,69,0},{57,36,71,0}};
struct marks t={0,0,0,0};
for(i=0;i<3;i++)
{
student[i].tot=student[i].eng+student[i].tel+student[i].sci;
t.eng=t.eng+student[i].eng;
t.tel=t.tel+student[i].tel;
t.sci=t.sci+student[i].sci;
t.tot=t.tot+student[i].tot;
}
printf(" STUDENT TOTAL \n\n");
for(i=0;i<3;i++)
printf("stu[%d] : %d\n",i+1,student[i].tot);
printf("SUBJECT TOTAL\n\n");
printf("English:%d\nTelugu:%d\nScience :%d\n",t.eng,t.tel,t.sci);
printf("\n Grand total : %d\n",t.tot);

}
Example2: Write a program to enter 5 dates. Store this information in array of structures
#include<stdio.h>
struct date
{
int day, year;
char month[10];
} b_days [5];
main( )
{
int i;
for(i=0;i<5;i++)
{
printf(“\nEnter 5 dates:”);
scanf(“%d %d %s”,&b_days[i].day, &b_days[i].year, b-
days[i].month);
}
for(i=0;i<5;i++)
{
printf(“\nbirth day dates are %d %d %s”, b_days[i].day,
b_days[i].year,b_days[i].month);
}

Page 14
}
Arrays within Structures: C permits the use of array as structure members. We have already used
arrays of characters inside the structure. Similarly, we can use single or multi-dimensional arrays of
type either int or float.
Example:
struct marks
{
int no;
int sub[5];
float fee;
} stu [10];
Here, the member „sub‟ containing 5 elements. These elements can be accessed using appropriate
subscripts. For example,
stu[1].sub[2];
would refer to the marks of third subject by the second student.

Example: Rewrite the program of above example 1 using an array member to represent the
three subjects.
#include<stdio.h>
main( )
{
struct marks
{
int sub[3];
int total;
};
struct marks student[3]= {10,20,30,0,10,20,30,0,10,20,30,0};
struct marks t={0,0,0,0};
int i,j,k=0;
clrscr();
for(i=0;i<=2;i++,k++) /* „i? represent student*/
{
for(j=0;j<=2;j++) /* „j? represent subjects */
{
student[i].total+=student[i].sub[j];
t.sub[i]+=student[i].sub[i];
}

t. total+= student[i].total;
}

printf("\nSTUDENT TOTAL\n\n");
for(i=0;i<=2;i++)
printf("student[%d] %d\n", i+1,student[i].total);
printf("\nSUBJECT TOTAL\n\n");
for(k=0;k<=2;k++)
printf("subject-%d\t %d\n",k+1,t.sub[k]);
printf("\nGrand Total = %d\n", t.total);
getch();
}

Page 15
Structures and Functions: C supports the passing of structure values as arguments to a function.
There are three methods by which the values of a structure can be transferred from one function to
another.
1. The first method is to pass each member of the structure as an actual argument of the function
call. The actual arguments are then read independently like ordinary variables. This is the
most elementary approach and becomes unmanageable and inefficient when the structure size
is large.
2. The second method involves passing of a copy of the entire structure to the called function
[Like, call by value]. Since the function is working on a copy of the structure, any changes to
the structure members within the function are not reflected in the original structure.
Therefore, it is necessary for the function to return the entire structure back to the calling
function.
Note: All the compilers may not support this method of passing the entire structure as a
parameter.
3. The third approach employs a concept called pointers to pass the structure as an argument. In
this case, the address location of the structure is passed to the called function. The function
can access indirectly the entire structure and work on it. This is similar to the way, arrays are
passed to functions. This method is more efficient as compared to the second one.
Passing individual structure member as an argument to a function: Here we can pass individual
structure members as an argument to a function.
Example: Write a c program to simulate the multiplication of two fractions by passing
individual structure members to a function
#include<stdio.h>
struct fraction
{
int num;
int denom;
};
struct fraction multiply(int,int,int,int);
main()
{
struct fraction f1,f2,result;
printf("\nEnter numerator and denominator of first fraction:");
scanf("%d%d",&f1.num,&f2.denom);
printf("\nEnter numerator and denominator of second fraction:");
scanf("%d%d",&f2.num,&f2.denom);
result=multiply(f1.num,f1.denom,f2.num,f2.denom);
printf("\nThe result after multiplication of two fractions is:");
printf("\n%d / %d",result.num,result.denom);
}
struct fraction multiply(int a,int b,int x,int y)
{

Page 16
struct fraction r;
r.num=a*x;
r.denom=b*y;
return r;
}
Passing structure by value (call by value):A structure variable can be passed as an argument as
normal variable to the called function. If structure is passed by value, change made in structure
variable in the called function does not reflect in original structure variable in the calling function.
General format of sending a copy of a structure to the called function:
function name (structure_variable_name);
The called function takes the fallowing form:
data type function name (struct_type structvariablename)
{
-----------
-----------
return (expression);
}
Important points to remember:
1. The called function must be declared for its type, appropriate to the data type it is expected to
return. For example, if it is returning a copy of the entire structure, then it must be declared as
struct with an appropriate tag name.
2. The structure variable used as the actual argument and the corresponding formal argument in
the called function must be of the same struct type.
3. The return statement is necessary only when the function is returning some data. The
expression may be any simple variable or structure variable or an expression using simple
variables.
4. When a function returns a structure variable, it must be assigned to a structure variable of
identical type in the calling function.
5. The called function must be declared in the calling function, if it is placed after the calling
function.
Example: Write a c program which illustrates sending a structure variable through call by
value.
#include<stdio.h>
#include<string.h>
struct sbook
{
int pages;
float price;
char title[20],author[30],publisher[30];
};

Page 17
void dispalybook(struct sbook book1)
{
book1.price+=10.00;
book1.pages+=20;
}
main()
{
struct sbook sb={“c language”, “Balaguruswamy”,100.65,25, “technical”);
printf(“\n The book details before the functioncall is”);
printf(“Titles:%s”,book1.title);
printf(“Author:%s”,book1.author);
printf(“Price:%f”,book1.price);
printf(“pages:%d”,book1.pages);
printf(“Publisher:%s”,book1.publisher);
displaybook(sb);
printf(“\n The book details after the function call”);
printf(“Titles:%s”,book1.title);
printf(“Author:%s”,book1.author);
printf(“Price:%f”,book1.price);
printf(“pages:%d”,book1.pages);
printf(“Publisher:%s”,book1.publisher);
}

Example: Write a C program to create a structure student, containing name and roll. Ask user
the name and roll of a student in main function. Pass this structure to a function and display
the information in that function.
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void Display(struct student stu);
main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s",s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); / * passing structure variable s1 as argument */
}
void Display(struct student stu)
{
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}

Page 18
Example: Write a simple program to illustrate the method of sending an entire structure as a
parameter to a function(Passing a copy of the entire structure as an argument to a function).
#include<stdio.h>
#include<conio.h>
struct stores
{
char name[20];
float price;
int qty;
};
main( )
{
struct stores update(struct stores,float,int);
float mul(struct stores);
float p_inc,val;
int q_inc;
struct stores item={"pen",5.50,10};
printf("\nInput increment values :");
printf("\nprice increment and quantity increment\n");
scanf("%f %d",&p_inc,&q_inc);
item=update(item,p_inc,q_inc); /*function call*/
printf("\nUpdate values of item:\n");
printf("Name :%s\n",item.name);
printf("Price:%f\n",item.price);
printf("Quantity :%d\n",item.qty);
val=mul(item); /*function call*/
printf("\nValue of the item=%f\n",val);
}
struct stores update(struct stores prod,float p,int q)
{
prod.price+=p;
prod.qty+=q;
return(prod);
}
float mul(struct stores stock)
{
return(stock.price * stock.qty);
}
Example: Write a c program to simulate the multiplication of two fractions by passing entire
structure as an argument to a function.
#include<stdio.h>
struct fraction
{
int num;
int denom;
};
struct fraction multiply(struct fraction,struct fraction);
main()
{
struct fraction f1,f2,result;
printf("\nEnter numerator and denominator of first fraction:");

Page 19
scanf("%d%d",&f1.num,&f1.denom);
printf("\nEnter numerator and denominator of second fraction:");
scanf("%d%d",&f2.num,&f2.denom);
result=multiply(f1,f2);
printf("\nThe result after multiplication of two fractions is:");
printf("\n%d / %d",result.num, result.denom);
}
struct fraction multiply(struct fraction x struct fraction y)
{
struct fraction r;
r.num=x.num*y.num;
r.denom=x.denom*y.denom;
return r;
}
Passing structure by reference (call by reference): An address of structure variable can be passed
as an argument to the called function. If structure is passed by reference, any change made in
structure variable in the called function does reflect in original structure variable in the calling
function.
General format of sending address of a structure to the called function:
function name (&structure_variable_name);
The called function takes the fallowing form:
data type function name (struct_type *structvariablename)
{
-----------
----------- }
Example: Example: program on passing address of a structure variable.
#include<stdio.h>
main( )
{
struct book
{
char title[25];
char author[25];
int no;
};
struct book b={“ ANURAG C Notes”,”pps2”,9};
clrscr();
printf(“The book details before the function call”);
printf(%s\n %s\n %d\n”,b.tittle,b.author,b.no);
display(&b);
printf(“The book details after the function call”);
printf(%s\n %s\n %d\n”,b.tittle,b.author,b.no);
}
display(struct book *b)
{
b->no+=20;
}

Page 20
Pointers to Structures: We know that the name of an array stands for the address of its 0th element.
The same thing is applicable for the arrays of structure variables. The way we can have a pointer
pointing to an int, or a pointer pointing to a char, similarly we can have a pointer pointing to the
structure variables (Such pointers are known as structure pointers) but for accessing you have to use
arrow operator(->) or member selection operator and it is made up of minus and a greater than sign.
Consider the following declaration:
struct inventory
{
char name[30];
int number;
float price;
}product[2], *ptr;
This statement declares that, product as an array of 2 elements, each of the type struct inventory and
ptr as a pointer to the data objects of the type struct inventory.
The assignment statement would assign the address of 0 th element of product to ptr.
ptr = product;
That is, the pointer ptr points to product[0]. Its members can be accessed using the following
notation.
ptr -> name;
ptr->number;
ptr->price;
The symbol -> is called as the arrow operator and it is comprised of a minus sign & a greater than
sign. Note that ptr-> is simply another way of writing product [0].
Whenever the pointer is incremented by one, it is made to point to the next record,i.e., product[1].
We could also use the following notation,
(*ptr).name to access the member name.
Note: The parenthesis around *ptr are necessary because, the member operator (.) has higher
precedence than the operator *.
While using the structures pointers, we should take care of the precedence of operators. The
operators ->, “.‟, ( ), [ ] have the highest priority among the operators.
They bind very tightly with their operands. For example, consider the following definition:
struct xyz
{
int count;
float *p; /* Pointer inside the struct xyz */
} *ptr; /* struct xyz type pointer */

Page 21
For the above definition, the statement,++ptr->count; increments count, not ptr.However, the
following statement,
(++ptr) -> count; increments ptr first, and then links count.
The statement
ptr ++ -> count; is legal and increments ptr after accessing count.
The following statements also behave in the similar fashion.
*ptr-> p fetches whatever p points.
*ptr -> p++ Increments p after accessing whatever it points to.
(*ptr -> p)++ Increments whatever p points.
*ptr++ -> p Increments ptr after accessing whatever it points to.
We are already discussed about passing of a structure as an argument to a function. We also saw an
example, where a function receives a copy of an entire structure and returns it after working on it. As
we mentioned earlier, this method is inefficient in terms of both, the execution speed and memory.
We can overcome this drawback by passing a pointer to the structure and then using this pointer to
work on the structure members.
Example: example program on structure pointers.
#include <stdio.h>
main( )
{
struct book
{
char title[25];
char author[25];
int no;
};
struct book b={“ AnuragC‟ Notes”,”DCSE”,9};
struct book *ptr;
ptr=&b;
printf(“%s %s %d\n”,b.tittle,b.author,b.no);
printf(“%s %s %d\n”, ptr->tittle,ptr->author,ptr->no);
}
Output: ANURAG C Notes DCSE 9
ANURAG C Notes DCSE 9
Explanation: The first printf( ) is as usual way of accessing the members of the structure. The
second printf( ) however is peculiar. We cannot use ptr.tittle, ptr.author and ptr.no because ptr is not
a structure variable but it is a pointer to a structure, and the dot operator requires a structure variable
on its left. So, In such cases C provides an operator -> called as an arrow operator to refers the
structure elements.
Example: C Program to illustrate the use structure pointers.
struct invent
{
char name[20];
Page 22
int number;
float price;
};

main( )
{
struct invent product[3], *p;
printf(“\n INPUT \n\n”);
for( p = product; p<product+3; p++)
scanf(“%s %d %f”,p->name, &p->number, &p->price);
printf(“\nOUTPUT\n\n”);
p=product;
while(p < product +3)
{
printf(“%-20s %5d %11.5f\n”, p->name, p -> number, p ->price);
p++;
}
}
Accessing Structure Members with Pointer:To access members of structure with

structure variable, we used the dot( .) Operator. But when we have a pointer of
structure type, we use arrow ->to access structure members.
#include<stdio.h>
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book b;
struct Book *ptr = &b;
ptr->name = "Dan Brown"; //Accessing Structure Members
ptr->price = 500;
}

#include<stdio.h>
struct team
{
char *name;
int members;
char captain[20];
}t1 = {"India",11,"Dhoni"} , *sptr = &t1;
main()
{
printf("\nTeam : %s",(*sptr).name);
printf("\nMemebers : %d",sptr->members);
printf("\nCaptain : %s",(*sptr).captain);
}

Page 23
Page 24
Example: write a program to implement the problem in example one using pointer notation.
#include<stdio.h>
#include<conio.h>
void main( )
{
struct student
{
int marks1,marks2,marks3;
}s1,s2;
struct student *std1,*std2;
std1=&s1;
std2=&s2;
std1->marks1=55;
std1->marks2=66;
std1->marks3=80;
std2->marks1=60;
std2->marks2=85;
std2->marks3=78;
Printf(“marks obtained by 1st student: %d , %d and %d”,
std1->marks1,std1->marks2,std1->marks3);
Printf(“\n marks obtained by second student: %d and %d”,
std2->marks1,std2->marks2,std2->marks3);
}
Example: implement the problem in example using pointer notation.
#include<stdio.h>
#include<conio.h>
void main()
{
struct student;
{
int marks1,marks2,marks3,sum;
float avg;
}s1;
struct student *std1;
std1=&s1;
Printf(Enter the marks obtained by the student in three subjects : “);
scanf(“%d%d%d “,&s1.marks1 ,&s1.marks2,&s1.marks3);
std1 ->sum=std->marks1+std1->marks2+std1->marks3;
std1->avg=(std1->marks1+std1->marks2+std1->marks3)/3;
Printf(“sum=%d\navg=%.2f”,std1->sum,std1->avg);
}
Size of structures: We normally use structures and arrays to create variables if larger sizes. The
actual size of these variables in terms of bytes may change form machine to machine. We may use
the unary operator sizeof() to tell us the size of a structure.
The expression,
sizeof(struct x)
will evaluate the number of bytes required to hold all the members of the structure x.
If y is a simple structure variable of type struct x, then the expression,
sizeof (y)
Page 25
would also give the same answer.However,if y is an array variable of type struct x.
Example: program to display the size of a structure variable.
#include<stdio.h>
#include<conio.h>
void main()
{
struct s
{
int a;
char b;
float c;
long d;
}s1;
Printf(“\n size of (s1)=%d”,sizeof(s1));
getch();
}
Example: program to display the size of a structure variable.
#include<stdio.h>
struct book
{
char bname[30];
int ssn;
int pages;
};
main()
{
struct book b1;
printf("\nSize of bname : %d",sizeof(b1.bname));
printf("\nSize of ssn : %d",sizeof(b1.ssn));
printf("\nSize of pages : %d",sizeof(b1.pages));
printf("\nSize of Structure : %d",sizeof(b1));
}

Page 26
Unions: Unions are a concept borrowed from structures and therefore it follows the same syntax as
structures. However there is major distinction between them is, in terms of storage. In structures,
each member has its own storage location, whereas all the members of a union use the same location.
This implies that, although a union may contain many members of different types, it can handle only
one member at a time. Like structures, a union can be declared using the keyword union as follows.
Definition: A union is a collection of heterogeneous data elements.
(or)
C Unions is a collection of different data types which are grouped together and each element in a C
structure is called member.
 If you want to access union members in C, union variable should be declared.
 Many union variables can be declared for same union and same memory will be allocated for
all members.
Defining a union: union must be defined first their format and that may be used later to declare
union variables. Union is defined using a keyword union followed by the name of the union-tag
followed by the body of the union. The members of the union are declared within the union body.
The general format of defining a union is
Syntax: union union-name
{
data_type var-name1;
data_type var-name2;
.
.
data_type var-nameN;
};
Example: union book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword union declares a union to hold the details of union members (or) union elements .Each
member may belong to a different type .union-name is the identifier which represents the name of
the union and is also called as union tag. The tag name may be used subsequently to declare
variables that have the tags union. The union body contains union members (or)union elements .For
example
Example: union book_bank
{
char title[20];
char author[15];
int pages;
float price;

Page 27
};
Declaring union variables: After defining a union format we can declare variables of that type.we
can declare union variables using the union_tag anywhere in the program. A union variable
declaration is similar to the declaration of variables of any other data types. It includes the following
elements.
 The keyword union
 The union tag name
 List of variable names separated by commas
 A terminating semicolon
Syntax: union union_tag union_var1,union _var2,........union _varN;
Example: union book_bank book1,book2,book3;
Example:
union class
{
int marks;
float average;
char grade;
} student;
The memory allocated to the union variables is not the sum of the memory sizes of all its members,
instead memory allocated for the union variable is equal to the largest member memory size. In the
above example memory is allocated for union variable student is 4 bytes only.and any member of
student can take value. But the value is stored in the allotted 4 bytes only. If another member takes
value, then the value previously taken by the other member is erased and new member value is stored
in the same 4 bytes.
Accessing Union elements: To access a union member we can use the same syntax that we use for
structure members.
Syntax: union_variablename.union_member_name;
Example: union class
{
int marks;
float average;
char grade;
} student;
Now we will see how to access union members
student.marks;
student.average; ....and so on.
During accessing, we should make sure that we are accessing the member whose value is currently
stored. For example, the statements such as,

Page 28
student.marks=65;
student.average=65.0;
printf(“%d”, student.marks);
would produce erroneous output (which is machine independent).
A union creates a storage location that can be used by any one of it's members at a time. When a
different member is assigned a new value, this new value supersedes the previous member's value.
Unions may be used in all places where a structure is allowed. The notation for accessing a union
member, which is nested inside a structure, remains the same as for the nested structures.
write a program that uses the sizeof operator to differentiate between structures and unions.
#include<stdio.h>
void main()
{
struct s
{
int a;
char b;
float c;
long d;
}s1;
union u
{
int a;
char b;
float c;
long d;
}ul;
Printf(“\n size of (s1) = %d”,sizeof(s1));
Printf(“\n size of (u1) = %d”,sizeof(ul));
}

Example: Write a C Program to use structure within union. Display the contents of structure
elements.
main( )
{
struct x
{
float f;
char p[2];
};
union z
{
struct x set;
}
union z st;
st.set.f = 5.5;
st.set.p[0]= 65;
st.set.p[1]=66;

Page 29
printf(“\n%f\t%c\t%c”, st.set.f,st.set.p[0],st.set.p[1]);
}
Difference between union and structure: Though unions are similar to structure in so many ways, the
difference between them is crucial to understand. This can be demonstrated by this example:

Write a C Progra to demonstrate Difference between union and structure


#include <stdio.h>
union job
{
char name[32];
float salary;
int worker_no;
}u;
struct job1
{
char name[32];
float salary;
int worker_no;
}s;
main()
{
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
}
Output: size of union = 32
size of structure = 40
There is difference in memory allocation between union and structure as suggested in above example. The
amount of memory required to store a structure variables is the sum of memory size of all members.

But, the memory required to store a union variable is the memory required for largest element of an union.

What difference does it make between structure and union?


As you know, all members of structure can be accessed at any time. But, only one member of union can be
accessed at a time in case of union and other members will contain garbage value.
Write a simple program to demonstrate the use of unions.

#include <stdio.h>
union job
{
char name[32];

Page 30
float salary;
int worker_no;
}u;
main()
{
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);
printf("Salary: %.1f",u.salary);
}
Output: Enter name Hillary
Enter salary 1234.23
Displaying
Name: f%Bary
Salary: 1234.2

Example: write a simple program to demonstrate the use of unions.


#include<stdio.h>
#include<conio.h>
void main()
{
union student
{
int rollno;
char result;
}st1.st2;
St1.rollno=34;
St2.result=’P’;
Printf(“\n rollno:%d”,st1.roll_no);
Printf(“\n Result:%c”,st2.result”);
Printf(“\n\n”);
Printf(“\nroll no:%d”,st2.roll_no”);
printf(“\nresult:%c”,st1.result”);
}

Page 31
Sno Structure Union
1 The keyword struct is used to define a The keyword union is used to define a union.
structure
2 When a variable is associated with a When a variable is associated with a union,the
structure, the compiler allocates the memory compiler allocates the memory by considering
for each member. The size of structure is the size of the largest memory. So, size of
greater than or equal to the sum of sizes of union is equal to the size of largest member.
its members. The smaller members may end
with unused slack bytes.

3 Each member within a structure is assigned Memory allocated is shared by individual


unique storage area of location. members of union.
4 The address of each member will be in The address is same for all the members of a
ascending order This indicates that memory union. This indicates that every member begins
for each member will start at different offset at the same offset value.
values.
5 Altering the value of a member will not Altering the value of any of the member will
affect other members of the structure. alter other member values.
6 Individual member can be accessed at a Only one member can be accessed at a time.
time
7 Several members of a structure can initialize Only the first member of a union can be
at once. initialized.

Page 32
typedef in C

The typedef is a keyword used in C programming to provide some meaningful names to the
already existing variable in the C program. It behaves similarly as we define the alias for the
commands. In short, we can say that this keyword is used to redefine the name of an already existing
variable.

Syntax of typedef

typedef <existing_name> <alias_name>

In the above syntax, 'existing_name' is the name of an already existing variable while 'alias
name' is another name given to the existing variable.

For example, suppose we want to create a variable of type unsigned int, then it becomes a tedious
task if we want to declare multiple variables of this type. To overcome the problem, we use a
typedef keyword.

1. typedef unsigned int unit;

In the above statements, we have declared the unit variable of type unsigned int by using a
typedef keyword.

Using typedef with structures

Consider the below structure declaration:

struct student
{
char name[20];
int age;
};
struct student s1;

In the above structure declaration, we have created the variable of student type by writing the
following statement:

struct student s1;

The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To avoid
such a big statement, we use the typedef keyword to create the variable of type student.

struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;

Page 33
In the above statement, we have declared the variable stud of type struct student. Now, we can use
the stud variable in a program to create the variables of type struct student.

The above typedef can be written as:

typedef struct student


{
char name[20];
int age;
} stud;
stud s1,s2;

From the above declarations, we conclude that typedef keyword reduces the length of the code and
complexity of data types. It also helps in understanding the program.

Write a C program to demonstrate typedef the structure declaration.

#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
Output
Enter the details of student s1:
Enter the name of the student: Peter
Enter the age of student: 28
Name of the student is : Peter
Age of the student is : 28

Page 34
Write a C program to demonstrate typedef the structure declaration to display employee
details.

#include <stdio.h>
typedef struct employee
{
int salary;
int id;
}emp;
int main()
{
emp e1,e2;
e1.salary = 14000;
e1.id = 1;
e2.salary = 12000;
e2.id = 2;
printf("typedef using struct!");
printf("Salary of the first employee is : %d\n", e1.salary);
printf("ID of the first employee is : %d\n", e1.id);
printf("Salary of the second employee is : %d\n", e2.salary);
printf("ID of the second employee is : %d\n", e2.id);
return 0;
}

Output :
typedef using struct!Salary of the first employee is : 14000
ID of the first employee is : 1
Salary of the second employee is : 12000
ID of the second employee is : 2

Page 35
ENUM
An enumeration provides the data type with a set of values. An enumeration constant is a
type of an integer. A variable type takes and stores the values of the enumeration set defined by that
type. Enumerations can be used with indexing expressions also as operands with arithmetic and
relational operators. Enumerations can be also be used as an alternate way to use “#define”.

Declaring an Enumeration
There are two different types of enumerations declarations:
Creating a named type: enum exampletype {THIS, IS, A, TEST};
Creating an unnamed type: enum {THIS, IS, ANOTHER, TEST};
Both examples work, it simply comes down to preference, and which one you seem to work faster
with.

Write example program to demonstrate working off enum in C


#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}

Output:
2
Write example program to demonstrate working off enum in C using week days
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}

Output:
The day number stored in d is 4

Page 36
Write a C program to use enum in a switch case statement.
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum days d;
d=monday;
switch(d)
{
case sunday:
printf("Today is sunday");
break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}

return 0;
}

Advantages of Enumerations
1. Numeric values are automatically assigned.
2. It allows your code to become generally understandable by others or yourself.
3. Enums allow certain debuggers to print the values of an enumeration constant.

Page 37
Model Questions

1. What is structure? Write syntax and futures of structures and explain each component in
structure with suitable examples?
2. Define Nested structure? Write syntax and explain each component in nested structure with
suitable examples?
3. Write differences between array of structures and arrays in structure? Write syntax and
explain each component in array of structure with suitable examples?
4. Define union? Write syntax and explain each component in union with suitable example?
5. Differentiate between structures and unions and write programs for to print size of
structures and unions?
6. Briefly discuss typedef keyword and synatax with suitable example?
7. What is enum? Explain types of declaration and advantages of enumerated data types?

Page 38

You might also like