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

Structure and Union

The document discusses structures in C programming. It defines what a structure is, how to declare and define a structure, how to initialize and access structure members, arrays of structures, nested structures, pointers to structures, passing structures to functions, and differences between structures and unions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Structure and Union

The document discusses structures in C programming. It defines what a structure is, how to declare and define a structure, how to initialize and access structure members, arrays of structures, nested structures, pointers to structures, passing structures to functions, and differences between structures and unions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Notes For Bachelor of Science (TU)

BSC NOTES
PDF
COLLECTION
www.avashkattel.com.np/bscnotes
Unit 8 Structure and Union (5
Hrs)
Contents of the unit
• Introduction, array of structure, Passing structure to functions,
passing array of structure to function, structure within structure
(nested Structure), union, pointer to structure
C Structure

• Why use structure?


• In C, there are cases where we need to store multiple attributes of an
entity. It is not necessary that an entity has all the information of one
type only. It can have different attributes of different data types. For
example, an entity Student may have its name (string), roll number
(int), marks (float).
What is Structure

• Structure in c is a user-defined data type that enables us to store the


collection of different data types. Each element of a structure is
called a member.
• The ,struct keyword is used to define the structure. Let's see the
syntax to define the structure in c.
Syntax
• struct structure_name
•{
• data_type member1;
• data_type member2;
• .
• .
• data_type memeberN;
• };
Example
• struct employee
• { int id;
• char name[20];
• float salary;
• };
Declaring structure variable

• We can declare a variable for the structure so that we can access the
member of the structure easily. There are two ways to declare
structure variable:
• By struct keyword within main() function
• By declaring a variable at the time of defining the structure.
Comparison of Array and Structure
• Array is a collection of data items of same type and structure is simply
defined as the collection of data items of different types
• We can list differences as
Array Structure
An array is a collection of related data A structure can have elements of
elements of same type different types
An array is derived data type Structure is a user-defined data type
An array behaves line built in type Structure does not behave like a built in
types
Array name is a pointer to the first Structure name is not pointer
element of it
Structure Initialization
• We can initialize the members of structure like ordinary variables.
• The members to be initialized must appear in order as in the
definition of structure within braces and separated by commas.
• For example:
• struct student {
• int rn;
• char name[20];
•}
• struct student s = {1,”Kamal”};
Accessing the members of Structure
• The members of a structure are usually processed individually as
separate entity.
• Therefore, we must be able to access the individual structure
members.
• A structure members can be accessed by using period or dot(“.”).
• The syntax is:
• structure_variable.member
Example
Array of Structure
• Like ordinary variables we can create an array of structure.
• In this case, the array will have individual structure as its elements.
• Synax:
• struct structure_name array_name[size];
Example
Initializing Array of Structure
• We can initialize an array of structure in the same way as a single structure.
• Let us consider the following example:
• struct book
• {
• char name[20];
• int price;
• int pages;
• };
• Struct book b[2] = {
• “C programming”, 200, 300,
• “ Java programming”, 300,400
• }

