0% found this document useful (0 votes)
66 views11 pages

Structure and Union in C

It is a c language structure and it is used for the net users
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views11 pages

Structure and Union in C

It is a c language structure and it is used for the net users
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

Page- 1

Structures and Unions, Enumerated data type


Structures are introduced to combine different data types into single block. We can access entire
block of data with the structure. It can store different data elements information as a single unit.

Q). STRUCTURES:

1. Definition of Structure:
“Structure is a collection of a heterogeneous data types ”, Structure is a user defined data type
and it is a combination of different data types called as members. All these members are referred by a
single name known as structure name. Structure can be placed before or within the main.
Uses of Structures:
1. To maintain database management.
2. Check the memory size of the computer.
3. Sending the output to print.

2. Declaration of Structure:
A structure is declared using the keyword “struct ” followed by a structure name. all the
variables of the structure are declared within the structure.
Syntax to Create Structure:
struct tag_name
{
data type member 1;
..
data type member n;
};
The structure is terminated by a semicolon(;), tag_name such as a name of the structure like
employee.
Example:
struct employee
{
char name[20];
int empno;
int salary;
};
The structure employee holds the three fields. name, empno, salary. These fields are called as
structure elements (or) members. Each member may belongs to a different type of data.

3. Declaration of Structure variables:


We can access the members of structures using structure variable. This structure variable
should be created after completion of structure definition. We can create structure variable
in two ways.
a). Structure variable can be created as follows:

Syntax: struct tagname(structurename) structure_variable_name;

Ex: struct student s;


Here struct is a keyword, tagname is a name of the structure, s is a name of the variables.
Page- 2

b). We can also create the structure variable along with the structure definition as follows:
Syntax:
struct tagname
{
data type member 1;
..
data type member n;
}structure variable name;

Example:
struct employee
{
int eno;
char ename[20];
float salary;
}emp1, emp2;

Here emp1, emp2 are structure variables of type employee.

4. Initialization of a structure:
A structure can be initialized in the same way as other datatypes are initialized.
Initialization means to assigning some constant to the members of the structure.
Syntax:
struct struct_name
{
Datatype member1;
Datatype member2;

} struct_var={constant1, constant2, constant3, .};


(or)
struct struct_name struct_var={constant1, constant2, constant3, ..};

Example:
struct student
{
int rno;
char name[20];
char course[20];
float fee;
} stud={10, “Virat” “BSC”,23000 };
(or)
struct student stud={10, “Virat” “BSC”,23000 };

5. Accessing members of a Structure:

We can access members of structure by using dot (.) operator along with the structure variable
name.

Syntax: structure_variable_name.member;
Page- 3

Ex: e.eno;
e.name;
e.sal;

The following program illustrates the structure with employee data:

Aim: To write a C-Program to read and print an employee data using structure.
Program:
#include<stdio.h>
#include<conio.h>
struct Employee
{
int eno;
char ename[20];
float esal;
};
void main()
{
struct Employee e;

printf("\nEnter Employee Number:");


scanf("%d",&e.eno);

printf("\nEnter Employee Name:");


scanf("%s",&e.ename);

printf("\nEnter Employee Salaray:");


scanf("%d",&e.esal);

printf("\n\nThe Employee Details are....");


printf("Employee Number:%d",e.eno);
printf("\nEmployee Name:%s",e.ename);
printf("\nEmployee Salary:%d",e.esal);
getch();
}
Out put:
Page- 4

Q). Array of Structures:

Array is a collection of similar data types. In the same way we can also define array of structures.
In this structure array, every element is of structure type. The array of structure is declared as follows

Syntax: struct tagname


{
Data_type member1;
Data_type member2;
--------------------------
---------------------------
}array_variable_name[3];

Ex: struct emp


{
int eno;
char name[20];
float sal;
}e[10];

In the above example e[10] is an array of 10 elements containing 10 objects of type structure.
Each element of e[10] has structure type with three members that are eno, ename and esal.
The following program illustrates the above concept.

Aim: To Write a C-Program that creates a structure of 10 students having student number
(sno), student name (sname), marks in three subjects (m1,m2,m3), total marks of the
students (tot) and average (avg) and display the names of failed students.
Program:
#include<stdio.h>
#include<conio.h>
struct Student
{
int sno;
char sname[20];
float sfee;
char DOB[80];
};
void main()
{
struct Student s[10];
int n,i;
printf("\nEnter the Number of Students:");
scanf("%d",&n);

for(i=0; i<n; i++)


{
printf("Enter Student Number:");
scanf("%d", &s[i].sno);
Page- 5

printf("eneter Student Name:");


scanf("%s",&s[i].sname);

printf("enter Student fee:");


scanf("%s",&s[i].sfee);

printf("enter Student fee:");


scanf("%s",&s[i].DOB);

}
for(i=0;i<n;i++)
{
printf("******STUDENT DETAILS ARE******:");
printf(“%d”, s[i].sno);
printf(“%s”, s[i].sname);
printf(“%f”, s[i].sfee);
printf(“%d”, s[i].DOB);

}
getch();
}
Output:

Q). Pointer to Structures:

Pointer is a variable can store the address of another variable .The variable may be of any data
type. In the same way we can also define pointer to structure. Here, starting address of the member
variables can be accessed. Thus, such pointers are called structure pointers.

Ex: Struct book


{
char name[25];
char author[25];
int pages;
};struct book *ptr;

In the above example *ptr is pointer to structure book. The syntax for using pointer with
member is as given below

