0% found this document useful (0 votes)
24 views22 pages

Unit 2 Notes

Uploaded by

Benitta Mary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views22 pages

Unit 2 Notes

Uploaded by

Benitta Mary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT II-PROGRAMMING - ADVANCED FEATURES

Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables,


Arrays and Functions – File Handling – Preprocessor Directives.
2. INTRODUCTION
 Structures, unions and enumerations are known as user defined data types.
 These data types are used to create a flexible new data type.
 Structure can be used for the storage of different data types. The similarity
between structure and array is both contain a finite number of elements.
 Union is similar to structures in all aspects except the manner in which their
constituent elements are stored.
 In structures, separate memory is allocated to each element, while in unions all
the elements are share the same memory.
 Enumeration helps to define a data type whose objects can take a limited set of
values.

2.1 STRUCTURE
Definition
 A Structure is a collection of variables of different data types under a single
name and provides a convenient way of grouping several of related information
together.
 Unlike arrays, it can be used for the storage of heterogeneous data (data of
different data types).
2.1.2. Three main aspects of working with structure
1. Defining a structure type (Creating a new type)
2. Initializing structure elements
3. Declaring variables and constants (objects) of the newly created type.
2.1.3.Defining Structure
Syntax
struct structure_name
{
element-1;
element-2;
element-3; //Variable declarations
...
...
element-n;
} v1, v2......vn;
Where element1, element2, element3 are variables of any primitive or derived
data types and v1, v2,. vn are structure variable.
Example
struct book
{
char author [40];
float price;
int page;
} b1, b2;
Rules for defining structure
 Structure definition consists of the keyword struct followed by a structure tag
name and a structure declaration list enclosed within braces.
 The structure declaration list consists of one or more variables declaration,
possibly of different data types. The variable names declared in the structure
declaration list are known as structure members.
 Structure members can be variables of the basic types( eg: char, float, int) or
pointer type(eg: char *, int *) or aggregate type(eg: array).
 A structure declaration list cannot contain a member of void type or incomplete
type or function type.
 Self- referential structure: a structure may contain a pointer to an instance of
itself is known as self-referential structure.
2.1.4.Initializing Structure Elements
Syntax
Struct book
{
int page;
char author[10];
float price;
}b1;
Example
void main()
{
b1. author=” Kalam”;
printf(“Enter price:”);
scanf(“%f”,&b1.price);
b1.page=178;
}

2.1.5. Declaring Structure Objects


 Variables (or) constants of the created structure type can be created either at the
time of structure definition (or) after the time of structure definition.
Syntax
[type qualifier] structure type identifier name [= initialization list]; (or) variables;
Example
struct book b1={3,2,1}; // it contains the initialization list
struct book b1,b2,b3; // it contains the variable

Rules for declaring structure objects:


 It is important to note that the structure members cannot be initialized during the
structure definition; however the members of a structure object can be initialized
by providing an initialization list.
Aggregate Operations
 An aggregate operation treats an operand as an entity and operates on the
entire operand as whole instead of operating on its constituent members.
Types
a) Accessing members of an object of a structure
b) Assigning a structure object to a structure variables
c) Address of a structure object
d) Size of a structure.
a) Accessing members of an object of a structure :
The members of a structure object can be accessed by using:
(i) Direct member access operator (dot operator)
(ii) Indirect member access operator(arrow operator)
(i) Direct member access operator (dot
operator): Syntax:
struct variable-name.struct-element-name
(ii)Indirect member access operator (arrow operator)
Syntax :
struct variable name -> struct element name
(or)
*struct variable name . struct element name
b) Assigning a structure object to a structure variables
 Assignment operator (=) is used to assign the values of one variable to another
variable. When assignment operator (=) is applied on structure variables, it
performs member by member copy.
c) Address of a structure object
 The address of operator (&) when applied to a structure object gives its base
address. It can also be used to find the address of the constituting members of a
structure object.
Size of a structure.

 When the sizeof operator is applied to an operand of a structure type it will


