0% found this document useful (0 votes)
31 views51 pages

Structurepdf 2

The document provides an overview of structures and unions in programming, detailing how to group related data of different types into a single unit called a structure. It covers various topics including declaring structures, accessing structure elements, passing structures to functions, and using arrays of structures. Additionally, it explains nested structures and pointers to structures, along with example code snippets for practical understanding.

Uploaded by

rimipo8410
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)
31 views51 pages

Structurepdf 2

The document provides an overview of structures and unions in programming, detailing how to group related data of different types into a single unit called a structure. It covers various topics including declaring structures, accessing structure elements, passing structures to functions, and using arrays of structures. Additionally, it explains nested structures and pointers to structures, along with example code snippets for practical understanding.

Uploaded by

rimipo8410
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/ 51

Prepared by:

Sushant Paudel
STRUCTURE AND UNION
Introduction
Array of Structure
Passing Structure to Function
Passing Array of Structure to Function
Structure within Structure (Nested Structure)
Union
Pointer to Structure
INTRODUCTION TO STRUCTURE
• Problem:
–—
How to group together a collection of data items of
different types that are logically related to a
particular entity??? (Array)
E.g. name, roll_no, marks, gender and phone_no
–—
are related information of a student.
–—
However name is of char array type, roll_no is of int
type, marks is of float type, gender is of char type
and phone_no is of char array type or long int
type.
• Solution: Structure
STRUCTURE
• A structure is a collection of variables of
different data types under a single name.
• —
The variables are called members of the
structure.
• —
The structure is also called a user-defined
data type.
Structure
Structure is a collection of dissimilar data types
that means in a structure we can hold data items
of different types by a single name. it is very
useful in real life application. For example- to
manage student’s record, employee record, book
records etc.
Declaring a Structure:
Syntax:
struct structure_name
{
structure emement1;
structure element2;
……….
……….
structure element;
};

eg:
To declare a structure that holds 3 data items as book name, price and pages.
struct book
{
char name[20];
float price;
int pages;
};
When we declare a structure it doesn’t reserve any space in memory. To use the
structure it variable must be declared. Structure variables are declared as:
struct structure_name variable1,variable2,….. variable;
for eg:
struct book
{
char name[20];
int pages;
float price;
} struct book b1,b2,b3;
After declaring structure variables it reserves space in memory. All the space for a
single structure variables are in adjacent position.

Structure variables can also be declared as:


struct book
{
char name[20];
int pages;
float price;
}b1,b2,b3;
The structure initialization can be done as:
struct book
{
char name[20];
int pages;
float price;
};
struct book b1={“Let us C”, 211, 450.15};
struct book b2={“Math”, 100,190.5};
Accessing Structure Elements:
In structure to access individual structure element we use a (.) dot operator as:
Syntax:
structure_variable . structure_element
eg:
void main()
{
struct book
{
char name[20];
int pages;
float price;
};
struct book b1={“Let us C”, 211, 450.15};
struct book b2={“Math”, 100,190.5};
printf(“%s\t%d\t%f”, b1.name, b1.pages, b1.price);
printf(“%s\t%d\t%f”, b2.name, b2.pages, b2.price);
}
#include<stdio.h>
#include<conio.h>
struct student
{
int roll;
char name[20];
} stu1={20,"shyam"};
int main()
{
printf("roll of student is %d\n",stu1.roll);
printf("name of student is %s\n",stu1.name);
getch();
return 0;
}
#include<stdio.h>
#include<conio.h>
struct student
{
int roll;
char name[20];
} stu1={20,"shyam"};
int main()
{
struct student stu2;
clrscr();
printf("roll of student is %d\n",stu1.roll);
printf("name of student is %s\n",stu1.name);
printf("enter the roll_no of second student\n");
scanf("%d",&stu2.roll);
printf("enter the name of 2nd student\n");
scanf("%s",stu2.name);
printf("name of second student %s:",stu2.name);
printf("roll_no_2nd: %d",stu2.roll);
getch();
return 0;
}
• WAP to declare a structure employee that
holds name, age and salary. Now accept
information about two employees through
the keyboard and display that information.
void main()
{
struct employee
{
char name[20];
int age;
float salary;
}e1,e2;
printf(“enter the record of two employee”);
scanf(“%s%d%f”, e1.name, &e1.age,&e1.salary);
scanf(“%s%d%f”, e2.name, &e2.age,&e2.salary);
printf(“Employee Datails”);
printf(“%s%d%f”, e1.name,e1.age,e1.salary);
printf(“%s%d%f”, e2.name,e2.age,e2.salary);

getch();
}
Array of structure
We can create array of structure variables just like
array of other common data types. By using array
of structure we can handle thousands of records
by a single statement with the help of loop.
Syntax:
struct structure_name structure_variable[size];
struct book b[50];
WAP to declare a structure which consists of book name , price and pages.
Accept information of 50 books and display that information.
void main()
{
struct book
{
char name[20];
int pages;
float price;
}b[50];
int i;
printf(“enter the record of fifty books”);
for(i=0;i<49;i++)
{
scanf(“%s%d%f”, b[i].name, &b[i].pages,&b[i].price);
}
printf(“Book datails”);
for(i=0;i<49;i++)
{
prinntf(“%s%d%f”,
b[i].name,b[i].pages,b[i].price);
printf(“\n”);
}
getch();
}
FUNCTION AND STRUCTURE
• We will consider four cases here:
–—
Passing the individual members to functions
Passing whole structure to functions
–—
–—
Passing array of structure to functions
– Passing structure pointer to functions
• PASSING STRUCTURE MEMBER TO FUNCTIONS
• —
Structure members can be passed to functions
as actual arguments in function call like ordinary
variables.
• Problem: Huge number of structure members
• —
Example: Let us consider a structure employee
having members name, id and salary and pass
these members to a function:
#include<stdio.h>
#include<conio.h>
struct student{
int age;
char name[20];
};
void display(int ,char[]);
int main(){
struct student stu;
clrscr();
printf("enter the age of student\n");
scanf("%d",&stu.age);
printf("enter the name of student\n");
scanf("%s",stu.name);
display(stu.age,stu.name);
getch();return 0;
}
void display(int x, char c[])
{
printf("the age of student\n");
printf("%d",x);
printf("the name of student\n");
printf("%s",c);
}
PASSING WHOLE STRUCTURE TO FUNCTIONS
-W—hole structure can be passed to a function by the
syntax:
function_name(structure_variable_name);
- The called function has the form:
return_type function_name(struct tag_name
structure_variable_name)
{
… … … … …;
}
Note: In this call, only a copy of the structure is passed
to the function, so that any changes done to the
structure members are not reflected in the original
structure.
#include<stdio.h>
#include<conio.h>
struct student{
int age;
char name[20];
};
void display(struct student );
int main(){
struct student stu;
clrscr();
printf("enter the age of student\n");
scanf("%d",&stu.age);
printf("enter the name of student\n");
scanf("%s",stu.name);
display(stu);
getch();
return 0;}
void display(struct student stu1)
{
printf("the age of student\n");
printf("%d",stu1.age);
printf("the name of student\n");
printf("%s",stu1.name);
}
PASSING ARRAY OF STRUCTURES TO FUNCTIONS
• —
Passing an array of structure type to a function is
similar to passing an array of any type to a function.
• —
That is, the name of the array of structure is passed
by the calling function which is the base address of
the array of structure.
• —
Thus, any changes made to the array of structure
by the called function are directly reflected in the
original structure.
• Note: The function prototype comes after the
structure definition.
#include<stdio.h>
#include<conio.h>
int i;
struct student{
int age;
char name[20];
};
void display(struct student stu1[5]);
int main()
{
struct student stu[5];
clrscr();
printf("enter the age of student\n");
for(i=0;i<3;i++)
scanf("%d",&stu[i].age);
printf("enter the name of student\n");
for(i=0;i<3;i++)
scanf("%s",stu[i].name);
display(stu);
getch();
return 0;
}
void display(struct student stu1[5])
{
for(i=0;i<3;i++)
{
printf("%d\t",stu1[i].age);
printf("%s\n",stu1[i].name);
}
}
-Create a structure named student that has name, roll, marks,
and remarks as members. Assume appropriate types and size
of member. Write a program using structure to read and
display the data entered by the user.
-Create a structure named student that has name, roll, marks
and remarks as its members. Assume appropriate types and
size of member. Use this structure to read and display records
of 10 students.
-Define a structure of employee having data members name,
address, age and salary. Take the data for n employees in an
array and find the average salary.
#include<stdio.h>
#define SIZE 100
struct employee
{
char name[20];
char address[40];
int age;
float salary;
};
void main()
{
struct employee e[SIZE];
int n;
int i;
float sum_sal=0,avg_sal;
printf("How many emplyees are there?:\t");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter information about employee%d",i+1);
printf("\nName:\t");
scanf(" %s", e[i].name);
printf("\nAddress:\t");
scanf(" %s",e[i].address);
printf("\nAge:\t");
scanf("%d",&e[i].age);
printf("\nSalary:\t");
scanf("%f",&e[i].salary);
}
printf("\n\n");
printf("\n Employee name\t Address \t Age\t Salary");
for(i=0;i<n;i++)
printf("\n%s\t\t %s\t\t %d\t%f\n",e[i].name,e[ i].address,e[i].age,e[i].s alary);
for(i=0;i<n;i++)
Sum_sal=sum_sal+e[i].sala ry;
avg_sal=sum_sal/n;
printf("\nAverage Salaray=%f",avg_sal);
getch(); }
POINTER TO STRUCTURE…
• —Also, the address of a structure type variable can be
stored in a structure type pointer variable as follows:
struct book
{
char name[20];
int pages;
float price;
};
struct book b, *bptr;
bptr=&b;
• Here, the base address of b is assigned to bptr
pointer.
Now the members of the structure book can be
accessed in 3 ways as:

