C-Language Unit-4 PDF
C-Language Unit-4 PDF
C-Language Unit-4 PDF
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
Structures must be defined first for their format that may be used later to declare
structure variables.
struct tag_name
{
data_type member1;
data_type member2;
----------- -----------
----------- -----------
};
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
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.
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;
KHAN PUBLICATIONS
Page 2
Prepared by MD. IMRAN KHAN
<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.
KHAN PUBLICATIONS
Page 3
Prepared by MD. IMRAN KHAN
#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
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;
};
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
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
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.
#include <stdio.h>
#include <string.h>
union Data
{
int i;
char str[20];
};
int main( )
{
data.i = 10;
strcpy( data.str, "C Programming");
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.str : C Programming
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
ENUMERATION TYPES
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.
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
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.
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:
In C, you can perform four major operations on the file, either text or binary:
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;
KHAN PUBLICATIONS
Page 9
Prepared by MD. IMRAN KHAN
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.
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
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)
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, ...)
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