Nested Structure(Structure within Another
Structure)
• One structure may be nested within another structure’s definition.
• The outer structure is known as nesting structure and the inner is called
nested structure.
• For example
• struct date Struct student
•{ {
char name[20];
• int day; struct date dob;
• int month; int rn;
};
• int year;
•}
Pointer to Structure
• A pointer can also be used with a structure.
• To store address of a structure variable, we can define a structure type pointer variable in normal way.
• Example:
• Struct student
• {
• char name[20];
• struct date dob;
• int rn;
• };
• Then we can define structure variable and pointer variable of the structure type
• Struct student s;
• Struct student *p;
• p= &s;
Function and Structure
• Like an ordinary variable, a structure variable can also be passed to a
function.
• We may either pass individual structure elements or the entire
structure to a function as its argument.
• #include<stdio.h>
• struct Employee
• {
• int eid;
• char name[20];
• int salary;
• };
• void print(struct Employee );
• int main()
• {
• struct Employee e;
• printf("Enter eid, name and salary of employee\n");
• scanf("%d%s%d",&e.eid,e.name,&e.salary);
• printf("Employee Information\n");
• print(e);
• return 0;
• }
• void print(struct Employee emp)
•{
• printf("Empoyee Name:%s\n",emp.name);
• printf("Employee Salary %d\n",emp.salary);
• printf("Employee EID: %d\n",emp.eid);
•}
Union
• A union is similar to a structure with respect to syntax and use.
• The union also contains members whose individual data types may
different from one another.
• The distinction is that all members within a union share the same
storage area of computer memory, whereas each member within a
structure is assigned its own unique storage.
• Since same memory is shared by all its members, only one variable
can reside into a memory at a time.
• Thus, the union is used to conserve memory space.
Union
• Union is not useful for applications involving members where the
values need to be assigned to all of the members at the same time.
• Therefore, although a union may contain many members of different
types, it can handle only one member at a time.
• The compiler allocates a piece of storage that is large enough to hold
the largest variable type in the union
Defining Union
• union union_name
•{
• data_type 1 member1
• data_type 2 member 2
• ….
• data type n member n
• };
Example
• union ContacInfo
•{
• char phno [10];
• char perma_add [20];
• char temp_add [20];
• char emailId [20];
• };
• Example: Write a C program to demonstrate union
• #include<stdio.h>
• union Number
• {
• int a;
• float b;
• double c;
• };
• int main()
• {
• union Number n;
• printf("Enter integer number\n");
• scanf("%d",&n.a);
• printf("Ingere number is %d\n",n.a);
• printf("Enter float number\n");
• scanf("%f",&n.b);
• printf("float number is %f\n",n.b);
• printf("Enter double number\n");
• scanf("%f",&n.c);
• printf("double number is %f\n",n.c);
• }
Difference between Structure and Union
Structure Union
1 Each member of a structure is All members of a union share the same storage
assigned its own unique storage. area of computer memory.

2 It takes more memory It takes less memory

3 The amount of memory required The amount of memory required to store a union is
to store a structure is the sum of the same as memory size occupied by a member which
memory sizes required by its requires largest memory space among the
members members
4 All the members of structure can Only one member of union can be accessed at any
be accessed at any point of time given time

5 Structure is declared as Union is declared as:


struct student { union student {
int rn; int rn;
char name[20] char name[20]
} }
TU Question
• //Create a structure named course with name , code and credit_hour as its members.
• //Write a program using this structure to read data of 5 courses and display data of those courses
• //with credits hours greater than 3
• #include<stdio.h>
• #define N 5
• struct course
• {
• char name[20];
• char code[10];
• int credit_hours;
• };
• void read(struct course s[]);
• void display(struct course s[]);
• int main()
• {
• struct course cs[N];
• read(cs);
• display(cs);
• }
• void read(struct course cs[])
• {
• printf("Enter name, code and credit hours of %d subjects\n",N);
• for(int i=0;i<N;i++)
• {
• scanf("%s%s%d",cs[i].name,cs[i].code, &cs[i].credit_hours);
• }
• }
• void display(struct course cs[])
• {
• printf("Course Details\n");
• printf("Code\tName\tCredt_hours\n");
• for(int i=0;i<N;i++)
• {
• if(cs[i].credit_hours>3)
• printf("%s\t%s\t%d\n",cs[i].name,cs[i].code, cs[i].credit_hours);
• }
• }
TU Questions
• What is structure? Write structure Rectangle with members length and breadth
• Structure : Structure is a use define data type that is used to store different data types under one common
name.
• The data types are logically related.
• struct structute_name
• {
• data_type member1;
• data_type member2;
• …………………………………..
• data_type member
• };
• struct Rectangle
• {
• int length;
• int breadth;
• };
Example
• Create structure named distance which has memebrs meters and centimeter.
• Write a program to read a distance from user and multiply the entered distance
by 5.
• Finally display the result distance.

• struct distance
• {
• int meters;
• int centimeters;
• };

• d1 = 100m, 50 cm

• #include <stdio.h>
• struct distance
• {
• int meter;
• int centimeter;

• };
• int main()
• {
• struct distance d1,d2;
• printf("Enter distance in meter\n");
• scanf("%d",&d1.meter);
• printf("Enter distance in centimer meter\n");
• scanf("%d",&d1.centimeter);
• printf("Distance d1 is %dm %dcm\n",d1.meter,d1.centimeter);
• d2.meter = d1.meter*5;
• d2.centimeter = d1.centimeter*5;
• d2.meter = d2.meter+d2.centimeter/100;
• d2.centimeter = d2.centimeter%100;
• printf("Distance d2 is %dm %dcm\n",d2.meter,d2.centimeter);
• }

You might also like