produce the result as how much memory space is occupied by that particular
object.
Syntax:
sizeof
(expression);
sizeof type
Example:
sizeof (struct book); // use structure’s name
sizeof b1 // use variable

Program
#include<stdio.h>
struct book //structure type declaration
{
char a; // elements are declared
int b;
char c;
float d;
}; //structure type declarations are terminated
void main()
{
struct book var; //variable declaratio
printf(“obj of struct book will take %d bytes\n”,sizeof(struct book));
printf(“structure variable var takes %d bytes\n”, sizeof var);
}
Output:

obj of struct pad will take 8 bytes


structure variable var takes 8 bytes

2.2 UNION
 Union can be defined as a user-defined data type which is a collection of
different variables of different data types in the same memory location. The
union can also be defined as many members, but only one member can contain a
value at a particular point in time. Unions provide an efficient way of using the
same memory location for multiple-purpose.
 Union is a user-defined data type, but unlike structures, they share the same
memory location.
Defining a Union
 To define a union, you must use the union statement in the same way as did
while defining a structure. The union statement defines a new data type with
more than one member for your program. The format of the union statement is
as follows:
union [union tag]
{ member
definition; member
definition;
...
member definition;
} [one or more union variables];
 The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end
of the union's definition, before the final semicolon, you can specify one or more
union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str.
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. It means a single variable, i.e., same memory location, can be
used to store multiple types of data. You can use any built-in or user defined data
types inside a union based on your requirement.
Example Program Illustration of Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
void main( )
{ union Data
data; data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "Charulatha publication");
printf( "data.str : %s\n", data.str);
}
Output
data.i : 10
data.f : 220.500000
data.str : Charulatha publication
Difference between Structure and Union
Sl.No Structure Union
1 The member of a structure occupies The member of union share same
its own memory space. memory space.
2 The keyword struct is used to define The keyword union is used to define a
a structure structure
3 All the members of a structure can Only the first member of a union can
be initialized. be initialized.
4 In structure, each member is stored In union, all members are stored in
in a separate memory location. So the same memory locations. So, need
need more memory space. less memory space.

2.3 Enumerated Data Types


Defintion: The enum is an abbreviation used for enumerated data type. When this
keyword is used, we can basically initialize the sequence of integer constants.

The syntax is
enum identifier_name{sequence of items};

For example :

enum fruit {Mango, Orange, Banana, Grapes, Guava};

Here fruit is the name given to the set of constants. If there is no value given to the
sequence then by default the first value in the list is 0. For instance here Mango = 0,
Orange = 1, Banana = 2, Grapes = 3 and Guava = 4. We can reassign these values as
well.

For instance :

Mango = 1, Orange = 2, Banana= 3, Grapes = 4 and Guava = 5.Similarly we can write

enum fruit {Mango = 2, Orange, Banana-8, Grapes, Guava};

then the values get set automatically as

Mango= 2, Orange = 3

Banana= 8, Grapes = 9, Guava = 10


The main advantage of enum is that even if we do not initialize the constants, each one
would have a unique value. The first would be zero and the rest would be one more than
the previous one.

Let us understand the use of enumerated data type with the help of following C program -

C Program

#include<stdio.h>

#include<stdlib.h>

void main( )

enum fruit {Mango, Orange, Banana, Grapes, Guava};

printf("\n Mango: %d",Mango);

printf("\n Orange: %d", Orange);

printf("\n Banana: %d", Banana);

printf("\n Grapes: %d", Grapes);

printf("\n Guava: %d", Guava);

getch( );

Output

Mango: 0

Orange: 1

Banana: 2

Grapes: 3

Guava: 4

2.4 POINTERS
2.4.1 Pointers to Variables
 A pointer is a variable that stores an address of another variable of same type.
 Pointer can have any name that is legal for other variable.
 Pointer variables are declared with prefix of ‘*’ operator.
 Using a pointer variable, we can access the value of another variable assigned to
