c Programing 2
c Programing 2
3. The formal arguments in the function header must be prefixed by the indirec
tion operatior.
.
4. In the prototype, the arguments must be prefixed by the symbol *.
5. To access the value of an actual argument in the called function, we must use
the corresponding formal argument prefixed with the indirection operator
int a, b, C;
Scanf("d %d %d", &a, &b, c);
printf("%f \n", ratio(a,b,c));
if(p != q)
return (1);
else
return (0);
in ANSI C
288 Programming
9.6 RECURSION
process of chaining occurs. Recur.
a
When called funetion in turn calls another function A very simple
a
calls itself example
sion is a special case af this process, where a function
recursion is presented below:
Shote main( )
of recursion\n")
an example
printf("This is
main( );
like this:
output something
When executed, this program will produce an
This is an example of recursion
This is an example of recursion
This is an example of recursion
This is an ex
execution will continue indefinitely.
Execution terminated abruptly:otherwise the
is
is the evaluation of factorials
of a given number. The
Another useful example of recursion mulipications as shown below:
factorial of a number
n is expressed as a series of repetitive
factorial of n n(n-1)\(n-2)....1. =
For example,
factorial of 4 = 4X3×2x1= 24
factorial (int n)
int fact;
if (n==1)wollkt a
return(1);
else
fact = n*factorial (n-1):;
return(fact);
9.19
THE SCOPE, VISIBILITY AND
LIFETIME OF VARIABLES 1om Sm
iahlesin C difter in behaviour from
Sho<09 lone
those in most other languages. For example, in
variable a
BASIC program, a retains its value
in C. It all depends on the 'storage'class a
throughout the programn. It is not always the
variable may assume.
Io C not only do all variables have a data type,thev also
have a storage class. The follow
variable storage classes are most relevant
to functions:
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.
We shall briefly discuss the scope, visibility and longevity of each of the above class of
variables. The scope of variable determines over what region of the program a variable is
actually available for use ('active'). Longevity refers to the period during which a variable
retains a given value during execution of a program ('alive').So longevity has a direet effect
on the utility of a given variable. The visibility refers
to the accessibility of a variable from
the memory.
tion, as internal (local) or external (global). Internalvariables are those which are declared
outside of any function.
within aparticular function, while external variables are declared
lt is very important to understand
the concept of storage classes and their utility in order
Automatic Variables2m
which they areto be utilized. They are
inside a function in
Automatic variables are declared
called and destroyed automnatically
when the function is exited.
reated when the function is
private (or local) to the Fune.
Automatic variables are therefore
e the name automatie. variables are also re
thev are declared. Because of this property, autonmatie
In which
ferred to
as local internal
or variables.
class specification is, by default, an
A function without storage
variable declared inside a
of the variable number in the example
automatic the storage class
variable. For instance,
Delow is
automatic.
10
Stru tures and
|Unions
0.1 INTRODUCTION
02DEFINING A STRUCTURE
Unlike
declare
arrays(structures must be defined first for their format that may be used later
structure variables Let us use an example to illustrate the process of
structur
definition and the creation of structure variables. Consider a book database
consisting
10
structures and
Unions
INTRODUCTION
10.1
seen that
arrays can be
We bave
such as int or float. used to represent a group data itemsthat belong to the
of
char title[20];
char author [15] ;
int pages;
float price;
6sthe variable
bookl.price )
representing the price of bookl and can be treated like any other ordinary
eariable. Here is how we would assign values to the members
of bookl:
strcpy (bookl.title, "BASIC"):
strcpy (bookl.author, "Bal agurus amy"):
bookl.pages = 250;
bookl.price = 120.50;
We can also use scanf to give the values through the keyboard.
scanf ("%s\n",book1.title);
scanf("%d\n",
&bookl.pages):)
are valid input statements.
Structuresand Unions H327
int subjectl;E0S
int subject2;
int subject3;
main()
= 71; Sinc
student [2].subject3 any other array,
been with elemen
would have individual
just as it to access
array is declared methods element of stude
the array-accessing each
Note that use theusual
is an array, we
to access members. Remember,
student amulti-dimensior
then the member operator three members. in the same way as
and variable
with
memory
is a structure inside the
array is stored in Fig. 10.3.
structures looks as shown
An array of actually calculate
The array student program to
a
them as a pat of
above, write
array.
Structures and
Unions
ARRAYS OF 327
T0.8
We use
structures
to
STRUCTURES
describe the
XSn
zing the marks obtained byformat
a
of a
number
naly of
name and marks obtained class of related I variables, For example, in
student
In such in various Subswe miusea template to descrihbe
variables
structure cases, we may al the stodents as
Tnd then declare
rejpresenting ga declare
the array structure an array ot structures, each element of
:
variable. For
example:
e47struct class
array r called student [100]
defines an student,
struet that consists of 100
ofthe type class. Consider
the elementasEnch element is defined to be
following
declaration:
struct marks
int
subjectl;
int subject2;
int subject3:
main()
studentisan array, we use the usual array-accessing methodsto access individual elements
andthen the member operator to access members. Remember, each element of student
a
array is structure variable with three members.
An array ofstructures is stored inside the memory in the same way as amulti-dimensional
array. The array student actually looks as shown in Fig. 10.3.
Fig. 10.4 Arrays of
structures: Illustration structure variables
of subscripted
10.9
ARRAYs WITHIN STRUCTURES X"Sm
the use
of arrays as structure members. We have already used arrays
of charac-
C permits arrays
a structure. Similarly{ we
inside can use single-dimensional or multi-dimensional
ters
int or float. For example, the following structure declaration is valíid:
of type
struct marks
int number;
float subject [3]:
} student[2];
within a
structure means nesting
Structures of
us
consider thefollowing structures. Nesting of structures is permit-
C. Let
ted in structure definedto store
information about the salary
of employees.
struct sal ary
char name;
char department;
int basic pay;
int dearness àllowance:
int house rent allowance;
int city allowance;
employee;
This structure defines name, department, basic pay and three kinds of allowances. We can
as
gTOup all the items related to allowance together and declare them under a substructure
shown below:
struct salary
char name;
char department;
struct
int dearness;
int house rent;
int city;
all owance;
employee;
which itself is a structure
contains a member named allowance, dearness,
The salary structure structure namely
The members contained in the inner
with three members.
can be referred to as:
house_rent, and city
employee.allowance.dearness
rent
employee.allowance.house
employee.allowance.city all the con
accessed by chaining
a nested structure can be
An inner-most member mnember using dot op
in
(from outer-most to inner-most) with the
cernedstructure variables
erator.The following are invalid: is missing)
(actual member
employee.allowance is missing)
(inner structure variable
employee.house rent is
following form of declaration
can have more than one variable. The
An inner structure
legal:
Structures and Unions |333
of
passing the entire structureas a parameter.
as an argu
3. The third approach employs a concept called pointers topass the structurecalled func
is passed to the
ment. In this case, the address location of the structure
the entire structure and work on it. This is
tion. The function can access
indirectly
more eficient as
are passed to function. This method
is
similar to the way arrays
compared to the second one. third approach using
in detail the second method, while the
In this section, we diséuss dealt in detail.
next chapter, where pointers are
pointers is discussed in the function is:
of a structure to the called
The general formnat of sending a copy
Synton
function name (structure_variable name);
formn:
The called function takes the following
(struct type st name)
data type function name
return (expression) :
The following points are important to note;
for its type, appropriate to the data type it is
atd 11
Pointers
vatable hen (eyam) s
knGon
11.1
INTRODUCTION
Apointer is a derived
data type in C
available in It is
C,(Pointers contain built
from one the fundamental data types
of
addresses are the locations memory
in the addresses as their yalue. Since these
memory
are stored,(pointers
can be used tocomputer memory where program instructions and
Pointers are access and
data
undoubtedly one manipulate data stored in the
has added power and the of
most distinct memory.)
lexibility to the and exciting features of C language. It
difficult to language, Although they
understand for a beginner, appear little confusing
are mastered. they are a powerful and
tool and handy
to use once
Pointers are used they
frequentlyin C, as they offer
They include: a number of benefits to
theprogrammerS.
1. Pointers are
more efficient in
2. Pointers can be used handling arrays and
to return multiple values data tables.
ments. from functionvia a
argu
function
3. Pointers permit references
to functions and
as arguments to other thereby facilitating passing of
functions. functions
4. The use pointer arrays to
of
character strings results in
memory. saving of data storagespace in
5. Pointers allowto support dynamic
C
memory management.
6. Pointers provide an eficient tool for manipulating
dynamic data structures such as
structures, linked lists,queues, stacks and
trees.
7. Pointers reduce length and complexity of
programs.
8. They increase the execution speed and thus
reduce theprogram execution time.
Of course, the real power of C lies in the proper use of
pointers.In this chapter, we will
examine the pointers in detail and illustrate how to use them
in program development.
Chapter 13 examines the use of pointers for creating and managing linked lists.
The computer's memory is a sequential collection of storage cells as shown in Fig. 11.1. Each
cell, commonly known as a byte, has a number called address associated with it. Typicaly
11.3 ACCESSING THE ADDRESS OF A VARIABLE
The actual location of a variable in the memory is system dependent and therefore
address of a variable is not known to us immediately. How can we then determin
address of a variable? This can be done with the help of the operator &
available in
have already seen the use of this address operator in the seanf function.The opera
immediately preceding a variable returns the address of the variable associated with
example, the statement
p = &quantity;
the address 5000 (the location of quantity) to the variable p. The & op
(wouid assign
can be remembered as 'address of".
The fo
(The operator can be used only with a simple variable or an array element)
&
are illegal use of address operator:
1. &125 (pointing at constants).
2. int x[10];
&x (pointing at array names).
3. &(x+y) (pointing at expressions).
as
If x is an array, then expressions such
and &xi+3
(&
of Oth and (i+3)th elements of x.
the addresses
are valid and represent
along with
the address of a variable
it
Program
main()
char
int
Fig 11.4
Accessing the address of a
variabie
DECLARING POINTER
VARIABLES
In C.fevery variable must be
declared for its type.
that belong to a separate data addresses
declaresthevariable p
int "p:)* integer pointer */oPTn
as a pointer variable that points to an integer
that the type int refers to the data type
+
p and x.Since the memory locations
have not been assignedany values, these
locationsmay
contain some unknown values in them and therefore
they point to unknown locations as
shown:
Ha 2ano mE rmc A
peun te uaie adcde
12
File
in Management C
12.1 INTRODUCTION
Until now we have been
using the
These are console oriented /O functions such ass scanf and printf to read and write data.
sereen) asthe target functions, which
place. This works always use the terminal (keyboard and
fine as long as
life problems involve large the data is small. However, many real-
volumes of data and in
onerations pose two major problems. such situations, the console oriented I/O
naming a file,
opening a file,
• reading data from a file,
writing data to a file, and
closing a file.
There are two distinct ways to perform file operations in C. The first one is known as the
low-level IO
and uses UNIX system calls. The second method is referred to as the high-level
IO operation and usesfunctions in C's standard I/O library. We
shall discuss in this chapter,
the important file handling functions that are available in the C library. They are listed in
Table 12.1.
390 Programming in ANSIC
fscant)
getw)
Rendsa set
*Readsan integer
of datavalues from a file.
from a file.
M sli
to a ile.
Writes an integer
putw)
to a desired point
in the file.
fseek() "Sets the position
the current position in the file (in terqs of bytes from the start
ftell() Gives
*
ofthe file.
*Sets the position to the beginning
Om rewind(0
compilers.You
There are many other functions, Not all of them are supported by all shoula
.
If we want to store data in a file in the secondary memory, we must specify certain things
It
may contain two parts, a primary name and an optionalperiod with the extension. Exam
ples:
Input.data
store
PROG.C
Student.c
Text.out
Data structureof a file is defined as FILE in the library of standard I/O function delini
tions. Therefore, all files should be declared as type FILE before they are used. FILE s a
FILE *fp;
tp fopen ("filename", "mode"):)
The first statement declares the variable fp as a "pointer to the data type FILE". AS
stated earlier, FILE isa structure that is defined in the I/O library. The second stalement
File Management in C 391
the fle named filename and assigns an fp. This
opens identifier to the FILE type pointer
which contains all the information as a commu-
pointer, about the file is subsequently used
link between the system and
nication the program.
The second statement also
Specities the purpose of opening this file. The mode
does this
s
can be one ofthe
job. Mode following:
open the file for reading only.
W open the file for writing only.
open the file for appending (or adding)data to it.
Note that both the filename and mode are specified as strings.They should be enelosed in
double quotation marks.
When trying to open a file, one of the following things may happen:
1. When the mode is writing, a fle with the specifed name is created if the file does not
exist. The contents are deleted, if the file
already exists.
2. When the purpose is'appending,the file is opened with the current contents Sate.
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 fle is opened with the current
contents safe otherwise an error occurs.
The file data is opened for reading and results is opened for writing. In case, the results
fle already exists, its contents are deleted and the file is opened as a new file. If data file
does not exist, an error will occur.
Many recent compilers include additional modes of operation. They include:
r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.
We can open and use a number of files at a time. This number however depends on the
Systen we use.
all outstanding information associated with the file is flushed out from the buffers and all
links to the fle are broken. It also prevents any accidental misuse of the file. 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. Another instance where we have to close a fle is when we
want to reopen the same file in a different mode. "The 1/0 library supports a function to do
this for us. It takes the following form:
P)
Sclose(tile,pointen):)
C
392 Programming in ANSI
fclose(p1):
fclose(p2) ;
them after all operations on them are completed
This program opens two files and closes
Once a file is closed, its file pointer can be reused for another
file.
getc (fp2); )
would read a character from the file whose file pointer is fp2.
The file pointer moves by one character position for every operation ofgete or pute. The
gete will return an end-of-file marker EOF, when end of the file has been reached. There
fore, the reading should be terminated when EOF is encountered.
Example 12.1 Write a program to read data from the keybOard, write it to a file called
INPUT, again read the same data from the INPUT file, and
display on it
the screen.
A program and the related input and output data are shown in Fig.12.1.
data via the keyboard and the program writes
enter the inputWe
it, character by character, to the
The end of the data is indicated by file INPUT.
entering an EOF
character, which is control-Z in the
reference system. (This may be
control-D in other systems.) The file
signal. INPUT is closed at this
The getw and putw Functions
gete and pute
functions. They are similar to the
The getw and putw are integer-oriented These functions would be usef
read and write integer values.
functions and are used to
data. The general forms of getw
and putw are:
when we deal with only integer
getw(fp):
Example 12.2 illustrates the use of putw and getw functions.
putw(number, fl);
file is closed. The n
Notice that when we type -1, the reading is terminated and the
step is to open all the three files, DATA for reading, ODID
and EVEN for writing. T
contents of DATA file are read, integer by integer, by the function getw(fl) and written
ODD or EVEN file after an appropriate test. Note that the statement
(number= getw(r1)) != EOF
reads a value, assigns the same to number, and then tests for the end-of-file mark.
Finally, the program displays the contents ofODD and EVEN files. It is important to r
that thefles ODDand EVEN opened for writing are closed before they are reopened
reading.
he fprinurfand fseanfFunctions
So far, wve have seen functions, that can handle only one character or integer at a time, M..
compilers support two other functions, namely fprintf and fscanf, that can handle a re
of mixed data simultaneously.
The functions fprintf and fseanf perform I/0 operations that areidentical to the famil.
prìntf and scanf unctions, except ocourse thatthey work on files.The first argumeni
these funetions is a file pointer which specifies the file tobe used. The general form offprint
where fp is a file pointer associated witha file that has been opened for writing. The contral
string containsoutput specifications for the items in the list. The list may include variables
constantsand strings.Example:
fprintf(fl, "$s kd f", name, age, 7.5);
Thisstatementwould causethe reading ofthe items in the list from the file specified by fp.
according to the specifications contained in the control string. Example:
fscanf(f2, "s %d", item, &quantity):
Likescanf,fscanf also returns the number ofitems that are successfully read. When the
end offile is reached, it returns the value EOF.
main(int arge,
char *argvrf)up
The first parameter in the command line is always the program name and therefore
argv[0] always represents the program name.
Figure 12.7 shows the use of command line arguments. The command line is
7
F12 TEXT AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG
Each word in the command line is an argument to the main and therefore the total
number of arguments is 9.
The argument vector argv[1] points to the string TEXT and therefore the statenent
fp = fopen(argv[1], "w"):
opens a file with the name TEXT. The for loop that follows immediately writes the remain
ing 7
arguments to the file TEXT.
Program
#include <stdio.h>
FILE *fp:
int i;
char word[15]:
File
Management in C 407
fclose(fp):
printf("\n\n"):
Output
EEEEEE FFFFFF GGGGG
CCCCCC DDDDDD
C>F12 7 TEXT AAAAAA BBBBBB
9
of arguments in Command line
No.
file
Contents of TEXT
FFFFFF GGGGGG
AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE
C:\C\F12 7.EXE
TEXT
AAAAAA
BBBBBB
CCCCCC
DDDDDD
EEEEEE
FFFFFF
GGGGGG