Transcript
8/3/2019 C-IV v Vi Vi Viii Unit Notes
1/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 1
UNIT-IV
ARRAYS
Arrays : An array is a group of selected data items that share a common name,with in which
each element is an unique one and located in contiguous memory locations.
Declaration of an array : data type array-name[array_size];
ex : int a[5];
it tells to the compiler that 'a' is an integer type of array and can store 5 integers. the compiler
reserves 2 bytes of memory for each integer array element.
Array initializtion : An array can be initiiazed as follows
int a[5]={1,2,3,4,5};
here 5 elements are stored in an array 'a', the array elements the stored sequentially in
separate locations i.ein contiguous memory locations.
Accessing array elements : Reading of array elements begins from '0'. Array elements are
accessed by the array names followed by the element numbers. These numbers may be refred
to as indices of the array
a[0] a[1] a[2] a[3] a[4]
1 2 3 4 5
100 102 104 106 108
Arrays can be initilized in the following ways also
int a[]={1,2,3,4,5};
int a[5]={1,2,3,4,5};
8/3/2019 C-IV v Vi Vi Viii Unit Notes
2/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 2
y Til the array elements are not given any specific values,theyare supposed to contain garbage values.
y The subscript of the array is termed as the dimension of the array.y In C ,there is no check to see if the subscript used for an array exceeds the size of the
array. Data entered with a subscript exceeding the array seze will simply be placed in
memory outside the array,probably on top of the other data or on the program itself.
This wil lead to unpredictable results. Thus,it is necessary to check that we do not
reach beyond the array size.
Ex : main()
{
for(i=0;i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
3/61
8/3/2019 C-IV v Vi Vi Viii Unit Notes
4/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 4
we can access the elements of an 2-D array in the same way as that of an one-dimensional
array, using the indeces , but here we will have two subscripts, one for rows and one for
columns.
For Ex : in the students_marks array such as stud[4][2],an element can be accessed using the
indeces as follows stud[1][0] represents the 2nd row- first element of the array, as here also the
counting of rows and columns begin with 0. To access the third row,second element ,the
element to be accessed array can be viewed as a collection of one-dimensional array can be
viewed as collection of one-dimensional arrays placed one below the others.
Initialising a 2-Dimensional Array :
we can initialize a 2-d array in one of the following ways
int stud[3][2]={0,1,1,0,1,0}
int stud[3][2]={{0,1},{1,0},{1,0}}
It is important to remember that,while initializing a 2-D array, it is necessary to mention the
second (column) dimension , where as the first dimension,where as the first dimension(row) is
optional.
Ex: int stud[ ][2]={0,1,1,0,1,0} /* it is valid */
where as
int stud[ ][ ]={1,0,1,0,1,0};
int stud[3][ ]={1,0,1,0,1,0};
these intialization would never work.
However the 2-D array array element can be viewed as a collection of rows and columns,
but in memory,where it is a one-dimensional or a two-dimensional array ,the array elements
are stored in one continuous chain. First of all,the elements of first row are stored,followed
by second row and so on.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
5/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 5
Ex : s[3][3] is a 2-D array & its elements are stored in memory as follows
s[0][0] s[0][1] s[0][2] s[1][0] s[1][1] s[1][2] s[2][0] s[2][1] s[2][2]
10 90 60 50 40 10 30 40 30
102 104 106 108 110 112 114 116 118
the memory elements are stored in contiguous memory locations in row-wise
Multi-Dimensional Arrays : C-allows arrays of three or more dimensions. The general form of
multi-dimensional array is
data_type array_name[s1][s2][s3].........[si];
where i is the size of the i'th dimension ;
Ex : int x[3][4][2]; /* a three dimensional array */
int a[5][3][4][2] /* a 4-D array */
Initializing a 3-D array :
int a[3][4][2]= {
{ {2,4},{7,8},{3,4},{5,6}},
{ {7,6},{3,4},{1,2},{4,5}},
{ {8,9},{7,2},{1,4},{3,5}}
};
A three-dimensional array can be thought of as array of two-dimensional arrays. Here in the
example the outer array has three elements, each of which is a two dimensional array of four
one-dimensional arrays, each of which contains two elements. What ever may be dimensions
of the array. The elements are stored in contiguous memory locations only. The elements are
accessed using the indeces starting from '0', like those of 1-D or 2-D arrays
Number of elements in a 3-D array like a a[3][5][2] is 3x5x2=30 elements. Likewise, the
number of elements of any n-dimensional array can be calculated.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
6/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 6
2-D array applications : By making use of 2-D arrays we can perform any operations on the
matrices, such as additions of two matrices, multiplication of two matrices, check the
symmetrisity of a matrix etc.
UNIT-V
FUNCTIONS
Functions : A function is a self-contained block of statements that perform a task of some
kind. Every C program can be thought of as a collection of these functions. C functions can be
classified into two categories, namely,library functions and user-defined functions main is an
example of user-defined functions,where as printf and scanf belong to the category of library
functions. The main distinction between these two categories is that library functions are not
to be written by us where as a user-defined function has to be developed by the user at the
time of writing a program.
Main is a specially recognized function in C. Every program must have a main function to
indicate where the program has to begin its execution. When the program is too large and
complex, the task of debugging, testing and maintaining becomes difficult. If a program is
divided into functional parts, then each part may be independently added and later
combined into a single unit . These subprograms are called functions . these are much
easier to understand,debug and test.
A Multi-Function Program : Once a function has been designed and packed,it can be treated
as a 'black box' that takes some data from the main program and returns a value. The inner
details of operation are invisible to the rest of the program . All that the program knows
about a function is what goes in and what comes out.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
7/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 7
Ex : /* Illustration of the use of functions */
main()
{
printline();
printf( this a function calling program);
printline();
}
printline()
{
int i;
for(i=1;i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
8/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 8
y Any function can call any other function.y A 'called function' can also call other function. In above ex: main() is called 'calling
function ' and printline() and printline() is called 'called function.
y A function can be called more than once.y The functions can be palced in any order i.e a called function can be placed either
before or after calling function.
Format for C - functions :
function_name(argument list)
argument declaration;
{
local variable declaration;
stmt-1;
stmt-2;
.
.
.
stmt-n;
return(expression);
}
A function can have any number of executable statements. The return statement is the
mechanism for returning a value to the calling function. This is also an optional statement. Its
absence indicates that no value is being returned to the calling function . Function name must
follow the same rules of formation as other variable names in C . the argument list contains
valid variable names separated by commas. The list must be surrounded by parantheses. The
argument variables receive values from the calling function thus providing a means for data
communication from the calling function to the called function. All these variables must be
declared for their types.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
9/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 9
Categories of Functions : A function ,depending on whether arguments are present or not and
whether a value is returned or not , may belong to one of the following categories
1. Functions with no arguments and no return values.2. Functions with arguments and no return values.3. Functions with arguments and return values.
when a function has no arguments, it does not receive any data from the calling function.
Similarly when it does not return a value, the calling function does not receive any data from
the called function . In effect there is no data transfer between the calling function and the
called function .
The program implemented before with main() and printline() is an example of function with
no arguments and no returned values. As no return statement is employed, it does not return
any value to the calling function . In the same way printline() does not receive any data fromthe calling function i.e main().
Arguments but no return values : In the example the printline() will print the same line each
time it is called . We can make the calling function to read data from the terminal and pass it
on to the called function. In this way , the calling function can check for the validity of data ,if
necessary , before it is handed over to the called function .
Ex: main()
{ /* this is the way we used functions with no arguments & no return values */
printline();
sum(); /*function display the sum of the digits */
printline();
}
The same program can be implemented with arguments but no return values as follows
main()
{
int num; char ch;
void printline();void sum(); /*Function declaration */
8/3/2019 C-IV v Vi Vi Viii Unit Notes
10/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 10
printf(enter the num to print sum of digits );
scanf(%d.&num);
printf(enter the character to be printed :\n);
scanf(%c,ch);
printline(ch); /*function call */
sum(num);printline(ch); /*other function calls */
}
printline(char c)
{
int i;
for(i=1;i0)
{
digit=n%10;
n=n/10;
sum=sum_d+digit;
}
8/3/2019 C-IV v Vi Vi Viii Unit Notes
11/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 11
printf(sum=%d,sum_d);
}
Here the arguments ch,num are called actual arguments i.e arguments,in the function call are
called as actual arguments, where as the arguments in the function definition i.e c,n are
called as formal arguments the values of the actual arguments become the values the actual
arguments become the values of the formal arguments inside the called function. The actual
and formal arguments should match in number,type and order. The values of actual
arguments are assigned to the formal arguments on a one to one basis, starting with the first
argument we should ensure that the function call has matching arguments. In case , the actual
arguments are more than the formal arguments,the extra actual arguments are discarded on
the otherhand, if the actual arguments are less than the formal arguments,the unmatched
formal arguments are intialized to some garbage values. Any mismatch in data type may alsoresult in passing of garbage values. But no error message will be generated.
Arguments with return values :In the above example sum() receives data from the calling
function through arguments, but does not send back any value. However, we can send the
results of the calculation back to the main(),using the return statement. Such functions have
two-way data communication i.e data is transferred between both the calling function and
the called function.
A C-function returns returns a value of the type int as the default case when no other type is
specified explicitly. To return any non-integer value, the type-specifier must be specified along
with the function-name in the function header. the type specifier tells the compiler, the type
of data the function is to return. The called function must be declared at the start of the start
of the body in the calling function, like any other variable,to tell the calling function the type
of data that the function is actually returning.
Ex : main()
{
float a,b,mul();
int div();
a=12.82;b=8.2;
printf(mul value =%f ,mul(a,b));
8/3/2019 C-IV v Vi Vi Viii Unit Notes
12/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 12
printf(Div value=%d,div(a,b));
}
float mul(float a1,float b1)
{
return(a1*b1);
}
int div(float x, float y)
{
return(x/y);
}
Storage classes : A variable is C can have any one of the four storage classes.
1.Automatic variables.
2.External variables.
3. Static variable.4. Register variables.
The scope of the variable determines over what parts of the program a variable is actually
available for use. The longevity refers to the period during which a variable retains a given
value during execution of a program (alive).so longevity has a direct effect on the utility of a
given variable.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
13/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 13
The variable may also be broadly categorized,depending on the place of their declaration, as
internal (local) or external (global). Internal variable are those which are declared within a
particular function, which external variables are declared outside of any function.
Automatic variables :
Automatic variable are declared inside a function in which they are to be utilized.
They are created when the function is called and destroyed automatically when the function
is exited, so these variable are private or local to the function in which they are declared.
They are also referred to as local or internal variables.
A variable declared inside a function without storage class specification is by default, an
automatic variable. We may also use the keyword ' auto ' to declare automatic variables
explicitly.
Ex : main() main()
{ {
int num; (or) auto int num;
............... ....................
............... ....................
} }
' num ' is a local variable,both declaration are valid. One important note is that we may
declare and use the same variable name in different functions in the same program without
causing any confusion to the compiler.
External variables : variables that are both alive and active throughout the entire program
are known as external variables. They are also known as global variables. Unlike local
variables global variables can be accessed by any function in the program. External variables
are declared outside a function. In case a local variable and a global variable have the same
8/3/2019 C-IV v Vi Vi Viii Unit Notes
14/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 14
name, the local variable will have precedence over the global one in the function where it is
declared.
` int num,no
main() fun1() fun2()
{ { {
- - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - -
} } }
Global variable can be accessed by any function. Once a variable has been declared as global,
any function can use it and change its value. Then subsequent functions can reference only
that new value global variable can also be declared with the storage class extern .
Ex : main() fun1()
{ {
extern int y; extern int y;
} }
Here in the above example, although the variable y has been defined in the functions, the
external declaration of y inside the functions informs the compiler that y is an integer type
defined some where else in the program. The default initial value of external variable is zero.
The longevity of external variables losts as long as the programs execution doesn't come to an
end.
Static variables : A variable can be declared static using the keyword static
the value of the static variables persists until the end of the program. A static variable is
initialized only once,when the program is compiled it is never initialized again. The static
variables can be used to retain values between function calls. The default initial value of static
variable is zero. The scope of these variables is local to the block in which the variable is
defined.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
15/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 15
Ex : main() fun1()
{ {
for(int i=0;ix=8.
abs() : It returns the absolute value of the argument passed to it , i.e the positive rendered
value of the argument Ex: x=abs(-10)=> x=10.
sqrt(): it returns the square root of the argument passed to this function.
Ex : y=sqrt(25);
y=5.
ceil() : a ceiling value is the smallest integer value grater than or equal to a number.
Ex : ceil (-1.9) returns -1.0;
8/3/2019 C-IV v Vi Vi Viii Unit Notes
16/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 16
ceil(1.1) returns 2.0;
floor : a floor is the largest integral value that is equal to or less than a number
Ex : floor(-1.1) returns -2.0
floor(1.9) returns 1.0
turnc() : this function returns the integral in the direction of 0. they are same as floor function
for positive numbers and same as ceiling function for negative numbers.
Ex : trunc(-1.1) returns -1.0, trunc(1.9) returns 1.0
round() : the round function returns the nearest integral value. Only real values are passed as
arguments there is no such a round function that returns an int .
Ex : round(-1.1) returns -1.0,round(1.9) returns 2.0.
rand() : this function generates random numbers which uses a formula that has been
mathematically designed to ensure that each time this function is called returns a true random
numbers.
Besides these functions, some string functions such as strcpy(),strcat(),strrev() ect. Are also
stored in standard library. Other strings functions are :
tolower() : This function converts the string passed as argument to lowercase.
Ex :- str= HIGH , str1=tolower(str);
str1=high
toupper : this is same as tolower(),but converts the string passed as an argument to uppercase
gets() :Used to reading strings.
puts() :Used for printing strings.
In the same way getchar() and putchar() are used for reading and printing characters.
User defined functions :- main is a specially recongnized function in C. every program must
have a main function to indicate where the program has to begin its execution. While it is
possible to code any program utilizing only main function ,it leads to a number of
problems. The program may become too large and complex and as a result the task of
8/3/2019 C-IV v Vi Vi Viii Unit Notes
17/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 17
debugging ,testing and maintaining become difficult. If a program is divided into functional
parts, then each part may be independently coded and later combined into a single unit.
These subprograms called functions are much easier to understand ,debug and test. Such
functions are called as user-defined functions.
Ex :- void function_name(parameter list)
{
statements;
}
As explained in the previous sections, the functions may fall in to any one of the following
categories
1. Functions with no arguments and no return values.2. Functions with arguments and no return values.3. Functions with arguments and return values.
The arguments passed to these functions may belong to any primitive data type such
as int,float, char or double or to any user defined data type such as arrays, pointers etc. the
returns values can also belong to any one of the above mentioned data types. The variables
declared within the function have scope residing with in the function only, i.e they cannot be
accessed outside the function, unless they are declared as belonging to static data type.
Changes made to formal argument in called function will not affect the actual arguments in
the calling function, unless we pass the argument with the use of pointer variables.
Recursion :- When a called function in turn calls another function, a process of chaining occurs
. Recursion is a special case of this process i.e when a function calls itself, it is termed as
recursion.
Ex :- fun1()
{
printf( In function 1 );
fun()1;
8/3/2019 C-IV v Vi Vi Viii Unit Notes
18/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 18
}
when executed,it produces output as :
In function1
In function1
In function1
....
...
In function1
unless you terminate the program execution abruptly, the execution will continueindefinately.
Ex1 :-Program to print factorial of a given number using recursion.
#include
int factor(int);
main()
{
int a,fact;
printf(enter the number \n);
scanf(%d,&a);
fact=factor(a);
printf(factorial =%d,fact);
}
int factor(int n)
{
int f;
8/3/2019 C-IV v Vi Vi Viii Unit Notes
19/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 19
if(n==1)
return 1
else
f=n*factor(n-1);
return f;
}
O/p :-
enter the number : 5
factorial :120
Ex2:- Recursive solution for fibonacci series.
#include
int fib(int);
main()
{
int n, fnum;
printf(enter values for n : \n);
scanf(%d,&n);
fnum=fib(n);
printf(%d,fnum);
}
int fib(int x)
8/3/2019 C-IV v Vi Vi Viii Unit Notes
20/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 20
{
if(x>2)
return(fib(x-1)+fib(x-2));
else return 1;
}
Header files :In general, a header file is included in program when the program needs one or
more function prototypes, which are already defined in that header file. C supports 24
standard header files, which contains definitions for the standard library functions that are
commonly use in C programs. Based on the type of operations performed by functions , they
are grouped into those 24 header files. These header files are ended with a '.h' extension.
Some of them are :
assert.h :- This header file contains a macro name assert(). It may be used to test an expression
is given as the arguments to assert macro, it returns a zero and the program is terminated. In
case of correct expression, the program continues normally.
ctype.h :-the ctype.h header file contains a number of characters-testing and character-
conversion functions such as isdigit() which returns true,id the given argument is digit,
tolower(),tolower(),toupper(),etc.
erroer.h:-the error.h header files defines some symbolic constants. These constants are used in
error processing.
limits.h :- this file holds the information about the range of values that different data types
can assumes i.e it difines symbolic constants that tell the maximum and minimum values for a
char ,an int, a long, and other types.
math.h :-various mathematical functions such as pow(),sqrt(),abs(),etc. Are stored here.
Stdio.h :-it contains several function prototypes and all necessary declarations to performprogram input-output.
Stdlib.h :-several standard library functions are stored here.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
21/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 21
C pre-processor :- as the name implies pre-processor it is a program that processes our source
program before it is passed to the compiler. the C program is generally known as source code
.the preprocessor works on the source code and creates expanded source code. If the
source code is stored in the file first.c then the expanded source code gets stored in a file,
first.I . it is this expanded source code that is sent to the compiler for comilation.
The preprocessor offers several features called pre-processor features called pre-processor
directives each of these preprocessor directives or commands begins with a # symbol .the
directives can be placed anywhere in a programm but are most often placed at the beginning
of a program,before the first function defination. Various preprocessor directives are
a) Macro Expansions
b) File inclusion
c)Conditional compilation
d)Miscellaneous directives
Macro expansion :-
#include
#define CONS 25
main()
{
int i;
for(i=0;i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
22/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 22
this statement is called macro definition. Or simply called a 'macro'. During preprocessing
the pre-processor replaces every occurrence of CONS in the program with 25. i.e the
expanded source code will be the following for the above program.
#include
main()
{
int i;
for(i=1;i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
23/61
C - PROGARAMMING NOTES
ADITYA ENGINEERIN COLLEGES Page 23
a=AREA(r1);
printf(Area =%d,a);
a=AREA(r2);
printf(Area=%d,a);
}
In this program, wherever the preprocessor finds the phrase AREA(x),it expands it into the
statement(7.14*x*x), i.e the statement AREA(r1) in the program causes the variable r1 to be
substituted for x, as (3.14*r1*r1). While using macros with arguments be careful not to leave a
blank between the macro template and its argument while defining the macro for example ,in
the above program, AREA(x),if we give space between AREA and x like this #define
AREA(x)(3.14*x*x),then (x)(3.14*x*x),would become the macro definition's expression to
macro template AREA also macro expansion should be enclosed within a pair of parenthesis
.And we can have any number of lines ,with a '\',(back slash) present at the end of each
line,are enclosed in the macro expansion.
#define LINE {
for(i=0;i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
24/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 24
Expanded Code :
Eg # include
Main()
{
# ifndef MACRO
Block of stmts;
# else
Block of stmts;
# endif
Block of stmts;
}
In the above example, if MACRO has not been defined, then the block of code in between # if ndef
and #else will be executed or else the code in between #else and # end if will be executed, which
performs exactly the opposite action as considered with #if def and # else disectives.
# if and # elif directives:
The # if directive can be used to test whether an expression evalutes to a non zero value ornot. If the result of the expression is non-zero, then subsequent lines up to a # else or # elif or # end
if are complied, other wise they are slipped.
Eg: main()
{
# if TEST
8/3/2019 C-IV v Vi Vi Viii Unit Notes
25/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 25
Usage of # elif:
Main()
{
# if TEST
8/3/2019 C-IV v Vi Vi Viii Unit Notes
26/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 26
{
Print f (Main \n);
}
Void fun1 ()
{ print f (FUN\n);
}
Void fun2()
{
Print (FUN2\n);
}
O/p: FUN 1
MAIN
FUN2
# Pragma Warn: On compilation the compiler reports errors and warnings in the program, if any.
Warnings, offer the programmer a hint or suggestion that something may be wrong with a particular
piece of code. The # pragms warn directive tells the compler whether or not we want to suppress a
specific warning.
# pragma warn rvl/* return value */
# pragma warn par/* parameter not used */
# pragma warn rch/*unreachable code*/
Int f1()
{
Int a=5;
}
Void f2 (int x)
{
Print f ( Inside f2\n);
8/3/2019 C-IV v Vi Vi Viii Unit Notes
27/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 27
}
Int f3 ()
{
Int x=6;
Return x;
X++;
}
Main ()
{
F1 ();
F2 ();
F3 ();
}
In above Eg , f1() doesnt return value, x passed to f2 () is not used anywhere and in f3 () the stmt
X++Is never executed i. e , unreachable code, but the warnings: are suppressed using the # pragms
warn directive. If + is used in place of - at rvl etc, then these warnings would be flashed on
compilation.
Build Process: Steps involved in converting a (program) into an executable form is called as build
process.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
28/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 28
UNIT-VI
Pointers: pointers are another important feature of c language .A pointer enable us to access
a variable that is defined outside the function. pointers are more efficient in handling the
data tables. pointers reduce the length and complexity of a program. They increase the
execution speed. The use of a pointer array to character strings results in saving of data
storage space in memory.
Generally, computers use their memory for storing the instructions of a program, as
well as the values of the variables that are associated with its memory is a sequential
collection of storage cells known as bytes and each byte has a numbers called address
associated with it. The addresses are numbered consecutively, starting from zero and the lastaddress depends on memory size.
Whenever we declare a variable, the system allocates, some where in the memory,
an appropriate location to hold the value of the variable this location will have its own
address number
Ex: int X=100
This statement instruct the compiler, to find a location in memory and give it name
is x and assign value 100 in that location.
x ---variable
100---value
2004--- Address
Now, during execution of the program, the system always associates the name x with the
address 2004 we can access the value 100 either by using the name x or the address 2004
since these memory addresses are numbers, they can be assigned to some variable which can
be stored in memory like any other variable. such variables that hold memory addresses arecalled pointers therefore, a pointer is nothing but a variable that contains an address which
is a location of another variable in memory.
Ex: variable value address
x 2004100
2004
8/3/2019 C-IV v Vi Vi Viii Unit Notes
29/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 29
p 5008
Here p to another variable x the address of x can be accessed using the x operator,
and it is assigned to p as follows.
p=&x
Declaring and initializing pointers:
In C every variable must be declared for its type. since pointer variables contain addresses
that belong to a separate data type. They must be declared as pointer before we use them.
Syntax: data type *pt-name;
The asterisk (*) tells that the variable of type data type ,pointer variable of type data type.
Eg: int *p;
This stament declares p as a pointer variable that points to an integer data type. once a
pointer has been declared, it can be made to point to a variable using an assignment
statement such as
p=&x; which courses p point to x
This is known as pointer initialization.Before a pointer is initialized, it should not be used.
we must ensure that the pointer variables always point to the corresponding type of data.
Ex: float a,b;
int x,*p;
p=&a;
Then execution of above statement will result in erroroneous output due to data type
mismatch
Accessing value of variable through its pointer:
The value of the variable can be accessed using another unary operator *( asterisk), usually
known as the indirection operation.
int x,*p , y;
p=&x;
8/3/2019 C-IV v Vi Vi Viii Unit Notes
30/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 30
x=100;
y=*p;
The fourth line contains the indirection operator * when the operator * is placed before a
pointer variable in an expression, the pointer returns the value of the variable in anexpression, which the pointer value is the address.In this case, * p returns the value of the
variable x.
Eg: main ( )
{
int x , y;
int *ptr;
x=10; ptr=&x; y=*ptr;
printf (value of x is % d,x);
printf (value of x is % d,*&x);
printf (value of x is % d,*ptr);
printf (value of x is % d,y);
}
Output:
value of x is 10
value of x is 10
value of x is 10
value of x is 10
Pointer expressions:
Like other variables, pointer variables can be used in expressions. p1 and p2 are pointer
variables then they can be used in expressions as.
y= *p1 **p2;S
sum= sum + *p1;
8/3/2019 C-IV v Vi Vi Viii Unit Notes
31/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 31
*p2 = *p1 - 10;
Only when used with / operator, we should insert a space between / and * , otherwise it
will be treated as a comment tag (/*). so, *p1=*p3/ *p4; is valid.
Also, c allows to add integers of subtract integers from pointers.
Eg: p1+4, p2-2, & p1-p2 are all allowed.
we may also use shorthand operations with the pointers
p1++, --p2 etc. expressions such as p1>p2, p1=-p2 & p1!=p2 are all allowed. But we may
not use pointers division or multiplication.
Ex: p1*p2 (or) p1/p2 are not allowed.
pointer increments and scale factor:
An expression like p1++ will cause the pointer p1 to point to the next value of its type.
for eg, if p1 is an integer pointer with an initial value. say 2800, then after the operation
p1++, the value of p1 will be 2802, and not 2801. that is, when we increment a pointer, its
value is increased by the length of the data type that it points to this length is called the scale
factor.
points and arrays:
When an array is declared, the compiler allocates a base address and sufficient amount of
storage to contain all the elements of the array in contiguous memory location. The base
address is the location of the first element (index o) of the array.
int x[5] = {1,2,3,4,5}
elements x(0) x(1) x(2) x(3) x(4)
value
Address 1000 1002 1003 1006 1008
Base address
The name of the array, here x is defined as a constant pointer pointing to the first element,
x[0] and therefore the value of x is 1000, the location where x[0] us stored i,e,
x=&x [0] = 1000
1 2 3 4 5
8/3/2019 C-IV v Vi Vi Viii Unit Notes
32/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 32
If we declase P as an integer pointer, then we can make the pointer P to point to the array
x, by the following assignment,
p=x;
The above statement is equivalent to,
p=&x [0];
Now, we can access every value of x using P++ to move prom one element to another.
P = &x[0] (=1000)
P+1 = &x[1] (=1002)
P+2 = &x[2] (=1004)
P+3 = &x[3] (=1006)
P+4 = &x[4] (=1008)
We can access the value, *(p+1) is the value of x[1], *(p+4) is the value of x[4] & soon.
pointer and 2-dimensional arrays:
In the same way as 1-D array, the array name will be pointing to the starting element of
the array, in case of 2- dimensional array also.
int S[2] [3] = { {1,2,3}, {4,5,6}; p=s;
To access S[1] [2] using pointers, we can access using
*(*(p+1)+2)
To access S[0] [2] (*p+2)
The same pointer notation can be used for accessing elements in any multi-dimensional
array.
Pointer and character strings:
A string is an array of characters, terminated with a null character. like in one
dimensional arrays. we can use a pointer to access the individual characters in a string.
Ex: Char *name;
8/3/2019 C-IV v Vi Vi Viii Unit Notes
33/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 33
name = GOODDAY;
Above staments, will declare name as a pointer to character and assign to name the
constant character string GOODDAY
The same type of assignment would not work for character arrays,
ie., char name[20];
name = GOODDAY; is not valid.
Although you use name [20] =GOODDAY;
it will assign 20 bytes to name where only 8 bytes are used and remaining 12 bytes are
wasted.
But, when we use character pointer it allocated only the needed, memory for the above
example, when used with character pointer the memory allocated is as follows.
Array of pointers: int *arr [4]
The above statement declares an array of pointers, arr will be holding an array of 4 pointers.
where as the statement, int(*x) [3];
This statement declares x as a pointer to an array of 3 integer elements. An array of
pointers means, it would contain a number of address.
Pointers and functions:
As normal variables are passed as arguments to functions. pointer variables can also be
passed as arguments to function. when we are passing pointers to functions, it actually
means that we are passing address of variable as arguments, so that we can actually refer to
the original address of variables passed as arguments.
Generally these are two types of function calls,
1. Call by value.
2. Call by reference.
G O O D D A Y \0
G O O D D A Y \0
8/3/2019 C-IV v Vi Vi Viii Unit Notes
34/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 34
Call by value. In this method, the value of each of the actual argument in the calling
function is copied into corresponding formal arguments of the called function. with this
method, the charges made to the formal arguments in the called function have no effect on
the values of the actual arguments in the calling functions.
/* program illustrating call by value function call */
#include < studio .h>
void swap (int, int);
main( )
{
int a = 10,b = 20;
swap(a,b);
printf (a=%d b=%d, a,b);
}
void swap( int x, int y)
{
int temp=x;
x=y;
y= temp;
}
o/p: a=10 b=20
The values of a and b are unchanged even after swapping their contents in swap ( ) function.As changes made to formal arguments have no effect on the actual arguments.
/* program illustrating call by reference function call*/
#include
void swap ( int *,int *)
8/3/2019 C-IV v Vi Vi Viii Unit Notes
35/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 35
main( )
{
int a =10, b=20,; swap (&a,&b);
printf(a=%d b=%d,a,b);
}
void swap ( int*x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
o/p: a=20 b=10
This program manages to exchange the values of a and b using their addresses stored in x
and y.
Passing array elements to a function:
Array elements can be passed to a function by calling the function by value or by reference.
In the call by value, we pass values of array elements to the function, where as in the call by
reference, we pass addresses of array elements to the function.
Eg;/* call by value */
# include < stdo.h>
void disp (int);
main( )
{
int I;
int marks [ ] = { 50,60,70,80,};
8/3/2019 C-IV v Vi Vi Viii Unit Notes
36/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 36
for (i=0; I
8/3/2019 C-IV v Vi Vi Viii Unit Notes
37/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 37
Here we are passing addresses of individual elements to the function disp( ) and those are
stored in each iteration of for loop, in a pointer variable x and printing the same value using
x, in each call made to the function.
Passing an entire array to function:
We can pass an entire array as an argument to the function. while passing an entire array,we
should also pass the total no. of elements in the array as another argument, otherwise the
function would not know when to terminate. The address of zeroth element is to be passed
to pass the array as argument and it is same as passing the array name, as array name is a
constant pointer to the starting element of the array.
Void display (int*, int)
main ( )
{
int num[ ] = { 25,35,45,55,};
display(int *x, int n)
{
void display (int *x,int n)
{
int,i,
for(i=0; i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
38/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 38
Passing 2-D arrays to functions:
There are three ways in which we can pass 2D array to a function. They are illustrated in the
example below.
# include (int *q, int, int)
void display (int *q,int,int)
void show (int (*q)[4],int,int)
void print (int q[ ][4],int,int)
main( )
{
int a [3][4]={1,2,3,4,5,6,7,8,9,0,1,6},
display(a,3,4);
show (a,3,4);
print (a,3,4);
}
void display( int*q, int r, int e)
{
int i,j;
for(i=0; i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
39/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 39
{
int I,j; int*p;
for(i=0; i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
40/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 40
Here p is a pointer variable that points to an element that is again a pointer to character.
we say that p is a pointer to point a character.
Pointer to function: A function like a variable, has an address in the memory. therefore, it
is possible to declare a pointer to function, which can then be used as an argument in
another function, a pointer to a function is declared as
type(*fptr)( );
This tells the compiler that fptr is a pointer to a function which returns type value.
Ex: double (*P) ( ) mul( )
p= mul;
Above stmt, declare p as a pointer to a function, and mul ( ) is a function and then making
p to point to function mul to call the function mul, we may now use the pointer p withlist of paraneters. i.e
(*p)(x,y) is same as mul(x,y).
Dangling memory reference problem:
# include < string.h>
main( )
{
( char*) string( );
str = string [10];
printf(%s, str);
}
(char*) staring( );
char S1([10], S2 [10];
printf( enter the staring :\n);
scanf(%s,S1);
return S2;
}
Above program is not guaranteed to work properly. the problem is in string( ) function.
A local character array S2 is defined and that array returned to main ( )
8/3/2019 C-IV v Vi Vi Viii Unit Notes
41/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 41
since local variable of the function string ( ) are popped out from the stack when the control
is transferred back to calling function, so these arrays are lost when the function call is
returned to main thus str in main ( ) Will be assigned an invalid address on returning from
the string( ) function. This is the dangling reference or the dangling pointer problem.
Dynamic memory allocation functions:
C requires the number of elements in an array to be specified at compile time we may not
be able to do so always. If our initial judgment of size is wrong. may cause failure. of the
program a wastage of memory space. many languages permit a programme to specify an
arrays size at run time. the process of allocating memory at run time is known as dynamic
memory allocation. There are four library routines known as memory management
functions that can be used for allocation and freeing memory during program execution.
Memory allocation process:
The program instructions and global and static variables are stored in a region known as
permanent storage and local variables are stored in another area called stack. The memory
space that is located between these two regions is available for dynamic allocation duringexecutions of the program .this free memory region is called the heap. The size of the heap
keeps changing when program is executed due to creation and death of variables that are
local to functions and blocks. Therefore it is possible to encounter memory overflow
during dynamic memory allocation functions return a null pointer( when they fail to locate
enough memory requested).
Functions:
malloc( ): A block of memory may be allocated using the function malloc. It reserves a
block of memory of specified size and returns a pointer of type void. This means that we canassign it to any type of pointer.
Syntax: ptr = ( cast-type*) malloc (type-size);
ptr is a pointer of typecast type and returns a pointer of (cast-type) to an area of memory
with size bytesize.
Local variables
Free memory
Global variables
C programinstructions
Permanent
Storage area
Heap
8/3/2019 C-IV v Vi Vi Viii Unit Notes
42/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 42
Ex: X = (int *) malloc (10);
On successful execution of this stmt, a memory space of 10 bytes is reserved and the
address of first byte of the memory allocated is assigned to the pointer x of type of int.
1000
calloc( ): It is another function used for allocating multiple blocks of memory. i.e. used for
requesting memory space at run time for storing derived data type such as arrays and
structures. malloc( )allocated a single block only calloc allocates multiple blocks each of same
size and then sets all bytes to zero.
Syn: cptr = (cast-type*) calloc (n, element-size);
It allocates contiguous space for n blocks, each of size element size bytes. all bytes are
initialized to zero and a pointer to the first bytes of allocated region is returned . if there is
not enough space, a NULL is returned.
Eg: cptr = ( int*) calloc (4,8);
Allocates 4 blocks each of 8 bytes storage storing integer data type.
realloc( ): If we discover that previously allocated memory allocation functions, is not
sufficient and use need additional space for more elements. in this case, we can change the
size, either increase of decrease, of the block allocated using realloc( ). this process is called
the reallocation of memory.
Syn: ptr = realloc (ptr,newsize);
Eg: ptr = malloc(ptr,8);
A bove stmt, reallocates ptr with 8 bytes of size.
free( ): With the dynamic run-time allocation, it is our responsibility to release the space
when it is not required. when we no longer need the data we stored in a block of memory
and we do not intend to use the block for storing any other information. we may release
that block of memory for future use, using the free function,
free (ptr),
1000
X
Address of
First byte
8/3/2019 C-IV v Vi Vi Viii Unit Notes
43/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 43
ptr is a pointer to a memory block which has already been created by malloc or calloc. use
of an invalid pointer in the call may create problems and causes system crash.
One solution to come out of dangling reference problem is to use dynamic memory
allocation functions. In the previous example of dangling reference problem program can be
solved using malloc as follow.
main ( )
{
char * string ( );
char str[10];
str = string ( );
printf (%s, str);
}
char s1[10];
{
char S1[10];
S2 = (char*) malloc(10);
printf (enter string:\n);
scanf (%s.s2);
strcpy(s2,s1);
return S2;
}
This program works perfectly, because S2 is allocated memory using malloc, it resides inmemory even if the control is transferred back to the main.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
44/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 44
UNIT VII
Structure: Arrays can be used to represent a group of data items that belong to the sametype. If we want to represent a collection of data items of different types using a singlename, then we cannot use an array. C supports a constructed data type known as structure,
which is a method for packing data of different types.
A structure definition creates a format that may be used to declare structure variables.
we can declare a structure using the keyword struct.
struct book
{
char title [20];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of three fields title, process*price.
These fields are called structure elements of members. each member may belong to same of
different data type book is the name of the structure and is called the structure tag.The tag
name may be used subsequently to declare. variable that have the tags structure.
In the above example, we have not declared any structure variables.
General format of structure is,
structure struct tag
{
data type member;
data type member;
};
We can declase structure variables as follows.
Atruct struct tag var1, var2,
8/3/2019 C-IV v Vi Vi Viii Unit Notes
45/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 45
Where var1, var2 are structure variable of sturct-tag type. for previous
Eg: struct book b1,b2;b1 b1,b2 are structure variables of type struct book.
We can combine the declaration of structure by and structure variables in one
statement.
Struct book
{
char titile[10];
float price;
} b1,b2;
Other way of declaring the structure is
struct
{
char title [10];
int pages;
float price;
} b1,b2;
The above structure is not having tag-name, so that we cant declare any more, structure
variables can also be initialized where they are declared.
struct book
{
char title[10];
int pages;
that price;
}
Struct book b1 = { chemistry,100,285.25};
8/3/2019 C-IV v Vi Vi Viii Unit Notes
46/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 46
Struct book b2 = { physics,150,482.50};
Struct book b3 = { 0 };
When0 is initialized to a structure variable, then all of the structure elements are
initialized to 0 for that particular variable.
Accessing structure elements: Structure use a special operator, known as. dot operator to
access the structure elements for.
Eg: pages can be referred to using
b1. Pages;
we can assign values to structure elements individually also using dot operator like
b1 pages=200
Structure elements are stored in contiguous memory locations for each structure variable
declared for a structure.
Eg: /* program using structure */ struct book
main( ) {
{ char title [10]
struct book b1; int pages;
printf(enter values for structure elements:\n); };
scanf (%d,&b1.pages);
scanf (%s,&b1.pages);
scanf (%f,&b1.pages);
printf(%s %d %f,b1.pages,b1.price);
Array of structures:
If we want to declare a large number of structure variables, then simply we may use
array of structures.
Struct book
{
8/3/2019 C-IV v Vi Vi Viii Unit Notes
47/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 47
char titile [10];
int pages;
float price;
};
main ( )
{
struct book b[10];
int i;
for( i=0;i
8/3/2019 C-IV v Vi Vi Viii Unit Notes
48/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 48
main( )
{
struct emp e;
scanf(%s, %s, %s, %d, e.name,
e.a.dno, e.a city,e.a pin);
printf (%s, %s, %s, %d, e.name,
e.a.dno, e.a city,e.a pin);
}
Other Features of structures: We can copy each structure element of one structure variable
to other structure variable in the same way to copy all the values of a structure elements of a
structure variable o another, we can use assignment operator= as it is used for normal
variables.
Eg: b1.pages = b2.pages /*copies pages only*/
b1=b2 /*assign values of structure element fof b2 to all elements of b1*/
Structure and functions: Like an ordinary variable, a structure variable can also be passed to
a function. We may pass either individual structure elements of the entire structure variable
at one go.
/* passing individual elements to functions*/
void display (char*, int,float)
main( )
{
struct book
{
char title[10];
float price;
} b1 = {physics,100,285.50};
8/3/2019 C-IV v Vi Vi Viii Unit Notes
49/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 49
display (b1.title,b1.pages,b1.price);
void display (char *s, int p, float r)
{
printf (%s %d %f,S,p,r);
}
o/p: physics 100 285.50.
/* program to pass the whole structure variable as argument to function */
struct book
{
char title[10];
int pages;
float pages;
void display(struct book);
main ( )
{
struct book b1 = {English,150,180,20};
display(b1);
}
void display (struct book b)
{
printf(%s, %d, %f, b. title, b. pages, b. price);
}
o/p: English 150 180 20
pointers to structures: As we have a pointer pointing to an int, or achar, similarly we
can have a pointer pointing to a struct data type. such pointers are known as structure
8/3/2019 C-IV v Vi Vi Viii Unit Notes
50/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 50
pointers. when a pointer is used to point a structure, we can access the structure elements
using a special operator known as arrow operator.
Eg: Struct book
{
char title[10];
int pages;
float prices;
};
main ( )
{
struct book b1 = {English,120,245.25};
struct book *ptr
ptr = &b1;
printf(%s %d %f, b1.titile,b1.pages,b1.price);
printf (%s %d %f, ptr title, ptr pages, ptr price);
}
o/p: English 120 245 .25
English 120 245.25
Union : Unions are a concept borrowed from structures and therefore follow the same
syntax as structures. the major difference between them is in terms of storage. in structures,
each members has its own storages location, where as all the members has its own storages
location It means that, 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 type in the union. An union can be declared using the keyword
union as follows:
Union items;
{
8/3/2019 C-IV v Vi Vi Viii Unit Notes
51/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 51
int m;
float x;
char c;
}u1;
This declares a variable u1 of type union item. it contains there members, but we can use
only one of them at a time, as only one location is allocated for a union variables.
typedef: C supports a feature known as type definition, that allows uses to define an
identifier that would represent an existing data type.
typedef type identifier;
wheretype refers to existing datatype and identifies refers to the new name given to thedata type may belong to any class of type. including the uses-defined ones.
Eg: typedef int run;
Now we can declare variable of int data type with the new name given as follows.
num x,y,z;
x.y,z are declared as int variables One important note is that the new type is new only in
name, but not the data type.typedef cannot create a new type.
Eg: typedef struct book sbook;
struct book1, sbook2; is equivalent to sbook sbook1, sbook2.
enum: Another user defined data type is enumerated data type. It is defined as follows.
1003100210011000U1
c
m
X
8/3/2019 C-IV v Vi Vi Viii Unit Notes
52/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 52
enum identifier is a user defined enumerated data type which can be
used to declare variables that can have one of the values enclosed within the braces (known
as enumeration constants). After this definition, we can declare variables to be of this new
type as below:
enum identifier v1, v2 ,.vn;
The enumerated variables v1, v2 ,.vn; .. values the assignments of the following
type are valid.
v1 = value1;
v2 = value3;
Eg: enum day {Mon,Tue,Wed.,Sun};
enum day d1,d2;
d1 = mon;
d2 = wed;
The compiler automatically assigns integer digits beginning with 0 to all the enumeration
constants. That is the enumeration constant value 1 is assigned 0, value2 is assigned 1& 80 on
These automatic assignments can be overridden by assigning values explicitly to the
enumeration constants.
enum day {Mon = 1.Tue,..sun};
The constant mon is assigned 1, the remaining constants are assign need values that increase
successively by 1.
Bit fields: If in a program, a variable is to take only two values 1 and 0, we need just a single
bit to store it. similarly, if a variable is to take values from 0 to 3, then two bits are sufficient
to store these values. But up to now even if we know the bits to be stored in a variables,we
are declaring them as integers or short integers, resulting in wastage of memory. instead, we
can use bit fields to store several values in a single integer.
Eg: struct emp
{
8/3/2019 C-IV v Vi Vi Viii Unit Notes
53/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 53
int x:1;
int y:2;
int z:3;
};
The colon in the above declaration tells the computer that we are talking about bit fields
and the number after it tells how many bits to allot for the field. Here x is allocated 1- bit of
storage, y- 2- bits and z with 3-bits of storage. Hence saving the memory and making use of
Available memory in an efficient way.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
54/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 54
UNIT-VIIIConcept of a file: Until now, we have been using the functions such as scanf and prinf to
read and write data. These are console oriented I/0 functions which always use the terminal
(keyboard and screen) as the target place. this works fine as long as the data is small. when
they involve with large volumes of data, it becomes ambersome and time consuming to
handle large volumes of data through terminals and the entire data is lost when either the
program is terminated or the computer is turned off.
It is therefore necessary, to have a more flexible approach where data
can be stored on the disks and read whenever necessary, without destroying data. This
method employs the concept of files to store data. A file is a place on the disk where a
group of related data is stored. C supports a number of functions that have the ability to
perform basic file operations, which include .
(i) naming a file
(ii) opening a file
(iii) reading data from a file
(iv) Writing data to a file and
(v) Closing a file
Defining a file: If we want to store data in a file in the secondary memory, we must specify
certain things about the file, to operating systems they include.
1. Filename
2. Data structure
3. Purpose.
Filename is a string of characters that make up a valid filename for the operating system. it
may contain two parts, a primary name and an optional period with extension.
ABC. txt, input.txt, prg. c, store.mp3 etc,are some valid filenames.
Data structure of a file is defined as file in the library of standard I/0 function
definitions. Therefore all files should be declared as type FILE, before they are used. FILE is a
defined data type.
If we want to perform any operation on the file. First of all, we must open the file.When we are going to access a file that is stored on the disk. that file will be copied into the
buffer, a temporary storage area in memory and the program or the application will be now
accessing the file from the buffer, then on wards.
following is the general format for declaring and opening a file.
FILE *fp;
fp = fopen(filename, mode);
8/3/2019 C-IV v Vi Vi Viii Unit Notes
55/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 55
The first statement declares the variable fp as a pointer variable to the data type FILE. The
second statement opens the file named filename and assign as identifier to the FILE type
pointer fp. This pointer which contains all the information about the file is subsequently used
as a communication link between the system and the program.
The second statement also specifies the purpose of opening this file. the mode does thisjob.mode can be any one of the following.
r open the file for reading only.
w open the file for writing only.
a open the file for appending ( or adding) data to it both the filename and mode are
spcicified as strings. they should be enclosed with in double quotation marks.
when trying to open a file, one of the following things may happen.
1. when the mode is writhing, a file with the specified name is created if the file does not
exist. the contents are deleted if the file already exists.2. When the mode is appending, the file is opened with the current contents safe.A file
with the specified name is created, if the file does not exist.
3. If the purpose is reading and if it exists, then the file is opened with the current contents
safe, otherwise an error occurs.
FILE *p1, *p2;
p1 = fopen(input, r)
p1 = fopen(output, w)
The file, input is opened for reading, where as the file output is opened for writing . its
contents are deleted if the exists and the file is opened as a new file.
Some additional modes are included in the recent compilers. they are .
r+: the existing file is opened to the beginning for reading and writing.
w+: Same as writing w, except both for reading and writing.
a+: Same as a except both for reading & writing.
Closing file: A file must be closed as soon as all operations on it have been completed. this
ensures that all outstanding information associated with file is flushed out from the buffers
and all links to the file are broken. In case, there is a limit to the number of files that can be
kept open simultaneously, closing of unwanted files might help open the required files.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
56/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 56
another instance where we have to close a file is when we want to reopen the same file in
different mode. its format is
fclose (file-pointer);
This would close the file associated with the FILE pointer file-pointer.
Eg: fclose (fpl);
Input and output operations on files:
fgetc and fputc functions: The simplest i/0 functions related to files are fgetc. these are
analogous to getchar and putchar functions and handle and character at a time. assume that
a file is opened with mode w and file pointer is fpl. Then the stmt,
fput(c,fpl);
Writes the character contained in character variable c to the file associated with FILE
pointer fp. similarly fgetc is used to read a character from a file, that has been opened in the
read mode.
c=fgetc (fpl);
This stmt would read a character from file whose file pointer is fp1.
At the end of every file, the compiler keeps special character with ASCII value 26 this
generally ctrl+D or ctrl + z. it marks the end of file and is generally read as EOF by fgetc
function. The file pointer moves by one character position for every operation of fgetc and
fputc, The fgetc will return an end of file. marker EOF, when end of the file has been
reached therefore, the reading should be terminated when EOF is encountered.
The same functions as fgetc and fputc are perforoned by fgets and fputs, but they
perform operations on strings instead of characters.
The fprintf and fscanf functions:
The fprintf and fscanf perform I/0 operator that are identical to the familiar printf and
scanf functions, except that they work on files.
syn: fprintf (fp, control string, list)
fprintf (fp, control string, list)
the first argument to these function is a file pointer which specifies the file to be used, where
fp is a file pointer associated with a file that has been opened for writing or reading and the
8/3/2019 C-IV v Vi Vi Viii Unit Notes
57/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 57
control string contains out put or input specifications for the items in the list. the list may
include variables, constants and strings.
Eg:- fprintf (fp,%d %d ,x,y);
fscanf (fp, %d %d, &x, &y);
when fscanf is used for reading values from a file, it returns the value EOF, when end of file
is reached. generally, these are used for handling a group of mined data simultaneously.
Error handling during I/O operations:
It is possible that an error may occur during I/O operations on a file Typical error
situations include
(1) Trying to read beyond the end of file mark.
(2) Trying to use a file that has not been opened.(3) Trying to perform an operation on a file, when the file is opened for another type of
operation
(4) Operating a file with an invalid filename.
for detecting such errors, we have two standard I/o library function, feof and ferror that can
help us to detect I/O errors in the files.
the feof function can be used to test for an end of file condition it takes a file ponter
as its only argument and returns a non-zero integer value if al the data from the specified file
has been read and returns zero otherwise
if (feof(fp))printf (end of data);
This displays message if it reaches end of file.
the ferror function reports the status of the file indicated. it also takes a file pointes as
its argument & returns a non-zero integer if an error has been detected upto that point,
during processing or else returns zero.
Eg: if(ferror(fp)!=o)
printf (Error);
the statement will display error if the reading is not successful.
if the file cannot be opened, it returns a null pointer. this can be used to test whether
a file has been opened or not.
Eg: if (fp==NULL)
printf (file not opened);
Random Access to files:
8/3/2019 C-IV v Vi Vi Viii Unit Notes
58/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 58
When we are interested in accessing only a particular part of a file and not in reading
other parts, this can be achieved with the help of the functions fseek, ftell and the other is
rewind function, available In I/O library.
ftell():
n= ftell (fp);here n would give the relative offset of the current position this means that n bytes have
already been read or written this is useful in saving the current position of a file.
rewind(): It takes a file pointer and resets the position to the start of the file.
Eg: rewind (fp);
This statement sets the file points to the beginning of the file.
fseek(): fseek ( fileptr, offset, position);
Fileptr is a pointer to the file concerned, offset is a number or variable of type long and
position is an integer number the offset specifies the number of positions to be moved from
the location specified by position.The position can take one of the following three values.
Value meaning
0 - Beginning of file
1 - Current position
2 - End of file
The offset may be positive, meaning move forward, negative meaning move
backward when the operation is successful fseek returns a Zero, otherwise returns -1.
Eg: fseek (fp, ol,0) - Go to the beginning
fseek ( fp, ol,2) - Go to the end of the file, part the last character of
of the file
fseek(fp, m, o) - Move to (m+1) byte in file
fseek (fp,-m,1) - Move backward by m bytes from current
Position.
fseek (fp,-m,2) - Move backward by m bytes from the end.Eg: /* Program to copy one file to another */
main ()
{
File * fp1, * fp2;
8/3/2019 C-IV v Vi Vi Viii Unit Notes
59/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 59
char ch;
fp1 = fopen (ABC.txt, r);
If (fp1==NULL)
{
printf (file dosent exidt);
exit (0);
}
fp2=fopen (xyz.txt,w);
If (fp2== NULL)
{
printf (file couldnt be created);
exit(0);
}
while ((ch = fgetc(fp1)!=EOF)
fputc (ch, fp2);
fclose (fp1);
fclose (fp2);
}
Command line arguments:
It is a parameter supplied to a program when the program is invoked. This parameter may
represent a filename the program should process for
Eg: if we want to execute a program to copy the contents of a file named ABC to another
one named XYZ, then we may use a command line like.
C :\> PROG ABC XYZ
Where PROG is the filename where the executable code of the program is stored. Thiseliminates the need for the program to request the user to enter the filename during
execution these are actually stored in the parameter list specified with the main
function.
8/3/2019 C-IV v Vi Vi Viii Unit Notes
60/61
C - PROGARAMMING NOTES
ADITYA ENGINEERING COLLEGES Page 60
In fact, main can take two arguments called argc and argv and the information contained in
the command line is passed on to the program through these arguments, when main is called
up by the system.
main ( int argc, char * argv [ ])
The variable argc is an argument counters that counts the number of arguments on the
command line. The argv is an array of character pointers that point to the command line
arguments. The size of the aray will be equal the value of argc in our previous example for
command line arguments, argc is three and argv is an array of three pointers to strings as
shown below:
Argv [0] prog
Argc [1] ABC
Argv [2] XYZ
In order to access these arguments, we must declare the main function and its parameters as
shown above.
Text files and Binary files:
A text file contains only textual information like alphabets, digits and special symbols.
In actuality the ASCII codes of these characters are stored in text files. But a binary file is a
collection of bytes. This collection might be a compiled version of a c program of music data
or video or graphic data stored in a graphic file. The only change we have to make in
reading from or writing to the binary file is or open the file in mode as rb for reading of
wb for writing.
Eg: fp = fopen (first-exe, rb);
8/3/2019 C-IV v Vi Vi Viii Unit Notes
61/61
C - PROGARAMMING NOTES
This opens the file for reading and b specifies that it is a binary file.
All operations can be performed on binary file, but when comes to storage of new
line character in text-file involves a overhead of printing \r\n in write mode and converting
that back to \n\o in read mode, but in a binary file, these conversions will not take place.
The second difference between text and binary files is in the way the end of file is
detected. In text mode, a special character, whose ASCII value is 26, is inserted after the last
character in the file to mark the end of file. If this character is detected at any point in text
file, the read function would return EOF signal to the program,but there is no such special
character present in the binary mode files to mark the end of the file. the binary file keep
track of the end of the file from the number of characters present in the directory entry of
the file.
If a file stores numbers in binary mode, it is important that binary mode only be use
for reading the numbers back, since one of the number we store might well be the number
26. If this number is detected while we are reading the file opened in text mode, reading
would be prematurely terminated at that point.
The only function available for storing numbers in a disk file is the fprintf ( ) function.
When numbers are stored on the disk, they are stored as strings of characters. Thus 1234,
even though it occupies two bytes in memory, when transferred to the disk using fprintf ( ),
would occupy 4 bytes, one byte per character. Likewise, 12334.56 would occupy 7 bytes on
disk. Hence if large amount of numerical data is to be stored in a disk file, using text mode
may turn out to be inefficient. The solution is to open the file in binary mode and use the
top related