it.
Syntax
data_type *pointer_name;
Example
int *a;
 variable *a can store the address of any integer type variable.
 A pointer is a variable whose value is also an address.
 Each variable has two attributes
 Value
 Address
We can define pointers in two ways.
i) First a pointer is a variable and assigns different values to a pointer variable.
ii) Second the value contained by a pointer must be an address which indicates the
location of another variable in the memory. So, pointer is called as “address
variable”.
Example
int a=50; int
*ptr;
ptr=&a;

 Here ‘a’ is a variable holds a value 50 and stored in a memory location 1001.
‘*ptr’ is pointer variable holds a address of a variable ‘a’.
Advantages of Using Pointers
 Pointers are more compact and efficient code.
 Pointers can be used to achieve clarity and simplicity.
 Pointers are used to pass information between function and its reference point.
 A pointer provides a way to return multiple data items from a function using its
function arguments.
 Pointers also provide an alternate way to access an array element.
 A pointer enables us to access the memory directly.
Example Program
/*C program for printing value and address of a variable using pointer variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *ptr;
ptr=&i;
clrscr();
printf(“Address of i=%u\n”,ptr);
printf(“value of i=%d\n”,*ptr);
getch();
}
Output:
Address of i=65524
value of i=3

2.4.2 Pointer operators


a) Referencing a pointer
 A pointer variable is made to refer to an object.
 Reference operator(&) is used for this.
 Reference operator is also known as address of (&) operator.
Example

float a=12.5; float *p; p=&a;

b) Dereferencing a pointer
 The object referenced by a pointer can be indirectly accessed by
dereferencing the pointer.
 Dereferencing operator (*) is used for this.
 This operator is also known as indirection operator or value- at-operator.
Example
int b;
int a=12; a
int *p;
Example program
#include<stdio.h> void
main()
{
int a=12; int
*p;
int **pptr;
p=&a;
pptr=&p;
printf(“Value=%d”,a);
printf(“value by dereferencing p is %d \n”,*p);
printf(“value by dereferencing pptr is %d \n”,**pptr);
printf(“value of p is %u \n”,p);
printf(“value of pptr is %u\n”,pptr);
}
Output
Value=12
value by dereferencing p is 12 value
by dereferencing pptr is 12 value of
p is 1000
value of pptr is 2000

2.5 Arrays and Functions


When an array is passed as an argument to the function then we are actually passing the base
address of an array to the function. Using this base address we can access the remaining
elements of the array in the function. Thus instead of actual value, the address is passed as a
parameter to the function hence it is called parameter passing by address.
#include<stdio.h>
#include<conio.h>
void main()
{
void fun(int a[5]);/*function declaration*/
int a[]={10,20,30,40,50};
clrscr();
fun(a);/*call to the function*/ Passing the base address of an array
getch();
}
void fun(int a[6])
int i;
}
for(i=0;i<5;i++)
printf("%d",*(a+i));
/* or printf("%d",a[i]);*/
}
Output
10 20 30 40 50

2.6 FILE HANDLING


 A file is a collection of bytes stored on a secondary storage device, which is
generally a disk of some kind. The collection of bytes may be interpreted, for
example, as characters, words, lines, paragraphs and pages from a textual
document; fields and records belonging to a database; or pixels from a graphical
image.
 The meaning attached to a particular file is determined entirely by the data
structures and operations used by a program to process the file. It is conceivable
(and it sometimes happens) that a graphics file will be read and displayed by a
program designed to process textual data.
 The result is that no meaningful output occurs (probably) and this is to be
expected. A file is simply a machine decipherable storage media where programs
and data are stored for machine usage.
2.6.1 File Operations
 In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
 However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in
C.
 File handling in C enables us to create, update, read, and delete the files stored on
the local file system through our C program. The following operations can be
performed on a file.
 Creation of the new file
 Opening an existing file
 Reading from the file
 Writing to the file
 Deleting the file
