You are on page 1of 10

Prepared by MD.

IMRAN KHAN

UNIT-IV
USER-DEFINED DATA TYPES

STRUCTURE

INTRODUCTION

We know that arrays can be used to present a group of data items that belong to
the same 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. C supports a
constructed data type known as structures, a mechanism for packing data of different
types.

DEFINITION

C supports a constructed data type known as structures, a mechanism for packing


data of different types. For example, it can be used to represent a set of attributes, such
as student_name, roll_number and marks. More examples of such structures are:

date : day, month, year


book : author, title, price, year
address : name, house-number, street, city

Structures must be defined first for their format that may be used later to declare
structure variables.

The general format of a structure definition is as follows

struct tag_name
{
data_type member1;
data_type member2;
----------- -----------
----------- -----------
};

Here struct is a keyword.

Let us take a example, book database consisting of book name, author, number of
pages, and price. We can define a structure to hold this information as follows:

struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};

KHAN PUBLICATIONS
Page 1
Prepared by MD. IMRAN KHAN

DECLARING STURCTURE VARIABLES

After defining a structure format we can declare variables of that type. A structure
variable declaration is similar to the declaration of variables of any other data types. It
includes the following elements:
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.

The general format of a structure definition is as follows

struct tag_name
{
data_type member1;
data_type member2;
----------- -----------
----------- -----------
};

For Example:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank book1, book2, book3;

Initializing members of structure


Once structure is declared and a variable of that structure type is created, the members in
that structure can be initialized with the help of that structure variable. This can be done in
two ways:
1. By using assignment operator.
2. By using scanf() statement

(1). By using assignment operator


A structure can be initialized in its declaration itself with list of initializers enclosed
within the curly braces. Each initializer must be a constant and the order and type of each
initializer must match with the order and type of each member in declaration.
Ex: The above two structure variables stud1 and stud2 of structure type student can be
intialized as follows:
struct student stud1={13,18,”Balaji”,’m’,27500};
struct student stud2={5,18,”Sravani”,’f’,27500};

KHAN PUBLICATIONS
Page 2
Prepared by MD. IMRAN KHAN

The above two variables can also be initialized as follows:


struct student
{
int rno,age;
char name[15],sex;
float fees;
}stud1={13,18,”Balaji”,’m’,27500},stud2={5,18,”Sravani”,’f’,27500};
The memory map for the structure variable stud1 is as follows:

(2). By using scanf() statement


The input statement scanf() can be used to initialize the members of structure variables.
scanf() function can take members as arguments. Each member can be preceded with dot
operator that is preceded with structure variable. While reading members from keyboard,
there is no necessity of reading these in the same order as they are in structure declaration.
Ex: The structure variable stud1 of structure type student can be used to read all the members
of structure as follows:
scanf(“%d %s \n %c %f”,&stud1.rno, stud1.name, &stud1.sex, &stud1.fees);

ACCESSING STRUCTURE MEMBERS

We can access and assign values to the members of a structure in a number of


ways. Here members are not variables. They should be linked to the structure variables 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’. and it is follow as

<structure_variable>.<member_name>

For example,
book1.price

is the variable representing the price of book1 and can be treated like any other ordinary
variable. Now we are going to assign values to the members of book1.

strcpy(book1.title, “BASIC”);
strcpy(book1.author, “balagurusamy”);
book1.pages = 250;
book1.price = 120.50;

We can also use scanf to give the values through the keyboard.

scanf(“ %s \n” , book1.title);


scanf(“ %d \n” , &book1.pages);

KHAN PUBLICATIONS
Page 3
Prepared by MD. IMRAN KHAN

Program using structures:

(1). Read and print student details by using structures

#include<stdio.h>
struct student
{
int rno,age;
char name[15];
};
main()
{
struct student stud1;
printf(“\n enter student rno , name , age”);
scanf(“ %d %s %d \n”,&stud1.rno, stud1.name, &stud1.age);
printf(“\n student details”);
printf(“\n Rno= %d Name= %s Age= %d”, stud1.rno, stud1.name, stud1.age);
}

UNION

Definition and Declaration:

Union is also a user-defined data type like structures. There is a major difference
between them in terms of storage. In structures, each member has its own storage
location; where as all the members of a union uses the same location.
The general form of union is same as structures but here union declared using the
keyword union.
union tag_name
{
data_type1 member;
data_type2 member2;
………… …………
data_typeN memberN;

};

Let us take a example,

union item
{
int m;
float x;
char c;
} code;

KHAN PUBLICATIONS
Page 4
Prepared by MD. IMRAN KHAN

This declares a variable code of type union item. The union contains three
members, each with a different data type. However, we can use only one of them at a
time. This is due to the fact that only one location is allocated for a union variable,
irrespective of its size.
Storage of 4 bytes
1000 1001 1002 1004

c
m
x

Sharing of a storage locating by union members

The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union. In the declaration above, the member x requires 4 bytes which
is the largest among the members. The above figure shows how all the three variables
share the same address. This shows that a float variable requires 4 bytes of storage.

Initialization of Union

Though we can initialize all the members of a union at a time, only one member is
always active. Because all the members share the same memory location, the value of one
member overwrites the value of other member that is there in memory. The following program
demonstrates this:
#include<stdio.h>
main()
{
union student
{
int rno,age;
char name[15],sex;
float fees;
}s1;
s1.rno=6;
strcpy(s1.name,”Divya”);
s1.age=18;
s1.sex=’f’;
s1.fees=27500.00;
printf(“%d\t%s\t%d\t%c\t%f”,s1.rno,s1.name,s1.age,s1.sex,s1.fees);
}
Output: only the value of fees gets printed properly. All others are garbage values and
zeros.