bptr->name (*Bptr).name
b.name (*bptr).pages
bptr->pages
b.pages bptr->price (*bptr).price
b.price
#include <stdio.h>//ponter to structure
struct person
{
int age;
float weight;
};

int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of person1

printf("Enter integer: ");


scanf("%d",&(*personPtr).age);

printf("Enter number: ");


scanf("%f",&(*personPtr).weight);

printf("Displaying: \n");
printf("%d\n%f",(*personPtr).age,(*personPtr).weight);

return 0;
}
#include <stdio.h>
#include <conio.h>
struct employee {
char name[100];
int age;
float salary;
char department[50];
};
int main(){
struct employee employee_one, *ptr;
printf("Enter Name, Age, Salary and Department of Employee\n");
scanf("%s %d %f %s", &employee_one.name, &employee_one.age,
&employee_one.salary, &employee_one.department);
/* Printing structure members using arrow operator */
ptr = &employee_one;
printf("\nEmployee Details\n");
printf(" Name : %s\n Age : %d\n Salary = %f\n Dept : %s\n",
ptr->name, ptr->age, ptr->salary, ptr->department);
getch();
return 0;}
#include<stdio.h>//pointer to structure
#include<conio.h>
struct student{
int roll;
int name[50];
};
int main(){
struct student stu;
struct student *ptr;
ptr=&stu;
printf("enter the roll no of student");
scanf("%d",&ptr->roll);
printf("enter the name of student");
scanf("%s",ptr->name);
printf("\n the roll no of student is:%d\n",ptr->roll);
printf("the name of student is:%s\n",ptr->name);
printf("\n the roll no of student is: %d\n",(*ptr).roll);
printf("\n the name of student is: %s\n",(*ptr).name);
PASSING STRUCTURE POINTER TO FUNCTIONS
• —
In this case, address of structure variable is
passed as an actual argument to a function.
• The corresponding formal argument must be a
structure type pointer variable.
• —
Note: Any changes made to the members in the
called function are directly reflected in the calling
function.
#include<stdio.h>
#include<conio.h>
struct rectangle{
int length;
int width;
};
int area(struct rectangle *rect1);
int main(){
struct rectangle rect;
int A;
rect.length=10;
rect.width=5;
A=area(&rect);
printf("area:%d",A);
getch();}
int area (struct rectangle *rect1)
{
return rect1->length*rect1->width;
STRUCTURE WITHIN ANOTHER STRUCTURE (NESTED
STRUCTURE)
• Let us consider a structure personal_record to store
the information of a person as:
struct personal_record
{
char name[20];
int day_of_birth;
int month_of_birth;
int year_of_birth;
float salary;
}person;
In the structure above, we can group all the items
related to birthday together and declare them under a
substructure as:
struct personal_record
{
char name[20];
float salary;
struct
{
int day_of_birth;
int month_of_birth;
int year_of_birth;
}birthday;
}person;
#include<stdio.h> scanf("%d",&stu.d.month);
#include<conio.h> printf("enter the day of birth day");
struct student { scanf("%d",&stu.d.day);
char name[20]; printf("name:%s\n",stu.name);
struct dob{ printf("birth date:");
int yr,month,day; printf("%d-%d-%d“
}d; ,stu.d.yr,stu.d.month,stu.d.day);
}; getch();
int main() return 0;
{ }
struct student stu;
printf("enter the name of
student\n");
scanf("%s",stu.name);
printf("enter the year of birth
day");
scanf("%d",&stu.d.yr);
printf("enter the monhth of
birth day");
#include<stdio.h>
struct dob{
int yr,month,day;
};
struct student {
char name[20];
struct dob d; };
int main(){
struct student stu;
printf("enter the name of student\n");
scanf("%s",stu.name);
printf("enter the year of birth day");
scanf("%d",&stu.d.yr);
printf("enter the monhth of birth day");
scanf("%d",&stu.d.month);
printf("enter the day of birth day");
scanf("%d",&stu.d.day);
printf("name:%s\n",stu.name);
printf("birth date:");
printf("%d-%d-%d",stu.d.yr,stu.d.month,stu.d.day);
getch(); }
TU MODEL QUESTION
• Define a structure Table having data members
length, breadth and height. Represent different
measurements by another structure
Measurement having data members meter and
centimeter. Take data for some table and find
their volume.
struct Table printf("\nEnter breadth of
{ Table:\t");
int length; scanf("%d",&tab.breadth);
int breadth; printf("\nEnter height of Table:\t");
int height; scanf("%d",&tab.height);
}; volume.centimeter=(tab.leng th)*
struct Measurement (tab.breadth) * (tab.height);
{ printf("\nThe volume in
centimeters is:%f
float meter; cm^3",volume.centimeter);
float centimeter; volume.meter=(tab.length/10 0.0) *
}; (tab.breadth/100.0) *
void main() (tab.height/100.0);
{ printf("\nThe volume in meters
struct Table tab; is:%f m^3",volume.meter);
struct Measurement volume; getch();
printf("\nEnter length breadth and }
height in centimeter\n");
printf("\nEnter length of Table:\t");
scanf("%d",&tab.length);
/*READING printf("\n Enter name:\t");
RECORD DYNAMICALLY
(pointer to structure )*/ scanf("%s", bptr->name);
struct book printf("\n Enter no. of
{ pages:\t");
char name[20]; scanf("%d", &bptr->pages);
int pages; printf("\n Enter price:\t");
float price; scanf("%f", & bptr->price);
}; printf("\n Name\t\t No. of
Pages\t Price\n");
void main()
printf("%s\t\t%d\t\t%f",(*b
{ ptr).name,(*bptr).pages,(
struct book *bptr; *bptr).price);
float temp; getch();
bptr=(struct book }
*)malloc(sizeof(struct
book));
/*READING N DIFFERENT {
RECORDS DYNAMICALLY printf("\n Enter name:\t");
(pointer to structure )*/ scanf(" %s", (bptr+i)->name);
struct book printf("\n Enter no. of pages:\t");
{ scanf("%d", &(bptr+i)->pages);
char name[20]; printf("\n Enter price:\t");
int pages; scanf("%f", &temp);
float price; (bptr+i)->price=temp;
}; }
void main() printf("\n Name\t\t No. of Pages\t
{ Price\n");
struct book *bptr; for(i=0;i<n;i++)
int n,i; {
float temp; printf("%s\t\t%d\t\t%f\n",
printf("\nEnter how many (bptr+i)->name, (bptr+i)->pages,
records:\t"); (bptr+i)->price);
scanf("%d",&n); }
bptr=(struct book getch();
*)malloc(n*sizeof(struct book)); }
for(i=0;i<n;i++)
UNION…
A union is declared using the keyword union as:
union student
{
char name[20];
int roll_no;
float marks;
char section;
};
union student s;
While accessing union members, we should make sure
that we are accessing the member whose value is
currently residing in the memory. Otherwise we will get
erroneous output (which is machine dependent).
#include<stdio.h>
#include<conio.h>
int main(){
union sample
{
int a;
int b;
};
union sample s;
printf("size:%d\n",sizeof(s));
s.a=12;
printf("\n%d\n", s.a);
s.b=13;
printf("%d", s.a);
getch();}
Difference between Structure and Union:

Structure Union
1. It creates the multiple memory 1. It creates only one memory space.
space.
1. It stores each and every variable 2 .it stores all the variables inside a
with their own requirements. single memory location.
1. Size of structure depends on 1. Size of union doesn’t depends on
number of variables. number of variables.
1. Syntax: 4 .Syntax:
struct structure_name union union_name
{ {
structure element1; union element1;
structure element2; union element2;
………. …………….
structure element; ……………..
}; };
struct node
{ Info/data address
int data;
struct node *nextPtr;
}node1,node2;
node1.data=100;
node1.nextprt=&node2;
node2.data=200;
node2.nextptr=NULL;
100 200 NULL
A self-referential structure contains a pointer member that
points to a structure of the same structure type.
• —For example, the definition
struct node
{
info address
int data;
struct node *nextPtr;
};
defines a type, struct node.
• —A structure of type struct node, has two members: an int
member data and another pointer member nextPtr.
• —The member nextPtr points to (i.e. holds address of) another
structure of type struct node i.e. a structure of the same type
as the one declared here and hence is the term “self-
referential structure”.
#define NULL 0
struct node
{
int data;
struct node *nextPtr;
};
void main()
{
struct node node1,node2;
node1.data=100;
node1.nextPtr=&node2;
node2.data=200;
node2.nextPtr=NULL;
printf("\n") ;
printf("|%d|%u|----->
|%d|%u|",node1.data,node1.nextPtr,node2.data,node2.nextPtr);
printf("\n Address of node2=%u",&node2);
getch();
}
Assignment
• TU EXAM QUESTION
• —
Define a structure of employee having data
members name, address, age and salary. Take
data for n employee in an array dynamically and
find the average salary.
• Define a structure of student having data
members name, address, marks in C language,
and marks in information system. Take data for n
students in an array dynamically and find the
total marks obtained.

You might also like