2.6.1.1 Types of Files
2.6.1.1.1 There are two kinds of files in which data can be stored in two
ways either in characters coded in their ASCII character set or in binary
format. They are
1. Text Files (or) ASCII file
2. Binary Files
Text Files (or) ASCII file
2.6.1.1.2 The file that contains ASCII codes of data like digits, alphabets and
symbols is called text file (or) ASCII file.
Binary Files
2.6.1.1.3 A binary file is a file that uses all 8 bits of a byte for storing the
information. It is the form which can be interpreted and understood by the
computer.
2.6.1.1.4 The only difference between the text file and binary file is the data
contain in text file can be recognized by the word processor while binary file
data can’t be recognized by a word processor.
1. wb(write)
This opens a binary file in write mode.
SYNTAX: fp=fopen(“data.dat”,”wb”);
2. rb(read)
This opens a binary file in read mode
SYNTAX:fp=fopen(“data.dat”,”rb”);
3. ab(append)
This opens a binary file in a Append mode i.e. data can be added at the end of
file.
SYNTAX: fp=fopen(“data.dat”,”ab”);
4. r+b(read+write)
This mode opens preexisting File in read and write mode.
SYNTAX: fp=fopen(“data.dat”,”r+b”);
5. w+b(write+read)
This mode creates a new file for reading and writing in Binary mode.
SYNTAX: fp=fopen(“data.dat”,”w+b”);
6. a+b(append+write)
This mode opens a file in append mode i.e. data can be written at the end of file.
SYNTAX: fp=fopen(“data.dat”,”a+b”);
Opening Modes in Standard I/O
r Open for reading If the file does not exist, fopen() returns
NULL
rb Open for reading in binary If the file does not exist, fopen() returns
mode. NULL.
w Open for writing. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb Open for writing in binary If the file exists, its contents are overwritten.
mode. If the file does not exist, it will be created.

a Open for append. i.e, Data is If the file does not exists, it will be created.
added to the end of file.
ab Open for append in binary If the file does not exists, it will be created.
mode. i.e, Data is added to
end of file.
r+ Open for both reading and If the file does not exist, fopen() returns
writing. NULL.
rb+ Open for both reading and If the file does not exist, fopen() returns
writing in binary file. NULL
w+ Open for both reading and If the file exists, its contents are overwritten.
writing. If the file does not exist, it will be created.
wb+ Open for both reading and If the file exists, its contents are overwritten.
writing in binary mode. If the file does not exist, it will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.
ab+ Open for both reading and If the file does not exists, it will be created.
appending in binary mode.

Closing a File: fclose(fptr);