KHAN PUBLICATIONS
Page 5
Prepared by MD. IMRAN KHAN

Accessing Union Members

To access any member of a union, we use the member access operator (.).
The member access operator is coded as a period between the union variable name
and the union member that we wish to access. We need to use keyword union to
define variables of union type.

The following example shows how to use unions in a program −

#include <stdio.h>
#include <string.h>

union Data
{
int i;
char str[20];
};

int main( )
{

union Data data;

data.i = 10;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.str : %s\n", data.str);

return 0;
}

When the above code is compiled and executed, it produces the following result −

data.i : 1917853763
data.str : C Programming

DIFFERENCE BETWEEN STRUCTURE AND UNION

Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
General form General form
struct tag_name union tag_name
{ {
data_type member1; data_type1 member;
data_type member2; data_type2 member2;
----------- ----------- ………… …………
----------- ----------- data_typeN memberN;
}; };

KHAN PUBLICATIONS
Page 6
Prepared by MD. IMRAN KHAN

For Example: Let us take a example,


struct book_bank union item
{ {
char title[20]; int m;
char author[15]; float x;
int pages; char c;
float price; } code;
};

2. When a variable is associated with a 2. When a variable is associated with a


structure, the compiler allocates the memory union, the compiler allocates the memory
for each member. by considering the size of the largest
memory.
3. Each member within a structure is 3. Memory allocated is shared by individual
assigned unique storage area of location. members of union.
4. Altering the value of a member will not 4. Altering the value of any of the member
affect other members of the structure. will alter other member values.

5. Individual member can be accessed at a 5. Only one member can be accessed at a


time time.
6. Several members of a structure can 6. Only the first member of a union can be
initialize at once. initialized.

ENUMERATION TYPES

An enumerated data type is a set of values represented by identifiers called


enumerators. The values of each enumerator can be specified when the type is specified.
An enumerated data type is declared as follows:

enum tag_name
{
enumerator-1 , enumerator-2,…… enumerator-n
};
Here, enum is the keyword, tag is the name of the enumerated data type.
enumerator-1, enumerator-2,…… are valid identifiers. All the enumerators should be
separated with commas and enclosed in curly braces.

Ex: enum color {red, green, blue};


Once the enumerators are declared in an enumerated data type, each enumerator
holds an integer constants. Usually, these constant start from 0. So, form the above
example, it is clear that the enumerators hold these constants: red=0, green=1, blue=2

Program: #include<stdio.h>
main()
{
enum color {red, green, blue};
printf( “Red= %d \n Green= %d \n Blue= %d ”, red, green , blue );
}

KHAN PUBLICATIONS
Page 7
Prepared by MD. IMRAN KHAN

Output:
Red =0
Green =1
Blue =2
We can also specify our own integer constants to enumerators as follows:
#include<stdio.h>
main()
{
enum color {red, green=234, blue};
printf(“Red=%d \n Green=%d \n Blue=%d”, red , green , blue);
}

Output: Red=0
Green=234
Blue=235

FILES

INTRODUCTION

In C programming, file is a place on your physical disk where information is


stored.

Using Files

 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter
them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
 You can easily move your data from one computer to another without any
changes.

Types of Files

When dealing with files, there are two types of files you should know about:

1. Text files
2. Binary files

1. Text files

Text files are the normal .txt files that you can easily create using Notepad or
any simple text editors.
When you open those files, you'll see all the contents within the file as plain
text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide least
security and takes bigger storage space.

KHAN PUBLICATIONS
Page 8
Prepared by MD. IMRAN KHAN

A file is for storing permanent data. C provides file operations in stdio.h. A file
is viewed as a stream of characters. Files must be opened before being accessed, and
characters can be read one at a time, in order, from the file.

Using text files in C

1. DECLARE a FILE * variable

FILE *infile;
FILE *outfile;

2. Binary files

Binary files are mostly the .bin files in your computer. Instead of storing data in
plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a
better security than text files.

Binary files are very similar to arrays of structures, except the structures are in
a disk-file rather than an array in memory. Binary files have two features that
distinguish them from text files:

 You can instantly use any structure in the file.


 You can change the contents of a structure anywhere in the file.

FILE MANAGEMENT FUNCTIONS

In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Working with files

When working with files, you need to declare a pointer of type file. This
declaration is needed for communication between the file and program.

FILE *fptr;

FUNCTION NAME OPERATION


fopen() Creates a new file for use
fclose() Closing a file
fprintf() Writing to a text file
fscanf() Reading a file

KHAN PUBLICATIONS
Page 9
Prepared by MD. IMRAN KHAN

(1). Opening a file - for creation and edit:

Description

The C library function FILE *fopen(const char *filename, const char *mode)
opens the filename pointed to, by filename using the given mode.

Declaration
Following is the declaration for fopen() function.

FILE *fopen(const char *filename, const char *mode)

For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");

(2). Closing a File

The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().

Description
The C library function int fclose(FILE *stream) closes the stream. All buffers
are flushed.

Declaration
Following is the declaration for fclose() function.
int fclose(FILE *stream)

(3). Writing to a text file

Description
The C library function int fprintf(FILE *stream, const char *format, ...)
sends formatted output to a stream.

Declaration
Following is the declaration for fprintf() function.
int fprintf(FILE *stream, const char *format, ...)

(4). Reading a file

Description
The C library function int fscanf(FILE *stream, const char *format, ...)
reads formatted input from a stream.

Declaration
Following is the declaration for fscanf() function.
int fscanf(FILE *stream, const char *format, ...)

KHAN PUBLICATIONS
Page 10

You might also like