1) ptr-> name 2) ptr -> author 3) ptr -> pages

Q). Structure and Functions:


Like variables of standard data type structure variables also can be passed to the function by
value or address. A function may access the member of a structure in three ways as shown in below
1. Passing individual elements.
2. Passing entire elements.
3. Passing the address of the structure.
Page- 6

1. Passing individual elements.

To pass a any individual elements of the structure to a function, we must use the direct selection
operator to refer to the individual member for the actual parameters.

Whenever a structure element is to be passed to any other function, it is essential to declare the
structure outside the main() function i.e., global.
The following program illustrates the above concept.

Aim: To write a C program to find the sum of two complex numbers.


Program:
#include<stdio.h>
#include<conio.h>
struct point
{
int x;
int y;
}point p1={2,3};

void display(int, int);


void main()
{
struct point;
display(p1.x, p1.y)
getch();
}
void display(int a, int b)
{
Printf(“the result is%d%d”, a,b);
}
Output:

2. Passing entire elements.


To pass a entire elements to a structure. The entire structure will copy to the called function.
Syntax: function_name (structure_variable_name);
Example:
#include<stdio.h>
#include<conio.h>
struct point
{
int x;
int y;
}point p1={2,3};

void display(point);
void main()
{
struct point;
display(p1)
getch();
}
void display(struct point p1)
Page- 7

{
Printf(“the result is%d%d”, p.x, p.y);
}
Output:

3. Passing entire elements.


To pass a address of the structure we have to use the references of the structure lake a pointer
variables of the structure.

Q). Nested Structures


“A structure which contains the another structure as it member is called a NESTED STRUCTURE ”
(or) structure within the structure.
The general syntax of the nested structure is as follows

Syntax:
struct tag_name1
{data_type member1;
Data_type member2;

};

struct tag_name2
{ data_type member1;

Struct tag_name1 struct_variable;


};

Example:
A programe to read and display iformation of a student, using a structure within a structure.
#include<stdio.h>
#include<conio.h>
struct name
{
char fname[20];
char mname[20];
char lname[20];
};

struct student
{
char name[20];
int rno;
float fee;
struct name n;
} struct student s1={ Raj”, “Sandeep”, “Sharma”, 5, 50000};
void main()
{
struct student s1;
Page- 8

printf(“******student details are*********”);


printf(“%s”, s1.n.name);
printf(“%s”, s1.rno);
printf(“%s”, s1.fee);
getch();
}

Q). Unions:
A union is a user defined data type available in C that enables us to store different data types in
the same memory location.

We can define a union with many members, but only one member can contain a value at any
given time. Unions provide an efficient way of using the same memory location for multi-purpose.

1. Defining and Declaring a Union


To define a union, we must use the union statement. The format of the union statement is as
follows:
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Example:
union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in above example Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by character string.
Following is the example which will display total memory size occupied by the above union:

Example:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
}union Data d1;
int main( )
{
printf( "Memory size occupied by data : %d\n", sizeof(d1));
return 0;
Page- 9

}
When the above code is compiled and executed, it produces the following result:
Memory size occupied by data : 20

2. Accessing Union Members


To access any member of a union, we use the member access operator (.).the union variable
name followed by the dot operator followed by the member name.
Following is the example to explain usage of union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
}union Data d1;

int main( )
{
d1.i = 10;
d2.f = 220.5;
printf( " %d", d1.i);
printf( " %f", d1.f);
return 0;
}

OUTPUT:

Here, we can see that values of i and f members of union got corrupted because final value
assigned to the variable has occupied the memory location

Q). Array of Union:


Similarly to structure we can also have an array of union variables. However, because of the
problem of new data overwriting existing data in the other fields, the program may not display the
accurate results.
#include<stdio.h>
#include<conio.h>
union point
{
Intx,y;
} unio point p[20];

void main
{
int i;
p[0].x=2;
p[0].y=3;
p[1].x=4;
p[1].y=5;
for(i=0; i<2; i++)
{
printf(“%d%d”, p[i].x, p[i].y);
Page- 10

}
getch();
}

Q). Enumerated Data types in C:


1. Defination:
Enumeration type allows programmer to define their own data type . Keyword enum is used to
defined enumerated data type.
Syntax:
enum type_name
{
value1;
value;
........;
valueN
};

Here, type_name is the name of enumerated data type or tag and value1, value2,....,valueN are
values of type type_name.
By default, value1 will be equal to 0, value2 will be 1 and so on but, the programmer can change
the default value as below:

enum suit
{
club=0;
diamonds=10;
hearts=20;
spades=3;
};

2. Declaration of enumerated variable


The above code defines the type of the data but, no variable is created for the enum data type.
The following will shows the creation of a variable of type enum.

enum Boolean
{
false;
true;
};
enum boolean check;
Here, a variable check is declared which is of type enum boolean.

Example of enumerated type


#include <stdio.h>
enum week
{
sunday, monday, tuesday, wednesday, thursday, friday, Saturday
};
int main()
Page- 11

{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}

Output
4 day

We can write any program in C language without the help of enumerations but, enumerations
helps in writing clear codes and simplify programming.

Important Questions:
1. Define structure and explain the process of accessing structure variables with an example.
2. Explain array of structures with an example.
3. Explain the pointers to structures with an example.
4. Explain how to pass structures to functions with an example.
5. Explain about the Unions in C with an example.
6. Explain about the Enumerated data types in C.

You might also like