2.6.1.1.5 The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().
Reading and writing to a text file
2.6.1.1.6 The functions fprintf() and fscanf() are used to read or write the file
They are just the file versions of printf() and scanf(). The only difference is
that, fprint and fscanf expects a pointer to the structure FILE.
Writing to a text file
Write to a text file using fprintf()
#include <stdio.h> int
main()
{
int num;
FILE *fptr;
fptr = fopen(“C:\\program.txt”,”w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num: “);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num); fclose(fptr);
return 0;
}
Reading from a text file
Program Read from a text file using fscanf()
#include <stdio.h> int
main()
{
int num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.txt”,”r”)) == NULL)
{ printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,”%d”, &num);
printf(“Value of n=%d”, num);
fclose(fptr);
return 0;
}
Reading and writing to a binary file
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Writing to a binary file
To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk, number
of such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Reading from a binary file
Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Program Reading from a binary file using fread()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.bin”,”rb”)) == NULL)
{ printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf(“n1: %d\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
Text Files
In C, all components are files, each with a different behavior based on the attached devices.
To enable the I/O functions, several standard built-in functions were created and stored in
libraries.
Some of the high level file I/O functions are given in
High level file I/O functions
S.No Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file

1. fopen () : It creates a new file for use or opens an existing file for use.
2. fclose (): It closes a file which has been opened for use.
3. fscanf( file pointer, format string, address of the variable)
Example: fscanf(fptr,”%d”, &num);
4. fprintf(console output, “format string”, file pointer);
Example: fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
5. getw (): This function returns the integer value from a given file and increment the
file pointer position to the next message.
Syntax: getw (fptr);
Where fptr is a file pointer which takes the integer value from file.
6. putw (): This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a given file.
Example Program for getw() and putw()
Program Write a program to read integer data from the user and write it into the
file using putw() and read the same integer data from the file using getw() and
display it on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
clrscr();
fp=fopen(“c.dat”, “wb+”);
printf(“Enter the integer data”);
scanf(“%d”,&n);
while(n!=0)
{
putw(n,fp);
scanf(“%d”,&n);
}
rewind(fp);
printf(“Reading data from file”); while((n=getw(fp))!
=EOF)
{
printf(“%d\n”,n);
}
fclose(fp);
getch();
}
7. fwrite()
 This function is used for writing an entire block to a given file.
Syntax: fwrite(ptr,size,nst,fptr);
ptr is a pointer ,it points to the array of structure.
Size is the size of the structure nst
is the number of the structure fptr
is a filepointer.
8. fread()
 fread(ptr,size,position,fptr);similar to fwrite
9. fflush(stdin);To clean the input stream
Program program for fwrite():
Write a program to read an employee details and write them into the file at a time
using fwrite().
#include<stdio.h>
#include<conio.h>
void main()
{
struct emp
{
int eno;
char ename[20];
float sal;
}e;
FILE *fp; fp=fopen(“emp.dat”,
“wb”); clrscr();
printf(“Enter employee number”);
scanf(“&d”,&e.eno); printf(“Enter
employee name”); fflush(stdin);
scanf(“%s”,e.ename); printf(“Enter
employee salary”);
scanf(“%f”,&e.sal);
fwrite(&e,sizeof(e),1,fp);
printf(“One record stored successfully”); getch();
}
Operations for Search data in a file
1. fseek()
2. ftell()
3. rewind()
fseek() : Getting data using fseek()
 When many records inside a file and need to access a record at a specific position,
you need to loop through all the records before it to get the record. This will waste
a lot of memory and operation time. An easier way to get to the required data can
be achieved using fseek().
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
fseek(file pointer, displacement, pointer position);
 The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.
 This function is used for seeking the pointer position in the file at the specified
byte.
Syntax: fseek( file pointer, displacement, pointer position); file
pointer - It is the pointer which points to the file.
displacement -It is positive or negative.
 This is the number of bytes which are skipped backward (if negative) or forward
(if positive) from the current position. This is attached with L because this is a
long integer.
Pointer position: This sets the pointer position in the file.
Value Pointer position Value Pointer position
0 Beginning of file.
1 Current position
2 End of file
2.7 PREPROCESSOR DIRECTIVES
 The C preprocessor is a microprocessor that is used by compiler to transform your
code before compilation. It is called micro preprocessor because it allows us to add
macros.
 Note: A macro is a segment of code which is replaced by the value of macro.
Macro is defined by #define directive.
Example
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.

 All preprocessor directives starts with hash # symbol. Let's see a list of
preprocessor directives.
 #define: It substitutes a preprocessor using macro.
 #include: It helps to insert a certain header from another file.
 #undef: It undefines a certain preprocessor macro.
 #ifdef: It returns true if a certain macro is defined.
 #ifndef: It returns true if a certain macro is not defined.
 #if, #elif, #else, and #endif: It tests the program using a certain condition; these
directives can be nested too.
 #line: It handles the line numbers on the errors and warnings. It can be used to
change the line number and source files while generating output during
compile time.
 #error and #warning: It can be used for generating errors and warnings.
 #error can be performed to stop compilation.

 #warning is performed to continue compilation with messages in the console


window.

You might also like