1
CONTENT
: University of Mumbai
Dr. Sanjay Deshmukh
Vice Chancellor
University of Mumbai
Mumbai.
Dr. Ambuja Salgaonkar
Incharge Director
Institute of Distance and
Open Learning
University of Mumbai, Mumbai
Dr. D. Harichandan
Incharge Study Material
Section IDOL
University of Mumbai,
Mumbai
Programme Coordinator : Prof. Srivaramangai
Head Dept. of I.T.
Dr. S.D. Sharma Bhavan,
Vidnagari, Mumbai-400 097.
Course Writer :
Mr. Nikhil Pawanikar
University Dept. of I.T.
3rd Floor, Dre. S.D. Sharmar Bhavan,
Santacruz (E), Mumbai - 400 098
: Mr. Jayesh Shinde
University Dept. of I.T.
3rd Floor, Dre. S.D. Sharmar Bhavan,
Santacruz (E), Mumbai - 400 098
M.C.A. (Sem.I) Paper I PROGRAMMING WITH C
Reprint September, 2015
Published by
Incharge
Director,
Institute of Distance and Open Education,
University of Mumbai,
Vidyanagari , Mumbai-400 098.
DTP Composed by :
Printed By :
SHREE GRAPHIC CENTRE
28,MANGAL WADI, MUMBAI - 4
M.C.A. (Sem.I)
Paper I
PROGRAMMING WITH C
Contents
1.1
1.2
1.3
1.4
1.5
Flow charts
Flowchart Symbols
Need for computer Languages
Computer Programming Languages
Example (C program to add 2 numbers)
1.1 Flow Charts
A flowchart is a type of diagram that represents an algorithm or process,
showing the steps as boxes of various kinds, and their order by connecting
these with arrows. This diagrammatic representation can give a step-bystep solution to a given problem. Process operations are represented in
these boxes, and arrows connecting them represent flow of control. Data
flows are not typically represented in a flowchart, in contrast with data
flow diagrams; rather, they are implied by the sequencing of operations.
Flowcharts are used in analyzing, designing, documenting or meaning a
process or program in various fields.
No
Yes
Yes
No
1.2 Flowchart Syrnbols
Symbols
A typical
flowchart from older basic computer science textbooks
may have the following kinds of symbols:
Start and end symbols
Represented as circles, ovals or rounded rectangles, usually
containing the word "Start" or "End".
'
Arrows
."
'
ltisknownaS,'@''incomputerscience.AnarroW
coming from one symbol and ending at another symbol represents
that control passes to the synnbol the arrow points to.
Generic processing steps
It's represented as Lectanoles. Examples: "Add 1 to X"; "replace
identified part"; "save changes" or similar.
Subroutines
It's represented as rectangles with double-struck vertical edges;
these are used to show complex processing steps which may be
detailed in a separate flowchart.
lnpuUoutput
It's represented as a parallelogram, Examples: Get X from the user;
display X.
Prepare conditional
It's represented as a hexagon. lts shows operations which have no
effect other than preparing a value for a subsequent conditional or
decision step.
Conditional or decision
Represented as a diamond (rhombus) showing where a decision is
necessary, commonly a Yes/No question or True/False test. The
conditional symbol is peculiar in that it has two arrows coming out
of it,
usually from the bottom point and right point, one
coresponding to Yes or True, and one corresponding to No or
False. (The arrows should always be labeled.)
Junction symbot
Geinerally represented with a black blob, showing where multiple
control flows converge in a slngle exit flow. A junction symbol will
have more than one arow coming into it, but only one going out.
ln sirnple cases, one may simply have an arow point to another
anow instead. These are useful to represent an iter?tive process
(what in Cornputer Science is called a looo). A loop may , for
connector where control first enters,
example, consist of
processing steps, a conditional with one anow exiting the loop, and
one going back to the connector.
Labeled connectors
Represented by an identifying label inside a circle. Labeled
connectors are used in complex or multi-sheet diagrams to
substitute for arows. For each label, the "outflow' connec{or must
always be unique, but there may be any number of "inflow"
connectors. ln this case, a junction in control flow is implied.
Concurrency symbol
Represented by a double transverse line with any number of entry
and exit anows. These symbols are used whenever two or more
control flows must operate simultaneously. The exit flows are
activated concunently when all of the entry flows have reached the
concurrency symbol. A concurency symbol with a single entry flow
is a fork; one with a single exit flow is a iorn.
It is important to remember to keep these connections logical in
order. All processes should flow from top to bottom and left to
right.
$tart
Id*l F*l
ls ful=N?
Figure: 1.2 The Flow Chart of Factorial of given Number
s?'r
..1:
1.3 Need for Cornputer Languages
The flowchart is essential for drawing a diagram/Symbols based on
the certain algorithm; here Siven certain example of looping
structure and Conditional statement.
False
Test
Expressio
n
Figure 1.3 Flow chart of the while loop
Body of Loop
lnitializatlon
:llt:l-f--__l
Test
Expression
t#r .
lncrement Expression
Figure 1.4 Flow chart of the for loop:
Figure 1.5 Th flow chart of the if...sl5e statement:
Suficltmihblc
cqnlsnr*ce*
Sndtdt,vathllt i
equebro@d )
Suttchrnrhbh
cqualt Thlrdcrse
The fbw chart of the switeh statement:
Flowchart (EJtirmolgli
find the sum of first 50 natural numbers.
Figure 1.7 Flowchart to flnd the largest of ttrree numbens A,B,
and C:
1.4 Cg$pyter Proglamming Lsnguages
r
I
I
I
A programming language is an artificial language that can
be used to control the behavior of a machine, particularly a
computer
Programming languages, like human languages, are defined
how to used the syntactic and semantic rules, to determine
structure and meaning respectively,
facilitate
used
Programming languages
and
organizing
task
the
communication about
express algorithms
manipulating information, and
precisely.
Over 5 decade, computer programmers have been writing
programming code. New technologies are continuously
emerging day by day becoming ,rpre a mature at given
rapid pace. Now there are more than 3,500 docurnented
programming languages!
are
of
to
to
Hbl-rlguel Language
Assembly language
Machine Langmge
Figure 1.8 Machine language:
It is the lowest-level programming language
Machine languages are the only languages understood by
computers.
1.4.1 Machine lanquaqe:
Machine language is easily understood by computers but
machine languages are not hurnan's readable language
because the language is expressed in term of bits i.e 1 or 0.
For exaqrolq, All the physical prccessors can execute the
fot6wing binarylnstruction which are expressed in term of machine
language:
Binary:
101 10000 01100001
(Hexadecimal: 0xb061)
I
1.4.2 Assemblv Level Lanquaoe:
r An assembly language is a low-level programming
language for computers.
r A program written which are in assembly language has a
series of mnemonic statements and meta-statements.
r lt used a symbolic representation of the numeric machine
codes and other constants needed to program a particular
CPU architecture.
r A utility program is known as an assembler,
is used to
convert assembly language statements into the target
compute/s machine code.
a more or less isomorphic
one-to-one mapping) frorn mnemonic
The assembler performs
translation
(a
statements into machine instructions and data.
Example: Assembly language representation is easier to
rernernber (mo re m nemonicl
mov al, 061h
This instruction rneans: Move the hexadecimal value 01 (97
decimal) into the processor register named "a1". The mnemonic
'mov" is an operation code or opcode, A comma-separated list of
arguments or parameters follows the opcode;
Examplq (Adds 2 EugrbeEl:
nalRe "add"
; bin=00000101b
mov bl, 10 ; hex=0ah or bin=00001010b
add bl,
10 15 (declmal)
hex=0fh or
bin=000011 11b
rnoval,5
al ; 5 +
or
1.4r3 Hioh.leyel laBquaoe:
r
t
t,
r
r
High-level languages are human readable language which
can be used in everyday life, because the programmer does
not require a detailed knowledge of the machine level
language and assembly level language.
High level language are converted into low level language by
using a utility tool is known as compiler
High-level languages are used to solve problems and are
often described as problem-oriented languages
Examples of Hiqh_Levgll Lanouage :
r BASIC was used to designed
programmers;
COBOL
to leam by
first-time
is used to write programs for solving business
problems specific;
FORTRAN is developed
mathematical problems.
for solving scientific and
With the inoeasing popularity of windouns.based systems,
prsgramming languages was
designed to facilitate the deuelopment of GUI interfaces; for
example, Visual Basfe wraps the BASIC language in a
the next generation of
graphica I programming environrment.
C++ and java is popularly known as object oriented language
which based on obiect
lr5_ExaTple (C Program to a!1{ 3. nlllbersl
#includscstdlo.h> //header files
void main(fi
int a, b, ci
// declaration of $ variabtos
prl nt("Enter two n um ber-s:\n");
scanf("olod", &a) tl read 13t number
scanfi"olod",&b); /l read 2nd numher
c=a+b;// compute the sum
prlnt('Sum of 2 numbers is o/d", E!: trIprlnt sum
*a*
*_
C LANGUAGE PRELIMINARIES
Contents
2,1 C character set
2.2 lderrtifiers ard keyrords
2.3 Primary data tyPe
2.4 Declaration of Variables
2.5 Defining Symbolic Constants
2.6 Statements
2.7 Symbolic constants
2.1 C Character Set
A character is denoted by any alphabet ,digit or syrnbols to
represent information and data . The following are the valid
alphabets, numbers and special symbols which are allowed in C
Numerals: 0, 1, 2,3, 4, 5, 6, 7, 8,
Alphabets: o, b, ,,..2
A,
B,
.z
Arithmetic Operations: *, -, *, /, %(Mod)
Special Gharacterc:
2.1.1 Constants, Variabtes And Keyrrords
A 'constant' is an entity or variable that does not change, but a
'variable' as the name may change.if we do ceftain calculation
and result want to stored in some specific memory location,
11
Since we have to specify the variable depend on their
datatypes.consider an exampte if we want to store an vatue in
certain memory location that value could be of integer we have
declared a variable of integer type. since value we stored in
certain location may change, for holding such values in the
memory location we have to give the name to these memory
locations are called as 'variable names'.
Constants:
There are mainly three types of constants namely: integer, real
and character constants.
lnteger Constants:
The integer constants are
Whole Numbers
Eg. 30, 45, -26, -48
Each Computer allocates only 2 bytes in memory
depend upon the lnteger datatype.
16n bit is sign bit lnteger. (if O that means
+ve(postive) value, if 1 that menas -ve(negative)
value)
.
.
.
11111111
1111
214 213 212 211 210 2e 28
27
26
25 24 23 22 21 20
= 1*1 + 4*'l + 8*1 + 16*1 + 32*1 + 64*1 + 128*1
256*1+512*1+1024*1+ZO4B*1 + 4096*1 + 2*1
8192*1 + 16284*1
= 32767 (32767 Bits can be stored for integer constants)
. 32768 is positive
. -32767 is negative
(i) Declmal lnteger Constant:
. 0to9
o E.g: 59, 60, -72, ... (40000 cannot come because
it is greater than 32TOT)
(li) Octal lnteger Constant:
. The value is specified between 0 and T
o We have to prefix "0' value before any lnteger
values.
Eg.: 045, 056, 067
(iii) Hexadecimal lnteger:
.'
o
The value is specified between 0 to g and A to F
We have to prefix u0x" before any lnteger vatues.
E.g: Ax42,0x56, 0x67
REAL CONSTANTS:
+
+
12
The real or floating point constants are mainly in tuo part i.e
'
fractional part and the exponential part.
A real constant in fractional part must:
. lt must includes at least one digit
. lt must have a decimal point.
o lt could have positive or negative sign(default sign is
v
.
.
positive)
lt s must not have commas or spaces within it
The computer could have allocates 4 bytes in rnemory
space
Ex: +867.9, -26.9876, 654.0
ln exponential part, the real constant is represented as two
parts. The part which lying before the'e' is the 'mantisss', and
other part one which. is following 'e' is the 'exponent'.
The real constant in exponential form must follow the following
rules:
o
.
.
.
o
The mantissa part and the exponential part must
be
separated by the letter'e'
The mantissa may have a positive or negatlve sign(default
sign is positive)
The exponent must have at least on digit
The exponent must be a positive or negative integer(default
sign is positive)
The range of real constants in exponential form is -5.3e48
and .7e48
Ex +t.t94,4.1e8, -O.2e+4, 4.2e4
CHARACTER CONSTANTS
A character constiant is an alphabet, a single digit or a single
special symbol enclosed within inverted commas. The length of
a charader constant can be maximum up to 1 character which
allocated a size of each character constant would be 1 bytes
Ex: 'B','l', '#'
2.2 lde ntifi qrs_a n4 _Ke_ywords
Every word in C language is
known as keyruord or an
identifief/variable. ln C language, the reserved keyvtrord cannot be
used as a variable name. lf we used as reserved keyword as
variable name then the C complier would give compile time
exception. These reseved keyrord are specifically meant for the
compiler for its own purpose used and they can serve as buitding
blocksofaCprogram.
2.2,1 ldentifiers:
13
As per the rules of C programming language, the ldentifiers would
following the certain rules
variables, classes, methods and interfaces would gives
named as ldentifiers
The ldentifiers should be as a whole word and starts with
either an alphabet or an underscore.
The first letter of an ldentifiers or word cannot be started as
digit i.e variable name as lday declared in the programming
can muse an eror and would allow to declared as an
variable in C language
The identifiers are case sensitive ie if we declared variable
Names as day and DAY in clanguage, the compirer would
not interpret as same variable. The capital letter and Small
letter are different because the ASCII value is different for
Capital letter and Small letter therefore the C Complier
would interpret different even though the variable have same
meaning
when declaring any identifiers no @rnmas or blanks are
allowed in it
No special symbol other than an underscore can be used at
declaration.
Ex.: name
Person name ll notallowed in C langauge
o
.
.
seml_rollno
alpha
Types of C Variables
While Declaring an Variable in the C Program , the operating
system allocate a space(i.e location) in the memory and ttrese
locations can contain integer, real or character constants, i.e
An integer variable can hold only an integer mnstant, a real
variable can hold only a real constant and a character variable
can hold only a character constant.
Rules for declaring Variable Names
A variable name is any combination of 1 to 26 small alphabets
and Capital letters , digits or unders@res. Some compilers
allow variable names should be length of 24T characters.
The first character in the variable name should be an
alphabet
When declaring any identifiers m) @mmas or blanks are
allowed in it.
No special symbol other than an underscore can be used
at declaration
Ex.: simple_interest
employee_!ra
pod_e_81
14
C compiler makes it compulsory for the programmer to declare
an variable nanid
any variable name following datatype
according needs of the programs while developing The
declaration of datatype must declared first followed by the
variable name. These is an example of declaration of an
variable name along with their datatypes
Ex.: int simple interest, employee-hra ;
float basic_salary ;
char grade ;
of
The maximum length that C language is allows up to 31
characters for declaration of variable ,Large number of
variable names can be constructed by using the abovementioned rules. lt is good practice for the programmers that
the declaration of the variable name must have meaning full
name according to the needs for program.
C Keywords
C language has 32 keyrords or reserved words which
combines together to form a formal syntax. Note that all
keywords in C languages are written in lower case. Remember
as mentioned above in the course that a keyword could not
allowed as a variable name in the language
The Following Table is an well known reserved keyword of the
C language.
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
shofi
signed
sizeof
static
Struct
Switch
Typedef
Union
Unsigned
Void
Volatile
While
A C language programmer has to tell the system before that the
different'type of numbers or characters while using in the program.
These types is called as data types. The C programming
languages has different numbers of datatypes.A C programmer
has to use appropriate data tlpe as per requirement of program
needs.
C language data types can be broadly classified as
Primary data type
Derived data type
User-defined data type
'
15
2.3 Primary Data T'
These are fundamental data types are using in C programming
language.
1
lnteger
int
Character
char
Floating Point
float
Double precision floating point
double
Void
void
The size and range of each data type is given in the table below
DATA TYPE
RANGE OF VALUES
Char
-128 to 127
lnt
-32768 to +32767
Float
3.4 e-38 to 3.4 e+38
double
1.7 e-308 to 1.7 e+308
2.3.1 lnteger Type :
lntegers are whole numbers which value's are dependent totally
dependent upon different types of machines. The C programming
language has given specific types of a range of numbers and
storage space. C programming language has 3 types of integer
storage i.e. short int, int and long int. All of these data types have
signed and unsigned forms. A short int requires half the space than
normal integer values. Unsigned numbers are always positive .lf we
want to specify the longer range value than we have to declare
signed long and unsigned long int data types.
2.3.2 Floating Point Types ;
Floating point number contains a real number has 6 digits precision
or accuracy. Floating point numbers are represented by the
reserved keyword known as float. When the accuracy of the floating
point number is insufficient, then instead of float datatype we can
use double datatype. The double datatype equivalent to floating
point number but has longer precision than the floating point
precision. lf we want to extend the precisiun further we can use
long double which can occupies memory space of 80 bits.
16
2.3.3 Void Type
We used tha void data type, at the time of function declaratlon
.when we declares a function as void datatypes it epnsiders as the
function doesnot retum any values to the function which have been
called
2.3.4 Character Type :
A single character can be defined as a char datatype. Memory
requirement for storing a character value is a 8 bits allocation
means a 1 byte. The signed or unsigned can be explicitly used in
char datatypes. Unsigned characters have values between 0 and
255 and signed characters have values from -128 to 127.
Size and Range of Data Types
TYPE
SIZE
Range
(Blts)
Char or Signed Char
-128 to 127
Char or Signed Char
0 to 255
lnt or Signed int
16
-32768 to 3276V
Unsigned int
16
0 to 05535
Short int or Signed
short int
-128 to 127
Unsigned short int
0 to 255
Long int or signed
lono int
Unsigned long int
32
-21 47
32
0 to 4294967295
Float
32
3,4 e-38 to 3.4 e+38
Double
64
1.7e-308 to 1.7e+308
Long Double
80
3.4 e-4932 to 3.4 e+4932
2.4 Declaration Of Variables
483648 to
21 47
483647
17
fie*iaratlon of variables tells the compiler what types of values will
be'assigned to variable name whether value would be lnteger type
or ehmre$ter type or values would be another datatype as
rnentisnad in ahove table The declaration does two things.
t. Tells the co*T lpiler what is the name of varaible.
2" Sp*ei$es what typa of data or value the variable will hold in the
mernory location.
The geneml format of any declaration
datatype a1 , &?, &3,
,... an:
Where a1, 42, a3 are variable names. Each variables are separated
by commes. A declaration statement must end with a semicolon.
Example:
int total;
int emp_no, salary;
double standard_deviation, mean;
Datatype
Character
Unsiqned Character
Signed Charac{er
Signed lnteger
Signed Short lnteger
Signed Long lnteger
UnSioned lnteoer
UnSigned Short lnteger
UnSigned Long lnteger
Floatins Point
Double Precision Floating Point
Extended Double Precision
Floating Point
Keyurord Equivalent
Char
unsigned char
siqned char
sisned int (or) int
signed short int (or) short int (or)
short
signed long int (or) long int (or)
long
unsigned int (or) unsigned
unsigned short int (or) unsigned
short
unsigned long int (or) unsigned
long
Float
Double
long double
2.4.1 Ueer defined Wpe declaration
ln C language , user defined data type identifier from the existing
data types which can be used for declaration of variables. The
general syntax is
typedef type identifien
18
Here 'type' represents existing data type and 'identifier'
given to the data type.
is name
Example:
typedef int rollno;
tlryedef float standard-deviation
Here rollno symbolizes or refer to int data types and
standard_deviation symbolizesor refer to float. They can be later
used to declare variables as follows:
rollno studentl, student2;
standard deviation deviationl , deviation2;
Therefore studentl and student2 are indirectly declared as integer
data type and deviationl, deviatian? are indirectly as float data
type.
The second type of user defined datatyrye is enumenated data type
which is defined as follows.
enum identifier {value1, value2 .... value n};
The identifier is a user defined enumemted datatype which can be.
used to declare variables that have one of the values enclosed
within the braces. After the definition we can declare variables to be
of this 'new' type as below.
enum identifier Vl , V2, V3, ... .. . . .. Vn
The enumerated variables V1,V2, ..... Vn can have only one of the
values valuel , value?.,... value n
Example:
enum day {Monday, Tuesd?y, .... Sundayl;
enum day week_start, week end;
week_st = Mondayi
week_end = Friday;
if(wk_start == Tuesday)
week_en = Saturday;
z.4.zDectaration of Storage Glass
Variables in C have not only the data type but also storage class
that provides information about their location and visibility, The
19
storage class divides the portion of the program within which the
variables are recogni zed.
auto : lt is a local variable known only to the function in which it is
declared. Auto is the default storage class.
static : Local variable which exists and retains its value even after
the control is transferred to the calling function.
extern : Global variable known to all functions in the file
register : Locial variables which are stored in the register.
2.5 Defining Symbolic Constants
symbolic constant value can be defined as a preprocessor
statement and that can be used in the program as any other
constant value. The general form of a symbolic constant is
# define symbolic_name value;of _constant
Valid examples of constant definitions are
# define marks 100
# define total 50
# define pi 3.14159
These values may appear anywhere in the program, but must
declare before it is referenced in the program.
It is a standard practice that the symbolic constant must be place
at the beginning of the program.
2.5.1 Declaring Variable as Constant
The values of some variable may be required to remain constant
throughout the program. lf we tries to modifies the constant value.
The C Compiler will not allows the programmer to modifies the
constant values We have to declared the qualifier const at the time
of initialization.
The const keyword is used to defined
declared the constant keyword followed
the program, ?s we
by
any data type and
variable assigned value to the variable , this value cannot modified
at the runtime.
The syntax for declaration of const qualifier:
const data type variable_name= vatue
2A
Example:
Const float pi =
3.142;
'1
The const data type qualifier tells' the compiler that the value of the
float varlable pi may not be modified in the program
Arlthmettc Exprcsslons
An expresslon is a cornbination
of variables constants
and
language.
C
the
rules
of
operators vlhich is written according to
ln C every oxpression evaluates to a value i.e., every resultant of
expression has some value of a certain data type that can be
assigned to a another variable of same type.
Some examples of C expressions are shown in the table given
below.
Algebralc Expression
C Expression
axb-c
a*b-c
(m+n)(x+y)
axb/c
(m+n)"(x+!/)
a*b/c
Evaluation of Expresslons
Expressions are evaluated using an assignment statement of.
the form
Variable = expression;
o
o
Variable is any valid C variable nQmg according to rules 0f C
languages which have been specifies.
When the statement is encountered, the expression ls
evaluated first and then replaces the previous value of the
variable on the left hand side.
All variables used in the expression must be assigned values
before evaluation is attempted.
Example of evaluation statements are
x=a"b-c
Y = b I c* a
z=a-blc+d;
2.6 $taternents
21
. Each instruction in a C program is written as a
sepflrate
statement. Therefore a complete C program wpuld comprisg of a
series of statements.
. The statements in a prognam must appear in the same order in
which we wish them to be executed; unless of course the logic of
the problem demands a deliberate Jurnp' or transfer qf control to a
statement, which is out of sequence.
r Blank spaces may be inserted between two words to improve the
readability of the statement.
. However,
no blank spaces are allowed within a variable, constant
or keyword.
All statements are entered in small case letters.
. C has no specific rules for the position
at which a statement is to
be written. That's why it is often called a free-form language.
o EveU C statement must end with a (semicolon)
statement terminator.
; Thus ; acts as a
2.7 Symbolic Constants
.
.
o
The numbers 0, 20, and 300 in the program mean very little to
readers of the program unless they are very familiar with what
the prograrn is doing
for (fahr=0; fahr <= 300; fahr = fahr+20)
C allows the definition of symbolic constants - narnes that will be
replaced with their values when the program is compiled
. Symbolic constants are defined before main0, and the syntax is
. #define NAME value
Example
I
I program name: temperatureconversion.c
#include <stdio.h>
#define LOWER_BOUND 0 f lower limit *l
#define UPPER_BOUND 300 /* upper limit */
#define INDEX_STEP 2A /* step size *l
main0
{
int fahrl
22
for
(fahTLOWERIOWER-BOUND;
fahr<=U PPER-BOUND; fah rfahr+ N DD(-STEP)
{
I
pri
n('
o63d
0/o6.
fin",fahr, (5. 0/9. 0 )*(fahr-32
)) ;
)
)
There
o
is no semi-colon afrer the definition of a symbolic
constant
. You cannot change the value of a symbolic constant at runtime
***
3
INPUT.OUTPUT
ContenG
3.0 lntroduction
3.1 Getchar Function
3.2 putchar Function
3.3 scanf Function
3.4 printf Function
3.5 gets and puts functions.
3.0 lntroduction
ln 'C' language there has many library furrction to take the input
data and output data like getchar, putchar, scanf, printf, gets and
puts. These functions allows the flow of data from the computer
and the standard inpuUoutput devices and vice-versa. As the name
suggest,the library function getchar and putchar allow single
characters to be transfened lnto and out of the computer, scanf and
printf allows the transfer of single characters, numerical values and
strings, gets and puts allows the string to flow in and out of the
@mputer.
An inpuU output function can be written and accessed from
anywhere in a program by simply writing the function name, the
function can contain the parenthisis or paramters. Sometime
inpuUoutput functions doesnot require parameters, but the empty
parentheses rnust be required.The C lanquage contain numrous
header file which contain the n number function and constant. One
of the header file in the C language for inpuUorJtput function is
stdio.h This header file contains the information about inpuUoutput
library functions.
3.1 Getchar Function
getchar function reads a single character from standard input
devices ie keyboard. lt does not have the parameters and it will
return a value as an input character.
ln general,format of getchar function is written as
variable = getchaO;
here variable as of character datatype ie char
For example char c;
6= gtGhar 0 ;
24
The seeond line state that lt will take a single character from the
standard input device and then lt will assigned to c i.e character
variable.
While doing operation on the file,lf an end-of-file condition is
encountered when reading a character with the getchar function,
the value of the symbolic constant EOF will becomes false and
loop will be terminated, the control of execution will comes out of
loop and next statements followed by while loops get exectued .
This function can also be used to read multicharacter strings, by
reading one character at a time within a multipass loop.
3.2 Putchar Function
is
the standard C function that will prints or displays a
Putchar
single chardcter to standard output devices i.e on monitor screen or
called as output console unit , so the function is called as putchar.
This function will takes one argument as character,this character is
enclosed with the single quotes and the single character will be
sent to the output console unit. lt also returns this character as its
result. lf an error is encountered , ?r error value is retumed.
Therefore, if the retumed value of putchar is used, it should be
declared as a function retuming an int.
For example
putchar ('N');
putchar ('a');
putchar ('t');
putchar ('i');
putchar ('o');
putchar ('n');
putchar ('a');
putchar ('t');
When putchar is used, however, each character must be output
separately. The parameter to the function calls in the given
statements
are character
apostrophes .
constants, represented between
Of course, the arguments could be
character
variables instead.
Two functions that require by FILE pointers are getc and putc.
These functions are similar to getchar and putchar, but that they
can operate on files other than the standard input and output
devices. The getc function will takes one argument, which is a FILE
pointer representing the file name from which the input is to be
taken.
The expression
getc(stdin) is similar to
?$
getchao
and
the expression putc(c, stdout) is *anne as putcha(c).
3.3 Scanf Function
lnput data or an data items can be taken into the cornputer by using
a standard input device by means of C library funqtion scanf. Any
combination of numerical values, charac{ers single character and
strings can be taken from standard lnput functlon of C library
function ie scanf$. This function I'etums the number of data items
or elements that have been entered successfully.
ln general form of scanf function can be written as
scanf (string, parameter
, paramster 9, . . , paranreter r,);
that will rerqe*ired to fonmatting
the input
Where string = string
parameters, and Parameter 1, paranneter ? that parameters is to
represent the individual input data item or elernents.
The string have individual groups af characters, wttfi one character
group for each input data item. Each character group must start
with percent sign (%). ln the string, multiple character groups can
be contiguous, or separated by white space charac'ters. The
@nversion character that is used with 7o sign are many in number
and all have different meaning coresponding to type of data item
that is to be input from keyboard.
Some of the conversion characters are listed below:-
Character
D
I
o
U
Input Data; Argument tyPe
decin'lal integer: int *
integer; int *. The integer may be in octal (leading
0) or hexadecimal (leading 0x or 0X),_
*
octal inteser (with or without leading zero); int
*
urnsigned decimal integen unsigned int
hexadecimal integer (with or without leading 0x or
OX);
int'
characters; char The next input characters
(default 1) are placed at the indicated spot. The
normal skipover white space is suppressed; to
read the next non-white space character, use %1s
character string (not quoted); char *, pointing to an
array of characters long enough for the string and
a terminating '\0'that will be added.
26
g,f,g
o/o
D
I
o
U
floating-point number with optional sign, optional
decimal point and optional exponent; float *
literal Yoi no assignment is made.
decimal integer; int'
integen int *. The integer may be in octal (leading
0) or hexadecimal (leading 0x or 0X).
*
octal inteser (wlth or without leadins zero); int
unsigned decimal integer; unsigned int *
hexadecimal integer (with or without leading 0x or
oX); int'
The next input characters
characters;
(default 1) are placed at the indicated spot. The
normal skip-over white space is suppressed; to
read the next non-white space character, use a/o1s
char
3.4 Printf Function
The printf function is used to print out the output, either on screen
or pape(The letter "f in printf consider as either Tormatted" or
"function" ). lt is similar to the input function except sole purpose of
the printf function is used to printf the data on the computer
peripheral devices like Monitor Screen or ouput Screen and printer
. So, printf function is used to transfer the data from the cornpute/s
memory to the standard output device, whereas the scanf function
is used to take the data from the user in term of the standard input
device like keyboard and stores the data in the cornpute/s
melrnory.
The general form is:
printf(string, parameterl,
parameterZ,
, parameter n)
string that will required to formatting the output parameters,, and
1, parameter2... parameter are argurnents that
nspresents the individual output data items. The parameters can be
written as constants, single variable or anay names or more
complex expressions.
parameter
Unlike scanf function, the pammeters in a printf function do not
represent mernory addresses and therefore they are not preceded
by ampersand (&) sign.
The control string or string is composed of individual groups of
characters, with one character group for each output data item.
Each character group must start with a percent sign like in scanf
function followed by a conversion character indicating the type of
the corresponding data item.
27
Fonnat Specifierc
There are many format specifiers defined in C
o/oi
ar
olod
o/oC
o/ol
ololt
%s
Note: ololf stands for
int
char
float
double
string
lono float
example of printf formatted ouput:
#includecstdio.h>
#includecconio.h>
main0
(
int a,b;
float c,d;
clrscO;
a=17i
b=al2i
printf('7od"',0)t
printf("7o3d\n',b);
printf('7o03d\n',b);
c = 17.3;
d=c/3;
p ri
ntf('
o/o3,
2fln', d );
getch0;
retum 0;
)
008
5.77
As you can see in the first printf stratement we print a decimal. ln the
second printf statement we print the same decimal, but we use a
width (o/o3d) to say that vue want three digits (positions) reserved for
the output.
The result is that two "space characters" are placed before printing
the character. ln the third printf statement we say almost the same
as the previous one. Print the output with a width of three digits, but
ftll the space with 0.
28
ln the fourth printf statement we want to print a float. ln this printf
statement we want to print three position before the decimal point
(called width) and two positions behind the decimal point (called
precision).
The \n used in the printf statements is called an escape sequence.
ln this case it represents a newline character. After printing
something to the screen you usually want to print something on the
next line. lf there is no \n then a next printf @mrnand will print the
string on the same line. Commonly used escape seguences are:
\n (newline)
\t (tab)
\v (vertical tab)
\f (new page)
. \b (backspace)
\r (caniage retum)
\n (newline)
Let's take another look at a printf formatted output in a
like
#includecstdio.h>
main0
{
int Fahrenheit;
.
.
.
.
.
.
.
o
for (Fahrenheit = 0; Fahrenheit <=
2OO;
Fahrenheit = Fahrenheit + 10)
printf('703d
Fahrenheit,
)
o -17.778
10 -12.222
20 -06.667
30 -01 .111
40 04.444
50 10.000
60 15.556
70 21.1'11
80 26.667
90 32.222
100 37.778
110 4i!.333
120 48.889
130 il.444
140 60.000
150 65.556
160 71.111
170 70.667
180 82.222
pa 87,778
200 93.333
5. 0/9.
0).( Fahrenheit.32))
7o06.3fln",
;
29
As we see that print the Fahrenheit temperrature wlth a width of 3
positions. The Celsius temperature is printed with a width of 6
posltlons and a precisbn of 3 positions afrer the decimal point.
. o/od (print as a decimal integer)
o o/oil (print as a decimal integer wlth a width of at bast 6 dbit
wide)
o %f (print as a floating poln0
o olo4t (print as a floatirp point trtlth a width of at least 4 dlglt
wide)
. o/o.41 (print as a floating point with a preclsion of four
characters after the decimal point)
o Yo3.X (prlnt as a floating point at least digit 3 wide and a
precision of 2 digit)
Formatting other Typec
Until now we only used integers and fuats, but thene are
more q/pes you can use. Take a bok at
the following example:
#includecstdio.h>
#includecconio.h>
cl*O;
int main$
{
printf(The mlor %s\n', Yetlovr/);
printf('First numben 7d\n', 5678);
printf('Secord number 7o04d\n', 78);
printf("Third numben 96i\n', 5678);
printf('Float numben 7o3.2fin', 3.1 41 5g);
print('Hexadecima[ 96x\h', 255);
printf('Octat: or6o\n', 255);
printf("Unsigned value: or6u\n", 1 50);
print('Just print the percentage sign 9696h', 10);
getoh0;
retum 0;
)
The mlon Yellow
First numben 5678
Second number: 0078
Thard number 5078
Float number 3.14
Hexadecimal: ff
Oqtal: 377
Unslgned value: 150
Just prlnt the
o/o
30
Note: Last printf statement only print percentage sign
,.
in
the
slrow
doesnot
The number 10 in the above last statement
output screen it doesn't matter , So if you want to print a percentage
number you vvould
like write the following
statement:
printf("%2do/oo/o\rr", ,O), (The output will be 1Oo/o)
Formatting Strings
How we used string format conversircns. Take
a look at the
following example:
#includecstdio.h>
#includecconio.h>
int main$
clrsc0;
printf(':%s:\n", "Hello, world!');
printf(":%1 Ss:\n','Hello, world!");
printf(':%. 1 Os:\n', "Hello, norld!');
printf(':%-l 0s:\n','Hello, world!');
printf(':%-1 5s:\n",'Hello, urorld !");
printf(':%. 1 5s:\n','Hello, trvorld!');
printf(":o/o1 5.1 Os:\n', 'l-Gllo, world!");
printf(':%-1 5. 1 Osih",'Hello, world!');
getch();
:Hello, tluorld!:
: Hello, world!:
:Hello, wor:
:Hello, world!:
:Hello, world! :
:Helto, world!:
Hello, wor:
:Hello,
:
wor
As you can see, the string format @nversion reacts very different
from number format conversions.
The printf(":%s:\n", "Hello, world!"); statement prints the string
(nothing special happens.)
The printf(":o/o15s:\n", "Hello, worH!"); statement prints the string,
but print 15 characters. lf the string is smaller the 'emp$
positions will be filled with "whitespace."
The printf(':%.1Os:\n", "Hello, world!"); statement prints the
string, but print only 10 chanacters of the string.
The prlntf(":%-10s:\n", "Hello, vvorld!'); statement prints the
string, but prints at least 10 characters. lf the string is smaller
"whitespace" is added at the end.
The printf(":%-1Ss:\n", "Hello, rrvorld!"); statement prints the
string, but prlnts at least 15 characters. The string in thls case is
.
o
.
.
31
shorter than the defined 15 cluracter, thus lrtritespace" is
.
.
o
o
added at the end (defined by the minus sign.)
The print(":%.15s:\n", 'Hello, world!'); statement prints the
string, but print only 15 characters of the string. ln this case the
string is shorter than 15, thus the whole string is printed.
The print(":%15.10s:\n", 'Hello, world!"); statement prints the
string, but print 15 charaders.
lf the string is smatbr the 'emptyf positions will be filled with
trhitespa@.' But it will only print a maximum of 10 characters,
thus only part of new string (old sting plus the whitespace
positions) is printed.
The printf(":o/o-15.10s:\n", "Helto, uorld!'); statement prints the
strlng, but it does the exact same thlng as the previous
statement, ac@pt the trhitespa@' is added at the end.
3.5 GETS AND PUTS FUNCTION
'C' @ntrains a number of other tibrary functions that permit some
fonn of data transfer into or out of the computer.
gets and puts functbns provides facilities to transfer of strings
between the computer and the standard inpuUoutput devices. ln
these function only one argument or parameter is passed. The
paratnter must be a data item or element that represents a string.
The string may contalns whitesprce characters,
ln the case of gets furrctbn wlll takes a character as string with a
newline characater.
The gets and puts functlons are altema$vs use for scanf and printf
for reading and displaylng strings.
f,ncludecstdio.h>
#nclude<conio.h>
lnt
(
cfiar
main(
name[301
clrsco
printr
puts
"Enter
gets
puts
getch0;
retum
(
(
(
your
name
'Welcome
name
name\n'
to
);
);
Departnent');
);
0;
Output:
Enter
0ur
name
32
Nitin
Welcome
Nitin W
to
Wagh
Depailment.
Tlpse lines uses the gets and puts to tnansfer the lina of teld into
and out of the comgtter, When this program is executed, it will give
the same result as that Elth scanf ard printf function for lnput and
output of given varlable or amay.
o+o
PRE.PROCESSOR COMMANDS
Centsnts
4"0 lnfitrcludion
4.1 Th* #inctude Preprocessor Directive
4.2 fm #define Pmproce$sor Directive: Symbolic Constants
4.3 Conditional Compilation
4.0 Intrcductlon
- For C preprooe$s&tr,
preprocessing occurs before a program is
process
involved during the preprocessing,
compiled. A complete
rcmpiling and linking can be read in Module W.
- Some possible actions are:
. lnclusion of other fiies in the file being compiled.
. Definition of symbolic constants ard macros.
. Conditional compilation of prograrn code or code segment.
. Conditional execution of preprocessor directives.
- All preprocessor directives begin with #, and only white space
characteni may appear before a preprocessor directive on a line.
4.1 The #lnclude Preprocessor Directivq
- The #include directive causes copy of a specified file to be
included in place of the directive
The two forms of the #include directive are:
//searches for header files and replaces this directive
//with the entire contents of the header file here
#include <headerJile>
-Or
#include "header_file'
e.g. #include
<stdio.h>
'
#include "myheader.h"
- lf the file name is enclosed in double quotes, the preprocessor
searches in the same directory (local) as the source file being
compiled for the file to be included, if not found then looks in the
subdirectory associated with standard header files as specified
using angle bracket.
34
- This method is nonnally used to include user or programrner'
defined header files.
- lf the file name is enclosed in angle brackets (< and >), it is used
for standard library header files, the search is performed in an
implementation dependent manner, normally through designated
directories such as C:\TC\INCLUDE for Turbo C (default
instaltation) or directories set in the programming (compiler)
environment, pCIect or configuration. You have to check your
compiler documentation. Compilers normally put the standard
header files under the INCLUDE directory or subdirectory.
- The #include directive is nonnally used to include standard library
such as stdio.h or user defined header files. lt also used with
programs consisting of several source files that are to be compiled
iogetfrer. These files should have common declaration, such as
functions, classes etc, that many different source files depend on
those @mmon declarations.
- A header file containing declarations common to the separate
program files is often created and included in the file using this
directive. Examples of such common declarations are structure
(struct) and union (union) declarations, enumerations (enum),
classes, function prototypes, types etc.
- Other variatibn used in UNIX system is by providing the relatlve
path as follows:
#i ncl ude "/usr/loca
l/i ncl
ude/test. h{
- This means search for file in the indicated directory, if not found
then look in the subdirectory associated with the standard header
file.
#include'sys/test1 .h'
- This means, search for this file in the sys subdirectory under the
subdirectory associated with the standard header file.
4.2
The #Define Preprocessor Directive:
Symbolic Constants
- The #define directive creates symbolic constants, constants that
represented as symbols and macros (operations defined as
symbols). The format is as follows:
#define identifi er rep lacement-text
- When this line appears in a file, all Subsequent occurences of
identifier will be replaced by the replacement-text automatically
before the program is compiled. For example:
35
#define Pl 3.14159
- Replaces all subsequent occurrences of the symbotic constant Pl
with the numeric constant 3.14159. const type qualifier also can be
used to declare numeric constant.
- Symbolic constants enable the programmer to create a nams for
a constant and use the name throughout the program, the
advantage is, it only need to be modified once in the #define
directive, and when the program is recompiled, all occurrences of
the constant in the program will be rnodified automatically, maklng
writlng the source code easier in big prograrns.
- That means everything, to the right of the symbolic constant name
replaces the symbolic constant.
- Other #define examples include the stringizing as shown below:
#define STR This is a simple string'
#define NlL ""
#define GETSTDLIB
#include <stdlib.h>
#define HEADER'rnyheader.h"
4. 2.
The #deft ne Preprocossor Dlroctive : iiacros
- A macro is an operation defined in #define preprocessor directive.
- As with symbolic constants, the macro-identifier is replaced in the
program with the replacement-text before the prograrn is compiled.
Macros may be defined with or without arguments.
- A macro without arguments is processed like a symbolic constant
while a macro with arguments, the arguments are substituted in the
replacement text, then the macro is expanded, that ls the
replacement-text replaces the identifier and argument list in the
pr0gram.
- Consider the following macro definition with one argument for an
area of a circle:
#define CIR_AREA(x) Pl"(x).(x)
- Wherevet'
CIR AREA(x) appears in the file, the value of
is
substituted for x in the replacement text, the symbolic constant Pl ls
replaced by its value (defined previously), and the macro is
expanded in the program. For example, the following statement:
area = CIR_AREA(a);
- ls expanded to
area = 3. 1 41 59.(4)'(4);
36
- Slnce the expression conslsts only of constants, at compile tirne,
fie value of the expression is evatuated and assigned to variable
en8a.
- The parentheses around each x in the replacernent text, force the
propor Order of evaluation when the macro atgument is an
oxprBssion. For example, the following statement;
arEa = CIR_AREA(y
*2'l;
- ls expancled to:
area = 3.14159*(y + Zl'(y + 2);
- This evaluates conectly because the parentheses force the proper
order clf evaluation. lf the parentheses are omitted, the macro
srtpression is:
anea = $.1 41 59*y+2'y+2;
- Wtrich evaluates incorrectly
(following the operator precedence
rules) as:
*
errea = (3,14159 y) +
(2' y) + 2i
li.'
.,j
- Because of the operator precedence rules, you have to be careful
about this.
- Macro CIR_AREA could be defined as a function. Let say, name it
a circleArga:
double clrcleArea(double x)
t
lrfttrn (3.14159*x"x);
)
- Performs the same calculation as macno CIR AREA, but here the
overhead of a function call is associated with circleArea function.
- The advantages of macro CIR AREA are that macros insert code
directly in the program, avoiding function ove*tead, and the
fogfiam rcmains readable because the CIR AREA
catctrtati'on is defined separately and named meaningfully' The
dlsadvantage is that its argument is Evaluated twice.
- The following is a macro definition with 2 arguments for the area
of a rectangle:
#define RECTANGLE-AREA(p, q) (p).(q)
37
- Wherever RECTANGLEJREA(p, q) appears in the program, the
vatues of p and q are substituted in the macno replacement text,
and the macro is expanded in place of the macro name. For
example, the statement:
rectArea = RECTANGLE_AREA(a+4, b+7);
- Will be expanded to:
rectArea = (a+4)"(b+7);
- The value of the expression is evaluated and assigned to variable
rectArea.
- lf the replacement text for a macro or symbolic constant is longer
than the remainder of the line, a backslash (\) must be placed at the
end of the line indicating that the replacement text continues on the
next line. For example:
#define RECTANGLEJREA(p, q) \ (p).(q)
- Symbolic
constants and macros can be discarded by using the
preprocessor
#undef
d irective.
Directive #undef un-defines a symbolic constant or macro Jralne.
- The scope of a symbolic constant or macro is from its definilion
until it is undefined with #undef, or until the end of the file. Once
undefined, a name can be redefined with #define.
Functions in the standard library sometimes are defined as
macros based on other library functions. For example, a macro
commonly defined in the stdio.h header file is:
#defi ne getchar$ getc(std in)
- The macro definition of getchafl uses function getc$ to get one
character from the standard input stream. putcharQ function of the
stdio.h header, and the character handling functions of
the ctype.h header implemented as macros as well.
- A program example.
#include <stdio..h>
#include <stdlib.h>
#define THREETIMES(x) (x)'(x).(x)
#define Cl RAREA(y) (Pl).(y).(y)
#define REC(2, a) (z).(a)
#define Pl 3.14159
int main(void)
(
float P = 2.5;
float r = 3.5, s, t, u = 1.5, v = 2.5;
38
printf("Power to three of =7ofln' )
ntf("%f',TH REETI MES( p));
printf('Circle circumfenen@ = o/ot,2*Pl*r )
*r)
p ri ntf( "o/ofl n ", (2'P
;
5 = QIffiREA(r+p);
printf("Circle area =W,= Pl'fr)
print("Yoftn',s);
t = REC(u,v);
printf('Rectangle area =o/of , u*v );
printf('olofln",t)
system("pause");
retum 0;
pri
'
4.3 Conditiona! Compilation
- Enable the prrgmmmer to control the execution of preprocessor
directives, and the compilation of program @de.
- Each of the conditional preprocessor directives evaluates a
constant integer expression. Cast expressions,
slzeofQ
expressions, and gnumeration constants cannot be evaluated in
preprocessor directives.
- The conditbnal preprocessor construst is much like the if selection
structure. Consider the following preprocessor code:
:
#if ldefined(NULL)
#define NULL
#endif
*,,.
- These directives determine wlrether the NULL is defined or not.
The expression deftned(NuLL) evaluates to 1 if NULL is deftrpd; 0
othenrise. lf the rcsult is 0, ldefined(NuLL) evaluates to 1, and
NULL is defined.
- Othenrise, the #define directive is sklpped. Every #if consfiuct
ends with #endif.
Directive #ifdef and #ifndef are shorthand for #if defined(name) and
#if ldefined(name).
- A multiple-part conditbnal preprocessor construct may be tested
using the #elif (the equivalent of else if in an if stnrcture) and the
#else (the equivalent of else in an if structure) directives.
- During program development, programmerc often find it helpful to
cornment out large portions of code to prevent it from belng
compiled but if the code contains comments, /' and *l or //, they
cannot be used to accomplish this task.
39
- lnstead, the programmer can use ttrc following
preprocessor
construct:
#if 0
cod.e prevented from comPiling...
#endif
- To enable the code to be ompiled, the 0 in the preceding
construct is replaced bY 1.
- Conditional compilation is commonly used as a debugging aid.
Another example shown below: instead using the printfQ
statements directly to print variable values and to confirm the flow
of control, these printf$ statements can be enclosed in conditional
preprocessor directives so that the statements are only compiled
while the debugging process is not completed.
#ifdEf DEBUG
printf("Variable x = 7od\n", x)i
#endif
The code causes a printf$ statement to be compiled in the
program if the symbolic constant DEBUG has been defined
(#defined DEBUG) before directive #lfdef DEBUG.
- When debugging is compbted, the #define directive is removed
from the source file, and the printf$ statements inserted for
debugging purpss are ignored during compilation. ln larger
programs, it may be desirable to define several different symbolic
constants that control the onditional compilation in separate
sections of the source file.
- A program exampl6.
#define ModulelO
#deflne MyVersion 1.1
#include <iostream.h>
#include <stdlib.h>
int main(void)
ntf('Sa m ple using #d efine, #ifd el #ifndefl n')
printf(' #undef, #else and #endif...\n");
pri
pri ntf(
"--F----$1'
#ifdef Modulel0
prinf(lnModulel 0 is defined.\n');
#else
printf("\nModulel 0 is not defined.\n");
#endif
#ifndef MyVersion
printf(lnMyVersion is not defined\n');
#else
printf('\nMyVersion is =96d\n,MyVersion)l;
#endif
40
ffief MyRevision
printf('\nMy Revision is defi ned\n");
#else
print(lnMyRevision is not delinedl\n');
#ndif
#urdef MyVersion
fifrdef M$/ersion
printf("MyVersion is not defined\n');
#else
prtntf('ltlyVersion is =96d", MyVersion );
#endlf
system('pause');
retum 0;
)
.&.&A
PREPARINffi EruA RU${NING A
COMPLETffi S PMSGRATfi
Contents
5.1 Preparing and Running a Complete C Pnogram.
5.2 The Program Development Cycle
5.3 Creating the Source Code
5.4 Using an Editor
5.5 Compiling the Source Code
5.6 l-inkirq to Create an Executable Fih
5.7 Cornpleting the Development Cycle
5.8 The C Development Cycle
5.9 Your First C Program
5.10 Entering and Compiling HELLOWOF(LD.C
5.1 Pr.eparing and Running a Qomplqlp Q fr1plam
Planning a prcrgram
First of all, you should have to take the certain step fsrcreating the program,lf desired problem Is given to 1ou,
according to need of the program, you have to plan, th*
after the planning is over, then you have to apply &A
plan it into program, before implemented in b ep
program, first of all you have write the algorithm for tHl
problem, after the algorithm, you have to translate il*
algorithm into the desired prqramming langtrage.
"
WritingaCprogram
Translate the algorithrn into equivalent C instructions
comments should be included within a c program
A well written program should generate ctear, legible output
The program should be user interactive.
consider a
display screen.
c prognam for display the "Hefloworld" on tfu
*l,I
Here the main objective of the prognammer to display tho
sentence "HelloWorld", if you do not have the objective in the mir*
then you never implemented the program in any programmias
langauge, As said to you,First of alt need the plan, then design fiu
t
tf
42
algorithm for particular to that problem, then algoritm is translated in
to Sre programming language code.
5,2 The Progratn Development CYcle
ln the ptogramming development cycle there are following
step, the first step is you need the editor you creating the file on the
disk. ln the window operating system, you need the notepad for
uiting the source code, ln the Unix operating system, )ou need the
vi Editor for writing the source code in C language, The second step
ls you need the conrpiler to compile the code, why we need the
compiler? As definifron say that the compller is the tool or program
which convert the high level language into machine level language,
because the high level language is human readable language and
easily understand by the programmer and write the set of
instructbn according to programming a language, this set of
instruction cannot understand by the computer , computer only
understand the machine language i.e 1 and 0, The compiler is a
tool that's converts the source code in to machine langusg,
For converttng the C source code , The vendor provides the
C compiler that converts the C Source Code into" the native
machine language. You complle the C sourqe code into the obiect
6ode. The link the object code by the linker to conveft the object
code into the executiable codel This executable code contains the
machine level language, this set of instr.rction is executed by the
processes.The fourth step is to run the progmm to get the desired
output according to your Plan.
5.3 Creating the Source Code
Flrs-tof tne question in your mind is what is an source code?
The Source code is the series or the set of instruction which is
executed by the machine to perform the desired output, As I
mentioned earlier, For writing the source code ,you will required the
editor
Let rrrite the Small C program to dlsplay "HelloWord'
The Syntax of C Program to display the HelloWorld
printf("He loWo rld" );
I
This statement instruct the computer
to
display the
'HelloWord' on the display Screen(Monitor)
5.4 Using an Editor
Most of the compiler comes with the editors(that is called the
ln{uilt compiler), some editior doesnot.Most of the operating
43
system have the inbuilt editor,such as if you are in the Linux or Unix
operating system then you can use the ed, emacs,ex,edit and vi
editor, if you are in the Windows operating system then you e6n use
the notepad or Wordpad
lf
none of these editior you want to use, then you have to
purchase the editior fiom the different vendor, sorne of the editor is
used for comerecial use , some of them used as shareware.depend
upon the need of your project you can purchass or free download
ftom the intemet.
As used are using the notepad on the windows operating
system,
The Step for open a editor , Open a notepad->Wnte the
Source code in C Langauage->after completing the souree code>then save the Source Code by used the extension .c
lf I name the program as HelloWorld.c
5.5 Compiling the Source Code
As C language is known as th6 high level language,tfrc
computer cannot understand the high level language, A computer
need a digital or binary instruction in what we called as machlne
language. Before you run the G program,first of all tyou have to
translated the C program or Source code whieh is human readable,
in to machine code that's the computer understand, For
conversion form the high level language into machine level
language, you need the tools for conversion is known as Compiler.
The compiler takes a source code as an input and produce a file
which is known as exectable file (.exe) which is conesponds to the
source code.The machine instruction which is created by the
compiler is known as object code . The file containlng the object
code is known as object file.
Each compiler has its own set of @mmand to create a obiect
@de. To compile, you use the command to run the mmpiler
following with the filename. The following example show the use of
the command to run the compiler to compiler the source file called
as Helloworld using various DOs/Windows Compiler.
Compiler
Command
Microsoft C
cl HelloWorld.c
Borland's Turbo C tcc HelloWorld.c
Borland C
bcc HelloWorld.c
Zortec C
ztc HelloWorld.c
4
To Compile HelloWorld.c under the Unix Operating system'
the following Command is used.
cc HelloWorld.c
lf you do not know which exact complier is used for compile
the source code ,contact the consultant compiler manual
lf you're using the GUI based development environment for
creating a source file and cornpiling the source file, lt very easy_ !o
used because the lntegrated Development enivornment(lDE)
contain the compile menu,by clicking the compile menu the source
code file and for running the program you can used the run
command from the IDE environment
Consider the Example famous IDE TOOL Known as TURBO
C, which contain the rich set of library file, include file and exe file
.you Can Create a new file from the file menu, use n save the
source file on the hard disk by using save menu or by using the
shorthand key F2, For compiling the source code the shorthand key
is ATL+F9 and running the executable file is CTRL +Fg
5.6 Linking to Create an Executable File
One more step ls required before running your program. C
function library that contains obiect
language consist
code (precompiled code) for predefined functions. A predefined
function contains C code that has already been written and is
supplied in a ready-to-use form with your compiler package.
is a
We have used the predefined function in C in the previous
example like printfQ . These library functions frequently need in the
program, such as for displaying information console and reading
data from fi[es. lf your are uing this predefined function in your
program, the object lile is created when you compile the source
code and combine object code from the function library to create
the final executable program . (Executable is the file which contains
the set of instruction that process required to execute the
instruction.) This process is called linking, and it's performed by a
program called (you guessed it) a linker.
Figure5.1 shows creation of source code to object code to
executqble program.
rl,li
i
il:l
i
;.1..,.|irJ":l I
q:,-
I
i
i+,Jti
i
-?:ri
-'t:- iril
! +,',
Figure 5.1, The C source.code that you wrlte is converted to object
code by the compiler and then to an executable file by the linker.
5.7 Gompleting the Devetopment Cycle
Once your program is compiled and linked to create an
executable file, you can run lt by entering its name at the systern
prompt or just like you would run any other prcgram. lf you run the
program and receive results different from what you thought you
would, you need to go back to the first step. You must idenUfy what
caused the problem and conect it in the source code. When llou
make a change to the source code, you need to recompile and
relink the progftlm to create a oonected version of the executable
file. You keep following this cycle until )ltlu get the progriam to
execute exactly as you intended.
One final note on oompiling and linking: Although compiling
and linking are mentioned as two separate steps, many compilers,
such as the DOS compilers mentioned earlier, do both as one step.
Regardless of the method by which compiling and linking are
accomplished, understand that these two processes, even when
done with one @rnmand, are two separate actbns.
46
5.8 The C Development CYcle
St"pl
,-]
an editor to write your source code. By tradition,' C
rce code files have the extension .C (for example
Helloworld,C, demo.c and so on).
Step Compite the program using a compifer. lf the compiler
doesnt find any errors in the program, it produces an obiecl
2
file. The compiler produces object files with an .OBJ
extension and the same name as the source code file (for
example, Helloworld.C compiles to Helloworld.OBJ). lf the
compiler finds errors, it reports them. You must retum to step
1 to make corrections in your source code.
Step Link the program using a linker. lf no erors occur, the linkel
produces an executable program located in a disk file with
3
an .EXE extension and the same name as the object file (fol
create
linked
example, Helloworld.OBJ
Helloworld.EXE).
Step Execute the program. You should test to detennine whether
it functions properly. lf not, start again with step 1 and make
4
modifications and additions to your source code.
is
to
5.9 Your First C Program
You're probably eager to try your first program in C. To help you
become familiar with your compiter, here's a quick program for you
to work through. You might not understand everything at this point,
but you should get a feel for the process of writing, compiling, and
runningareal Cprogram.
This demonstration uses a program named HELLOWORLD.C,
.which does nothing more than display the words Hello, World! onscreen. This program, a traditional introduction to C programrning,
good one for you to leam. The source code for
HELLOWORLD.C is in Listing5.l. When you type in this listing, you
won't include the line numbers or colons.
is a
Listing 5.1. HELLOWORLD.C.
I
1: #include
2:
3: mainQ
<stdio.F
4:{
5:
6:
7:l
printf("Hello, World!\n");
return 0;
Be sure that you have installed your compiler as specified in the
lnstallation instructions provided with the software. Whether you are
47
working with UNIX, DOS, or any other operating system, make sure
you understand how to use the compiler and editor of your choice.
Once your compiler and editor are ready, follow these steps to
enter, compile, and execute HELLO.C.
5.10 Entering and Compiling HELLOWORLD.C
To enter and compile the HELLOWORLD.C program, follow these
steps:
1. Make active the directory your C programs are in and start
ltour editor. As mentioned previously, any text editor can be
used, but most C cornpilers (such as Borland's Turbo C++
and Microsoft's Visual C/C++) come with an integrated
development environment (lDE) that lets you enter, compile,
and link your programs in one convenient setting. Check the
manuals to see whether your compiler has an IDE available.
2. Use the keyboard to type the HELLOWORLD.C source
code exactly as shown in Listing 5.1. Press Enter at the end
of each line.
3. Save the sour@
HELLOWORLD.C.
code. You should name the file
4. Verify that HELLOWORLD.C is on disk by listing the files
in the directory or folder. You should see HELLOWORLD.C
within this listing.
5. Compile and link HELLOWORLD.C. Execute the
appropriate command specified by your compile/s manuals.
You should get a message stating that there were no e,rors
or warnings.
6. Check the compiler messages. lf you receive no erors or
wamings, everything should be okay.
lf you made an enor typing the progf?ffi, the compiler will
catch it and display an eror message. For example, if )rou
misspelled the word printf as prntf, you would see a
rnessage similar to the following:
Erron undefined symbols:3mtf in HELLOWORLD.c
(HELLOWORLD.OBJ)
7. Go back to step 2 if this or any other error message is
displayed. Open the HELLOWORLD.C file in your editor.
Compare your file's contents carefully with Listing 5.1, make
any necessary corections, and continue with step 3.
48
8. Your first C program should now be compiled and ready to
run. lf you display a directory listing of all files named
HELLOWORLD (with any extension), you should see the
following:
HELLOWORLD.C, the sour@ code file you created with
lrour editor
HELLOWORLD.OBJ or HELLOWORLD.O, which contains
the object code for HELLO.C
HELLOWORLD.EXE, the executable program created when
you compiled ard linked HELLOWORLD.C
9. To exeafie, or run, HELLOWORLD.EXE, simply enter
hello. The message Hello, World! is displayed on-screen.
.&AA
6
OPERATORS AND EXPRESSIONS
Comtent$
6.1 Aritfrrnetic, llnatry, logical, bit-wise, assignment and conditional
oper*tonn
S.2 Relstional Operators
S"$ Lcgical ANO (&&)
S,4 t-ogical CIR {ll}
6.5 Logieal NST {!}
6"S The Conditiomal Sperator
6.7 Btfuise #perators
6.1
Arithmetic, Umary, Logical, Bit-Wise, assignment
and Cond$tfiona! Operators
You will leam about
operator
i.e.
Arithmetic operators,
RelationalOpenators, Logical Operatons, AssignmentOperators,
and
Decrement Operatorc, Conditional Operators,
Bitwise Operators and Special Operators.
Definition of Operators: Operator is symbol which helps the user to
command to do certain mathernatical or logical operation on data
and variable. C has the large amount of operators wtrich has been
classified as.
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. lncrements and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
lncrements
6.1 Arithmetic Operators
All basic operators can be canied out in C language. All
the operators have almost the same meaning as
other
languages. C has two unary mathematical operators and five binary
mathematical operators.
in
50
Arithmetic Operatorc
Operator llleaning
Addition or Unary Plus
Subtraction or Unary Minus
Multiplication
Division
finclude <stdio.h>//include header fi le stdio.h
void main(l lften the compiler the start of the program
t
lnt numbl, numZ, sum, sub, mul, div, mod; / ldeclaration of variables
scanf ("?6d %d* , &numl, &num2); //inputs the operands
sum = numl+numl; lladdition of nurnbers and storing in sum.
printf('\tt Thu sum is = %d', sum); /ldlsplaV the output
sub = numtr-numl; llsubtraction of numbers and storing in sub.
printf('\n Thu difference is = ?6d" , sub); I ldispJaV ttre output
mul = numlf nu m2; /lmultipllcation of numbers and storing jn mul.
print(\n Thu product is =/od", mul); //display the output
div = numUnum2; lldivision of numbers and storing in div.
printf(tn Thu division is =?&", dVl; lftisplay the output
mod = numl%num2; llnwdulus of numbers and storing in mod.
printf(ln Thu nrodulus is =i&o, mod); lldtsplay the output
)
Operatlon
Operator
Gomment
Value of Value of
Sum
before
sum afur
sum = sum *
4
2;
surn = sum /
4
sum = sum 4
+2i
Multiply
Divide
Addition
2;
51
sum = sum 2:
++sunt:
--sum;
sum = sum
olo
3;
Subtraction
lncrement
Decrement
++
Modulus
o/o
4
4
Operator
Symbol
Action
lncrement
++
lncrements the 1*X, X++
operand by one
Decrements the --X, X-operand by one
Decrement
Examples
The increment and decrement operators n be used only with
variables, not with constants. The operation performed is to add
one to or subtract one from the operand. ln other words, the
statements
++3i
-Cl,
are the equivalent of these statements:
a=a + 1l
a=a-1;
C has two unary operators for incrementing and decrementing the
operand. The increment operator ++ adds 1 to its operand; the
lto its
operand. Both
operator -subtracts
increment ++ and decrement-- can be used either as prefix
operators (before the operand: ++a ) or postfix operators (after the
operand: n++ )
A prefix(+*a ) operator first add 1 to operand and then the result is
assigned to the variable on the left
A postfix (a++)operator first assign the value to the vbriable on the
left and then increments the operand
decrement
For an example :
#includecstdio.h>
#includecconio.h>
Void main0
{
int m=10; int n=2oi
printf("m=7od\n",m);
p ri ntf( " n =o/od\n ", n ) ;
pri ntf(" ++m=7od\n", ++m
printf(" n++=%d\n", n++);
printf("m=7od\n",m);
p ri
ntf(
)
m=10
"
=o/od\n ", n ) ;
);
52
Output:
n=20
++6=f I
rl++=!Q
m=11
n=21
6.1.1 lnteger Arithmetic
The arithmetic operation is performed on two whole numbers or
integers that operation is called as integer arithmetic. This operation
always gives an integer as the result. Let x = Tand y = 6 be 2
integer numbers. Then the integer operation leads to the following
results.
x + Y = 13
x-Y=
x*Y=48
Xo/oY=1
xlY=1
ln integer division the fractional part is truncated.
6.1.2 Floating point arithmetic
When an arithmetic operation is preformed on two real numbers or
fraction numbenr such an operation is called floating point
arithmetic. The floating point results can be truncated according to
the properties requirement. The remainder operator is not
applicable for floating point arithmetic operands.
Let x = 14,0 and y = 4.0 then
x + y = 18.0
x-Y=10.0
x*Y=56.0
xlY=3.50
6.1.3 fiilixed mode arithmetic
When one of the operand is real and other is an integer and if the
arithmetic operation is canied out on these 2 operands then it is
called as mixed mode arithmetic. lf any one operand is of real type
then the result will always be real thus 15110;0 = 1.5
53
6.1
.4Precedence of oPerators
Level
Operator
6
7
I
I
Left-to-right
reference
(pointers
stgn
unary
operator
type cEtsting
pointer-tomember
(tvBd
r ->*
Muttipliq[lye
"lo/o
+-
Additive
shift
<><=>=
10
11
&
12
13
14
15
16
A
II
&&
?:
=
17
Scope
*= l= o/o= += -=
))= ((= t=
Leftto-right
Right-to-left
indirection and
+5
Grouping
dynamic-cast
static_cast
Postfix
reinterpre[-cast
const_cast
typeid
++ - ! sizeof unary (prefix)
new delete
*&
DescriptioQ
A3
Relational
EqualitY
bitwise AND
bitwise XOR
bitwise OR
loqical AND
loqical OR
Conditional
Risht-to-left
Left-to-right
Left-to-nght
Left-to-right
Left-to-right
Lefi-to-right
Left-to-righ!
Lefi-to-right
Left{o-right
Leftto-nghL_
Left-to-right
Left-to-right
Riqht-to-left
Assignment
Right-to-left
Comma
Left-to-right
l-
l-
18
6.2 Relational OPerators
There are six relation operators in C' They are
These six operators are used to form logical expressions, which
represent conditions that are either true or false. The resulting
expressions will be of type integer, since true is represented by the
integer value 1 and false is represented by the value 0'
54
Here there are some examples:
5) ll evaluates to false.
4) tl evaluates to true.
2) ll evaluates to true.
6) ll evaluates to true.
5) /l evaluates to false.
(7 ==
(5 >
(3 !=
(6 >=
(5 <
Operator Maaning
is less than
<=
is less than or equal
to
is greater than
of course, instead of using only
numeric constants, we can use
any valid expression, including
)=
is
greater than or
equal to
is equal to
variables.
Suppose that a=2, b=3 and c=6,
!=
is not equal to
5)
(a ==
l/ evaluates to false since a is not equal to S.
(a*b :>= c) ll evaluates to true since (2*g >= 6) is true.
(b+4 > a*c) ll evaluates to false since (3+4 , 2"0) is false.
((b=2) -= a) ll evaluates to true.
Be careful! The operato; = (or equal sign) is not the same as the
operator == (two equal signs), the first one is an assignment
operator (assigns the value at its right to the variable at its left) and
the other one (==) is the equality operator that cornpares whether
both expressions in the two sides of it are equal to each other.
Thus, in the last expression ((b=2) == a), we first assigned the
value 2 to b and then we compared it to a, that also stores the
value 2, so the result of the operation is true.
C's logical operators.
C has the following
logical operators, they compare
logical and relational expressions.
Operator Meaning
&&
Logical AND
il
Logical OR
Logical NOT
or
evaluate
55
6.3 Logical and (&&)
The logical operators && and ll are used wtren evaluating two
exprressions to obtain a single relational result. The
operator && conesponds with Boolean logical operation AND. Thls
operation results true if both its tvvo operands are true, and false
othenrise.
operator &&
The following panel shorrs the resutt
evaluating
the
expression
&&
of
b:
&A OPERATOR
a
a&&b
true true true
irue Felce false
lala
IruE lalse
[alse lalse lalse
This operator is used to evaluate 2 conditions or expresslons with
ralatircnal operators simultaneously. lf both the expressions to the
left and to the right of the logical operator is true then the whole
compound expression is true.
.,
Example
a>b&&x==10
The expression to the left is a > b and that on the right is x ==
10 the whole expression is true only if boft xpressions are tnre
i.e., if a is greater than b and x is equal to 10.
6.4 Logical Or (fl)
The operator fl conesponds with Boolean logical operation
OR.
This operation results true if either one of its tuuo openands is true,
thus being false only when both operands are false themselves,
Here are the possible results of a ll b:
ll oPERATOR
all
b
true true true
lrue false lrus
false true true
a
56
talselfalseffalse
The logical OR is used to combine 2 expressions or the condition
evaluates to true if any one of the 2 expressions is true.
Example
a<mll
a.n
The expression evaluates to true if any one of them is true or if both
of them are true. lt evaluates to true if a is less than either m or n
and when a is less than both m and n.
or example:
(5 == 5) && (3 , 6) ) /l evaluates to false ( true && false
2 (5 == 5) ll (3 > 6) ) // evaluates to true ( true ll false ).
1
).
6.5 Logical Not (!)
The Operator ! is the C operator to perform the Boolean operation
NOT, it has only one operand, located at its right, and the only thing
that it does is to inverse the value of it, producing false if its
operand is true and true if its operand is false. Basically, it retums
the opposite Boolean value 6f evaluating its operand. For example:
5)
4)
ltrue
5 ==
ll evaluates to false because the expression at its
2 5 == 5) is true.
ll evaluates to true because (6 .= 4) would be false.
3 !(6 <=
ll evaluates to false
4
lt evaluates to true.
1
lfalse
6.5.1 Compound Assignment Operators
The compound assignment operators consist of a binary operator
and the simple assignment operator. They per{orm the operation of
the binary operator on both operands and store the result of that
operation into the left operand, which must be a modifiable value.
s7
nm nt Operators
Operator Meaning
Store the value of the seeond operand in the object
*l=
o/e
+=
((=
))=
$=
A3
l=
specified by the first operancl (simple assiqnment).
Multiply the value of the first operand by the value of
the second operand; store the result in the object
specified by the first operane!.
Divide the value of the first operand by the value of the
second operand; store the result ln the object specified
by the first operand.
Take modulus of the first operand specified by the
value of the second operand; store the result in the
obiect specified bv the first operand,
Add the value of the second operand to the value of the
first operand; store the result in the objeot specified by
the first operand.
Subtract the value of the second operand from the
value of the first operand; store the result in the object
specified by the first operand.
Shift the value of the first operand left the number of
bits specified by the value of the second operand; store
the result in the obiect specified bv the first operand.
Shift the value of the first operand right the number of
bits specified by the value of the second operand; store
the result in the obiect specified by the first operand.
Obtain the bitwise AND of the first and second
operands; store the result in the object specified by the
first operand.
Obtain the bitwise exclusive OR of the first and second
operands; store the result in the object specified by the
first operand
Obtain the bitwise inclusive OR of the first and second
operands; store the result in the object specified by the
first operand.
you want to increase the value of x by 5, or, in other words, add 5 to
x and assign the result to x. You could write
x=x+5i
Using a compound assignment operator, which you can think of as
a shorthand method of assignment, you would write
x+=5;
ln more general notation, the compound assignment operators
have the following syntax (where op represents a binary operator):
exPl oP= exP7
This is equivalent to writing
expl = oxpl op exp2;
58
When we want to modiff the value of a variable by performing an
operation on the value currently stored in that variable we can use
CIompound assignment operators:
+= increase;ivalue = value + increase;i
ivatue
.+..*.?,......-.:**i
f*,..-*.*.-.--*..*.--*----+*
la=a-5;
rB-=5,
__-i
iffi.**__Fl
iplse-:-q$:-: l*
:"(.'qlil*J},i
rp:rse: arigs
and the same for all other operators. For example:
6.6 The Conditional Operator
C has one last operator which we haven't seen yet. lt's called the
conditional or "ternary" or ?: operator, and in action it looks
something like this:
The syntax of the conditional operator is
el?e2.e3
and what happens is that el is evaluated, and if it's true then e2 is
evaluated and becomes the result of the expression,
othenruise e3 is evaluated and becomes the result of the
expression. ln other words, the conditional expression is sort of
an iflelse statement buried inside of an expression.
#includecstdio.h>
int
mainfl{
int a,b;
printf("Enter a Number:");
scanf("o/od",&a);
printf("\n Enter Znd Number:");
SCanf("o/od", &b);
a>b ? printf("A is big") : printf("B is Big");
return 0;
)
59
A classic iflelse would use this syntax:
int max;
if(a>b)
t
max = 8,
)
else
t
max = b;
)
Using the ternary or conditional operator ? : we could shorten this
to:
int max;
max=(a>b)?a:b;
It means that first (a > b) is evaluatd; if it is true, the value of
expression would be the value given before : (the value between ?
and :), otherwise, it would be the value after :
6.7 Bih,vise Operatorc
One of C's pourcrful features is a set of bit'manipuflation operators"
These permit the progmmrner to access and manipulate individual
bits within a piee of data.
)perator
&
I
A
Meaning
One's Complement Operator
Risht Shift Operator
Left Shift Operator
Bitwise AND
Bitwise OR
Bitwise XOR Operator
//A program to demonstrate the working of bitwise operators.
#includecstdio.h>
int main0
int n = 149;
int res;
res=n&0017;
printf('The resultant of Bit wise AND operator is : o/od \t'1", res);
res=n10017;
printf('The resultant of Bit wise OR operator is : Vod \n", res);
res = n && 0017; // this is logical AND . Truth or false will be output
printf('The resultant of Logical AND operator is : o/od \n", res );
res = n ll 0017; ll this is logical OR . Truth or false will be output
printf('The resuJtant of Logical OR operator is : Yod \n", res):
res=n^0017;
60
printf("The resultant of Exclusive operator is : Yod \n", res);
res = n <<2;
printf("The resultant of shift left ( by 2 bits) operator is : 7od \n", res);
res = n >>2:
printf("The resultant of shift right ( by 2 bits) operator is : 7od \n',
res);
fes = -n;
printf("The resultant of NOT operator is : 7od \n", res);
return 0;
)
The resultant of Bit wise AND operator is : 5
The resultant of Bit wise OR operator is : 159
The resultant of Loglcal AND operator is : 1
The resuitiant of Logical OR operator is : 1
The resultant of Exclusive operator is : 154
The resultant of shift left ( by 2 bits) operator is : 576
The resultant of shift right( by 2 bits) operator is : 36
The resultant of NOT operator is : -150
6.7,', - Tilde operator . one's complement Operator. This is a
unary operator, used to find one's
complement of a given number .
n = 1 00 1 0 1 0 I =149(decimal)
-r E 0 1 I 0 1 0 1 0 = bitwise complement
6.7.2 Right Shift Operator
operands. lt shifts each bit in its left operand to the right. The
number of places the bits are shifted depends on the number
following the operator (i.e. its right operand).
Thus, ch >> 4 would shift all bits in ch four places to the right.
Similarly, ch >> 6 tlrould shlft all bits 6 places to the right.
o
E
U'
a
J
.!r
II
7 6'5
0
3 2 1 O
I o I 1 I
,,$
\\tu\\rr\
t I
Right arithmetic
shift
1
\
Note that as the bits are shifted to the right, blanks are created on
the left. These blanks must be filled somehow. They are always
filled with zeros.
61
position , bits of a binary
number is equal to division of the given number with 2.
6.7.3 Right
Shift. Shifting right by one
n=1
0010000=144(decimal)
01001000=7l(decimal)
n>> 1
n>>2
0 0 1 0 0 1 0 0 = 36(decirnal)
6.7.4 Left Shift Operator
This is similar to the right shift operator, the only difference being
that the bits are shifted to the left, and for each bit shifted, a 0 is
added to the right of the number
Us
=:r
?riSl,:10
toloi*itioirrrlt
i.*,l-*.i..r..I
c,L-+a-.i..
t.- d
ldlulrlolrlrlrla'. -or
Left arithmetic shift
G.7.5 << Left Shift. Shifting left by one position , bits of
number is equal to multiplying the number with 2.
n=1
a binary
0010000=144(decimal)
1 0 0 1 0 00 00 = 288(decimal)
n<< 1
n<<2 1001000000=576
6.7.6 Bitwise AND Operator
This operator is represented as &. Remember it is different than
&&, the logical AND operator. The & operator operates on tulo
operands. While oper:ating upon these two operands they are
compared on a bit-by-bit basis. Hence both the operands must be
of the same type (either char or int). The second operand is often
called an AND mask.
The & operator operates on a pair of bits to yield a resuJtant bit.
Resultant bit
o
0
0
Second bit
0
First bit
0
0
The example given below shows more clearly what happens while
ANDing one operand with another.
This operand when ANDed bitwise
1
With this operand yields
1
62
this result
1
6.7,7 & Bit wise AJ{D. Used for maskirg operation. For example if
you want to mask first four bits of a number'n' , then we will mask n
with a number whose last four bits are 1s. i.e. 0001 111. ln Octal
representation it is O17(Remember an octal number starts with 0
and a hexa number stails with 0x)
00 1 0 1 0 1 =149(decimal)
0 0 0 O 1 1 'l 1 = 017(octal)
n=1
&
resultn=00000101
Note that last four bits are 0101 and are unaffected i.e. they are fust
reproduce in the result , whereas , the left four bits are all 0s. i.e.
they are masked.
Bitwlse OR Operator
Another important bitwise operator is the OR operator which is
repnesented as l. The rules that go\nem the value of the resulting bit
obtained after ORing of two bits is shown in the truth table below.
First bit
0
0
Second bit
0
Resultant bit
0
Using the Truth table confirm the result obtained on ORing the two
operands as shown below.
11010000 Original bit pattem
0000011 1 OR mask
11010111 Resulting bit pattem
Xbn Operator
The XOR operator is represented as A and is also called an
Exclusive OR Operator. The OR operator retums 1, wten any one
of the two bits or both the bits are 1, whereas XOR retums 1 only if
one of the tuo bits is 1.
6.7.8 Bitwise
63
The truth trable for the XOR openator is given below
Firct bit
0
Second bit
0
Resultant bit
XOR operator is used to toggle a bit ON or OFF. A number XORed
with another number twice gives the original number
6.7.9 ^ Blt wlse Excluslve OR Exclusive OR also known as odd
function , produces output
1 , when both bits are not same (odd) and produces a 0 when both
bits are same.
1 001 01 01 =149(decimal)
n=
A3
00000101=005(octal)
result n = 1 0 0 1 0 0 0 0 =149(decimal)
.&.r..t
7
CONTROL STATEMENTS
Contents
7.1 The while Statement
7.2The for Statement
7.3 Nested loops
7.4 The if Statement
7.5 The else Clause
7.6 The if Statement
7.7 The switch Statement
7.8 The break Statement
7.9 The continue Statement
7 .1A The goto Statement
7.11 The Comma Operator
While, do-while, for statements, nested loops, if else, switch, break,
Continue, and goto statements, cornma operators
7.1 The While Statement
ln most programming languages, a while loop is a contnol flow
statement that allows code to be executed repeatedly based on a
given Boolean condition i.e True or Flase. The while loop can be
consider as a repeation of if statement.
The while statement consists of a block of code or series of
lnstruction or staement and a condition. The condition is firstly
evaluated, and if the condition is true, the code within the block of
code is executed. This execution
statement repeated until
unless the condition becomes false. Because while loops check the
condition before the block is executed, the control structure is often
also known as a pre-test loop.
of
1.
2.
The expression condition is evaluated.
It condition evaluates to false (that is, zero), the execution of
while statement terminates, and contrcl of execution is passes
to the first statement following stafement
.lf condition evaluates to true (that is, nonzero), the execution of
while statement follows, the series of instruction or statement is
executed unless the mndition becomes false.
Execution retums to step 1
Figure. The operation of a while statement.
WHILE inup-test at beginning
66
)
Output125
The do,.,whlle Loop
The "do while loop" is almost the same as the while loop. The "do
while loop' has the following form:
i---
ioot
; ) while ( condition );
L---
-----i
i
:
-----.,
Notice that the condition is tested at the end of the block instead of
the beginning, so the block of statement will be executed at least
once. lf the condition is true, The cursor jump back to the beginning
of the bbck and execute the block of statement again. A do..while
loop is almost same as a while loop except that the loop body is
permitted to execute at least once.
A while loop says "Loop while the condition is true, and execute
this block of @de',
A do... while loop says'Execute this block of code, and then
continue to loop while the condition is true".
Figure
The operation of a do..,while loop.
The statements associated with a do...while loop arie always
executed at least once. This is because the test condition is
evaluated at the end, instead' of the beginning, of the loop. ln
opposite, for loops and while loops evaluate the test condition at the
beginning of the loop, so the associated statements are not
executed at all ,if the test condition is initially false.
Exarnple
#includecstdio.h>
int main$
(
int counter, howmuch;
scanf("o/d", &howmuch);
counter = 0l
do
{
counter++;
printf("7od\n", counter);
)
while ( counter < howmuch);
retum 0;
)
67
ln this Program , the block of statement is executed at least onCs
that is counter variable and printfQ statement is exected at one time
here the counter variable is initialized to zero at declaration of the
variable, when the instruction is flows inside do while loops than the
counter variable is increment by one and followed by the printf0
statement is executed i.e it will prints the value of the counter
variable is 1 to once, then the while condition is checked whether
the condition is fatse or true , if the condition is falqe, the loop will
terminated, only the value at beginning will print at once , if the
condition is true , the control jump back at beginning of loop , the
block of statement of an do..while untill unless the codition
becomes false.
Be aware that you must put a trailing semi-colon after the while in
the above example. A naiVe programmer always forget to put a
trailing semicolon after the while statement it consider that do while
loop must be terminated with a semicolon (the other loops should
not be terminated with a semicolon, adding to the confusion).
Notice that this loop will execute once, because it automatically
executes before checking the condition.
7.2 The For Statement
for ( initialization_expression ; loop-cond ition ; i ncrement-expression){
// statements
)
For loops are divided in to three parts that is separated by semi'
colons in control block of the for loop.
initialization_expressrbn is executed before
The frsf part
execution of the loop starts. This is part is used to initialize a
counter for the number of loop iterations. You can initialize a
counter for the loop in this Part.
The second pan is used to check the condition, depend upon the
continues until unless the
condition execution of the loop
loop_condition is false. This expression is checked at the beginning
of each loop iteration.
The increment_expression, is usually used to increment the loop
counter. This is executed at the end of each loop iteration
is
is
#include <stdio.h>
void mainQ{
// using for loop statement
int max = 5l
inti=0:
fo(i =0; icmax;i++X
printf("%d\n", i);
This programm indicates that the max variable is initialized to 5 Integer
value, he for loop contains the initialized expression i.e. 1 = 0, the
loop_condition i.e. i<max is checked, the first iteration checked 0<5, the
condition is true the block of statements is executed, then the loop counter
variable is increment by one i.e. i++, the i variable becomes 1 (i=1), then
the condition is checked (i<1), the condition is true, the block of statement
is executed, the counter variable is incremented by 2(i=i+1) the for loop is
iterated until unless the condition becomes false(5<5), the condition is
checked, the condition is false and loops is terminated, the control is come
out of loops, the statement after the for loop is executed.
7.3 Nested Loops
Nested for statements
The loop within the loop is called a nested loops. These types of loops are
used to create matrix. Any loop can contain a number of loop statements
in iteself. If we are using loop within loop that is called nested loop. In this
the outler loop is used for counting number of rows and the internal loop is
used for counting number of columns.
69
printf ("\n");
)
getch ( );
)
OUTPUT OF THIS PROGRAM IS
t**t
***t
::::
7.3.1 Nested Loops
The term nesled loop refers to a loop that is contained within
another loop. You have seen examples of some nested statements.
C places no limitations on the nesting of loops, except that each
inner loop must be enclosed completely in the outer loop; you can't
have overlapping loops. Thus, the following is not allowed:
for( count = 1;count < 100; count++)
{
do
t
/* the do...while loop */
*/
) /" end of for loop
)while (x != 0);
lf the do...while loop is placed entirely in the for loop, there is no
problem:
for (count = 1; count < 100; count++)
t
do
/* the do...while loop
)while (x != 0);
*/
) /' end of for loop
*/
When you use nested loops, remember that changes made in the
inner loop might affect the outer loop as well. Note, however, that
the inner loop might be independent from any variables in the outer
loop; in this example, they are not. ln the previous example, if the
inner do...while loop modifies the value of count, the number of
times the outer for loop executes is affected.
7.4The lf Statement
This allows us to control the flow of the program, lets the
statements it make decisions on what code to execute, it is
important for the programmer point of view. The if statement allows
70
you to control if a program enters a section of code or not based on
whether a given condition is true or false. One of the important
aspect of the tuncllons ffiat is tlre if statement allows the program
to select an ac'tion based upon frte use/s input. For example, by
using an if statement to Check a user entered password, your
program can decide whether a user is allowed acoess to the
prw,am.
The form of an if statement ls as follows:
it (expression)
statement
expressrbn would be ambinatiqt of relational opentor or the
logical or arthemtic evaluates to true, sfafemenf is executed. lf
expression evaluates to false, statenpnt is not executed.
It
A block of stratement can be used anywhere a single statement can
be used. Therefore, you could write an
if statement as folloua:
fi (exgessrbn)
{
statenpntl;
statement2;
additional code goes here
statementni
)
'/
LIST.C: Demonstrates lf statements.
*/
/* Demonstrates the use of if statements
#nclude <stdio.h>
maln0
(
int x, y;
/' lnput the tu,o values ttl be tested '/
printf(lnlnput an integer value for x ');
scanf('7od", *)t
print("\nlnput an integer value for y: ");
scanf('%d', &y);
*/
/* Test values and print result
if (x == Y;
printf("x is equal to y\n");
71
if(xrY)
printf('x is greater than y\n");
if(x.Y)
print('x is smaller than y\n');
retum 0;
)
lnput an integer value for x 100
lnput an integer value for y: 10
x is greater than y
lnput an integer value br x 10
lnput an integer value for y: 100
x is smaller than y
lnput an integer value for x 10
lnput an integer value for y: 10
x is equal to y
7.5 The Else Glause
if..else syntax is as follorrc:
if(condition){
expr_setl;
)
else {
expr_set2;
)
lf given condition is evaluated as TRUE then expr_setl will get
executed.
lf given condition is evaluated as FALSE (rrct TRUE), expr_set2 will
get executed
if..else example
The program for find out large number of tvrro ftom given input:
includecstdio.h>
int main(fl
int x,y
printffEnter value for x :');
scan("o/od',&r);
printf('Enter value for y :");
scanf('7od',&y);
if(x>yX
print('X ls large number - o/od\n',x);
)
else{
printf(Y is large number - 96d\n',y);
)
72
retum 0;
)
Output:
Enter value for x :20
Enter value for y: 10
X is large nurnber- 20
7.6 The If Statement
Form
tf( expressron )
statementl:
nexlsfatement
if statement as an simplest form. lf expresslbn is true, statementl
is executed.lt expression is not true, statemenf/ is not executed.
Form 2
if( expression )
statementl;
else
statement2;
nexf_sfatement
This is the most @mmon form of the if statement. lf expression is
true, statemenfl is executed; othenrise, sfafement2 is executed.
.Form 3
if( expressionl )
statementl:
else if( expression2
sfatement2;
else
statement3;
nexf_sfatement
This is a called as nested if. lf the first expression is evaluated and
expressionl is true, statementl is executed before the program
continues with the nexf_sfatement. lf the first expression is not
true(i.e ), the second expression, expression2, is checked. lf the
first expression is not true, and the second is true, statemenf2 is
executed. lf both expressions are false, statemenf3 is executed.
Only one of the three statements is executed.
Following example of nested if statement.
void main
int result;
Printf('Enter the percentage of students\n");
1e $S
d"+
Scanf("%d",result);
if (result >= 75)
printf("Passed : Grade A\n.i;
else if (result >= 60)
printf("Passed : Grade B\n");
else if (result >= 45)
printf("Passed: Grade C\n-')i
else
printf("Failed\n");
)
Out put
Enter the percentage of students
80
Passed: Grade A
7.7 The Switch Staternent
Switch case statements are applicairle for lcng if ststeraents that
compare a variable to several 'integrci" v;ill;+s* i"irl1uEtr*.li'- values fir"e
simply values that can be expressed a$ &ru lnt*ger, sr.lch i3$ :he
value-of a char). The basic format for using switch case is outlined
below.
The vatue of the variable given into switch is compared to the value
following each of the cases, and when one value matches tPte value
of the viriable, the computer continues executing the prog!'arn fnom
that point.
switch(<variable>){
case this-value:
Code to execute if <variable> == this-value
break;
case that-value:
Code to execute if <variable> == that-value
break;
ln this stateme nt, expression is any expression that evaluates to an
.
integer value: type long, int, or
The switch statement evaluates expression and compffirBs the
value against the templates following each case label, and then *ne
of the following happens:
lf a match is found between expression and one of the templates,
execution is transferred to the statement that follows the case label.
lf no match is found, execution is transferred- to the statement
fotlowing the optional default label.
char.
74
lf no match is found and there is default label is executed,
executbn passes to the first statement following the switch
statemenfs closirqg brace.
marn{){
int a;
printf('Vr Enter a value:');
scanf('ol0d",&a);
surtitch(a)
{
case 1:
printf(" \nThis is case 1");
break;
case 2:
printf(" lnThis is case 2");
break;
case 3:
printf(" \nThis is case 3");
break;
default:
printf("\n Defau lt
)
)
**")
Output:
Enter a value:2
This is case 2
Example
switch( letter )
case'A:
casg'a':
printf( "You entered A" );
break;
case'B':
case'b':
printf('You entered B");
::""*'
iefault:
printf( "l don't have a case for a/od',letter );
)
7.8 The Break Statement
The break statement terminates the execution of the nearest
enclosing do, for, Bwltch, or while statement in which it appears.
Control passes to the statement that follours the terminated
stiatement.
75
Syntax
jump-statement
break;
The break statement is frequently used to terminate the processing
of a parthular case within a switch statement. Lack of an enclosing
iterative or switch statement generates an eror.
Within nested statements, the break statement terminates only the
do, for, switch, or while staternent that immediately encloses it.
You can use a return or goto statement to transfer control
elsewhere out of the nested structure.
With loops, break can be used to force an early exit from the loop,
or to implement a loop with a test to exit in the middle of the loop
body. A break within a loop should always be protected within an if
statement which provides the test to control the exit condition.
#includecstdio.h>
int rnain$
{
int i;
i=0;
while(i<20l
t
i++;
if ( i== 10)
break;
)
retum 0;
ln the example above, the while loop will run, 8s long i is smaller
then twenty. ln the while loop there is an if statement that states
that if i equals ten the while loop must stop (break).
7.9 The Gontinue Statement
with ,,@ntinue;" it is possible to skip the rest of the @mmands in
the cunent loop and start from the top again. (the loop variable
must stitl be incrcmented). Take a look at the example below:
#includecstdio.h>
int main$
int i;
i=0;
while ( i< 20 )
76
{
i++:
continue;
printf("Nothing to see\n");
)
retum 0;
)
ln the example above, the printf function is never called because of
the "continue;".
7,10 The Goto Statement
The goto statement is a jump statement which jumps from one
point to another point within a function. The goto statement is
marked by label statement. Label statement can be used
anywhere in the function above or below the goto statement. You
can see in the given example, we want to display the numbers
from 0 to 9. For this, we have defined the label staternent loop
above the goto statement. The given program declares a variable
n initialized to 0. The n++ increments the value of n till the loop
reaches 10. Then on declaring the goto statement, it will jumps to
the label statement and prints the value of n.
#include <stdio.h>
#include <conio.h>
int rnain$ {
intn=0;
loop:
printf("\nolod", n);
n++,
if (n<10) {
goto loop;
)
getch0;
return 0;
)
7.11 The. Gomma Operator
The comma operator (,) works almost like the semicolon ; that
separates one C statement from another. You can separate almost
any kind of C statment from another with a comma operator. The
comma-separated expressions are evaluated from left to right and
the value of the whole comma-separated sequence is the value of
the rightmost expresgion in the sequence. Cqnsider the following
code example.
77
#include <stdio.h>
/* To shorten example, not using argp *l
int main (int argc, char *argvu, ctrar *envp[)
t
int a, b, c, d;
a=(b=2,c=3,d=4);
ntf ( "a = 7od \n b = Yod\nc= o/od\n d =%d\ n',
o, b, c,d);
retum 0;
pri
The value of (b = 2, c = 3, d = 4l is 4 because the value of its
rightmost sub-expression, d = 4, is 4. The value of a is thus also 4.
When run, this example prints out the following text:
a=4
b=2
c=3
aaa
STORAGE TYPES
Contents
8.0 Objectives
8.1 lntroduction
8.2 Storage Classes
in C
8.2.1 Automatic
8.2.2 Extemal
8.2.3 Register
8.2,4 Static
& Further Reading
References
8.3
8.4 Review Questions
8.0 Objectives
After reading lhis clrapter you will be able to answer the following:
1. What is meant by storage classes in C?
2. What are the different types of storage
classes and how to
use them?
8.1 lntroduction
We have already seen how variables are declared. Every variable
has a name and Upe associated with it. But that's not entirely true.
A variable also has a STORAGE CLASS. We haven't used storage
class so far while declaring variables and still managed to get along
is because if a variables storage class is not specified while
declaration a default storage class is assumed by the compiler. ln
the sections to come we will see what does a storage class mean,
its types and try to understand them.
8.2 Storage Glasses ln C
A Storage Class is a speclfier that tells the compiler how to
store a variable.
Every variable declared in C has a physical location inside
the computer vvhere its value is stored. Therc are h,rc
possible locations where the value could be stored The
memory or the CPU registers.
It is the Storage Class that tells where the variables value
has to be stored.
The Storage Class indicates the following things about a
variable:
1. The locatlon where the variable would be stored.
79
2. The default initial value of the variable if it is not
specified.
The Scope of the variable
The lifetime of the variable.
The Storage Class Specifieni supported by C are:
3.
4.
The general form of a variable declaration that uses Storage
is shown here:
stora ge_specifie r type va r_na me ;
8.2.1 Automatic
.
.
Local variables are automatic by default.
A variable declared automatic has the fol
No
Property
Description
2
3
4
Keyword
Storaoe Location
Default lnitial Value
Scope
auto
Memory
Garbase Value
Life
Local
auto int i = 10j ;
{
auto int i = 11 ;
auto int i = 12 ;
printf ( 1n7od o/od', ij ) ;
printf ( 1n%d olod',
)
printf ( 1n%d Vod',
getch0;
12 862
11 862
10 862
which the
variable is deflned
Terminates wlnen the contnol exits the
block in which the variable is defined
Consider the following Example:
#includecstdio.h>
#includecconio.h>
void main( )
to the block in
ij
ij ) ;
80
program the variables i and j have been
declared as aurtomatic by using the kerytord auto.
The variable i is initialized to 10 for the first time while the
variable j is not initialized at all.
The output shows a value 862 when the value of variable j is
printed on the screen which is a garbage value and is
ln the above
unpredictable.
The variable i has been declared and initialized three times.
The compiler treats each i differently as they are declared in
different blocks.
lnside the innermost block the value of variable i is found to
be 3 as the control exits this block the value of variable i is
found to be 2 and as it exits this block the value of variable i
becomes 1.
From the above statement it becomes clear that the scope of
I is local to the btock in which it is defined. The mornent the
control bomes out of the block in which the variable is
defined, the variable and its value is lost.
9.2.2 Externat
o External variables have a global scope.
a
They are declared outside all functions and are available
whenever needed.
o A variable declared extemal has the following Properties:
No Propefty
1
2
3
KeWvord
Storage Location
lnitial
Value
Scope
Default
Description
extem
Mqnory
Zero
Global (lt is available throughout the
program)
Terminates only when the program
terminates
The keyword extern is used to indicate to the compiler that
the object (variable) is declared elsewhere in the program.
Conqlder the follgwing example:
include<stdio.h>
#includecconio.h>
void main( )
Life
extem int x,y;
printf( "x =olod & y=o/od',x,
getch0;
)
int x=l0;
// x is declared not defined
y) I
/l x is global, external
8l
tn the above example, variables x & y are declared extemal hence
they are globa!. Variable x is initialized outside the main$
Ttr# sr*put shows that value of y is zero, since y is not initialized its
defr.ruit value is printed which is zero since its declared extem.
Th* varis*tli* x is shown to have the value 10 because it is extern
and tetls the eumplier that its value is declared elsewhere.
&.P.3 ffi*g$ster
st The keywmrd regi*t*r tells the compiler to store the variable
im the pro*essors regieter rather than the regular memory.
The aentrat procs$$rng unit (CPU) of a computer contains a
few data ster#Se locations called registerc. lt is the register
'
.
.
urhere the artaisl operations on data are performed. To
menipulated Elata, the CPU transfers the data from memory
to the regi*ters performs the operrations on it and transfers it
back to the ft:ernory.
The benefit cf storing a variable in a register is that it is faster
to manipulate the data it contains.
A variable dectared with keyword register has the following
Properties:
No
Property
Description
reqister
Keyword
Storage Location Reqister inside CPU
Default lnitial Garbage Value
Value
Local to the block in which the variable
Scope
is defined
Terminates when the control exits the
Life
block in Which the variable is defined
2
3
4
5
lf a variable is used multiple times in a program it is better
to
declare its storage class as register. Ex. Loop Counters
#include <stdio.h>
#include <conio.h>
void main(
register int i
for(i=1;i<=5;i++1
printf
getch0;
('\n%d",i);
ln the above program, although variable i is declared to be
stored in register it is not sure if that would happen. This is
because the number of registers available with any CPU are
82
very limited and they may atready be busy in doing some
task.
ln such a situation the compiler would treat the variable to be
of auto storage class.
8.2-4 Static
Variables declared as static are permanent variables within
their own function or file and maintain their values between
calls.
A variabte declared with keyword static has the following
Properties:
No
Property
Description
static
Memory
zero
Keyword
Storage Location
Default lnitial
Value
Scope
Life
2
3
Local to the bhck in which the variable
is defined
Terminates when the control exits the
program
Consider the Following example:
#includecstdio.h>
#includecconio.h>
void add0;
void main( )
add( ) ;
add( );
add( );
getch0;
)
void add( )
static int x = 11
printf("%d\n",x);
x=x+1i
Output:
11
12
13
E3
o
o
o
ln the above program, variable x is declared in the function
definition of add$ and is static.
A static variable is initialized only once and exists till the
program terminates.
Since x is static, after belng initialized to 11 it does not loose
its value hence the second call to add() prints the value 12
and third call to add$ prints the value 13.
Comparison between Storage Classes ln C:
Erternal
Register
Static
No
Property
Automatic
Deecrlption
Keyword
auto
extem
register
slatic
Slorage
Location
Memory
Memory
Register
inside CPU
Memory
Default
lnilial
Value
Garbage Value
Zero
Garbage
Value
zero
Scope
Local
Local to the
Loca!
lo the block Global (lt
in whkt
the
variable is defined
is
avalhble
blod(
throghout
which
the program)
in
the
variable
is
defined
5
Life
Tenninates when
the control exits
he block in which
the variable is
defined
Terminales
when
the program
only
terminates
Terminates
when
lhe
control
exits the
block in
which
the
variable is
delined
to
blod(
the
in
whidr
the
variable is
defined
Terminates
the
control exits
the prograrn
when
84
8.3 References & Further Reading
1, Let us C - Yashwant Kanetlcar
2. C The Complete Referenc,$ - Herbert Schildt
3. The C Programming Language - Brian W. Kernighan
4,
Dennis M. Ritchie.
Teach yourself C in 21 days
Jones
and
Peter Aitken and Bradley L.
8.4 Review Questions
1. What is meant by Storage classes in C?
2. Whet is special about storing variables in CPU registers?
3.
How is it done?
What is the difference between static and auto
.3.4*
?'
FUNCTIONS
ContenB
9.1 Objectives
9.2 lntroduction
9.3 What are functions?
9.4 TyPes of Functions
9.5 Defining and accessing functions
9.6 Function Prototypes
9.7 Passing arguments
9.8 Recursion
9.9 Static functions
9.10 References & Further Reading
9.11
Review Questions
After reading this chapter you will be able to answer the
following:
1.' What is a function and why use it?
2. How do we define and use a function?
3. What is a function PrototYpe?
4. How to pass alguments to a function?
5. Types of functions : Built-in(library functions) & User defined
6. Static Functions
9.2 lntroduction
*
*
*
Usually programs are much larger than the programs that we
have seen so far.
programs manageable and less complicated,
To make large
-broken
down into subprograms. These
they are
subprograms are called functions.
The baiic principle of Functions is DIWDE AND COTI OUER.
Using functions we can divide a larger task into smaller
subtasks that are manageable.
9.3 What Are Functions?
We can understand functions by answering the following
questions:
1. What is a function?
2. Why use a function?
3. How does a function work?
E6
1.
What ls a function?
1.
A function is a self contained blocf of statements.
A function is self contained in the sense it may have its own
variables and constants
2, It is designed to do a well defined task.
Since a function is
part of
larger program (i.e. a
subprogram) it has a particular job to perform.
3. It has a unique name.
A function can be used (invoked) by the name given to it.
4. It rnay have retum type
A function invoked by a calling program may or may not
retum a value to it. ln case it retums a value the functions
retum type is the same as the variables data type.
5. A program that has a function should have the following
three things in it:
a. Function Declaration or Prototype
b. Function Call
which are discussed in a later part
SillflT,j;#on,
2. Why use a function? (Advantages of uslng a functlon)
1.
Functions are a structured way to programming. Larger
programs get divided into smaller manageable units.
2. tf a specific block of statements has to be executed multiple
times (for example. taking contact details from 100 users), it
can be written as a function and that function can be
repeatedly executed. This implies that redundancy in writing
the same piece of code multiple times is rcrnoved.
3.
a large program into smaller subprograms using
functions help to easily code them and reduces the
Dividing
debugging effort.
3.
How does a function work?
Consider the following:
87
The program to the hfi
lglmain()
{
;;;;;il;-c
contains three
the mainfl function,
seond is fundionl$
functions. First one is
and third is function2$.
any
prqgram begins with the
main
execution
func{lon. Unless there is
decision
looping
construct the execuUon
of the program prooeeds
in a serlal mannor.
ln the diagram to the left,
the prcgram execution
begins with main(), all
statements get
executed.
The execution of
of
or
the
A functlon gets called
when the
function
name ls followed by a
cemlcoton.
A function is
delined
name
lg
when funcUon
followed by a pair of
briacss in whlch one or
more statements may
be present
When the system encounters a call to functionl$ the prqram
control jumps outside the mainQ func{ion to execute the block of
statements named functionl0 shown by arrow numberl.
Once the lasfi statement in functionlQ is executed the program
control is again transfened to main$ and the immediate statement
after main ls executed, shown by anow number2.
When ths system encounters a call to functlcn2Q the program
control jurnps outside the main$ function again to execute fu block
of statements named function2$ shown by anow number 3.
Once the last statement in func{ion2Q is executed the program
control is again transfened to mainQ arul the immedlate statement
after main ls executed, shown by anow number 4.
88
9.4 Types Of Functions
Functions are of two types
1
Built-in functions
2. User defined functions
3.
Built-in Functions
. These are also called Standard Library Functions. As the
name suggests it is a Library of functions. These are the
functions that are already present .i.e. predefined in the
.
.
o
system.
They have been written, cornpiled and placed in libraries
under header files.
We can use these functions in our programs by just
specifying the name of the header files that contains the
function of our interest.
C language is collection of various inbuilt functions. lf you
have written a program in C then it is evident that you hav.e
used C's inbuilt functions. Example: printf, scanf, clrscr, etc
all are C's inbuilt functions. You cannot imagine a C program
without function.
Math Library Functions
C++ provides a library of math related functions called Math
Library Functions.
These functions are placed in header file <math.h> and it
contains 59 functions.
The following is a snapshot of the help menu of Turbo C++
the list of available built-in functions under
<math.h>.
displaying
iil'ff:iliTiF'ffi"ii**5Au'ril"*ftu't
""
tr,r*if i
:t:
*'*t*.*..*,
*H$;ii*ft'{t
I{,e
A{*T.t?ffi$fii*: f;t 6i,,
l l}
f,umtlm
a[s
atar. rtanl
unhl
-cals,
msh, eos&I
fln*r* flmrl
lqpot, lrypt!
lsfl, IryI
Mf , m$f I
p*lB* po*l8l
iqrt, iErtt
r,l{etr11,,.
f*+6fiet
fl
as***
as*rr* *stnl
*stnl
{r:Bffir
d:Bffir *g**I
*g**I
atsT*, et*r*t
, *atotd
e*i I.
*o$r wt
ffit I l
*tgr mryl , ' f*be, fch*t
fmd.'f,ffiI,, ' ' frcq1. froffl
Icfrs
r l{etg, I.IISI
lryl$. ' Iogt$l I,, ,,, matMr; .tmtlmrrl
polg, ffitgl .'' ,i 1ml*' , IXDETI
*in, stnl .
efnl* str*I
*tof
try , fd-I
tutf ttl
Example ; Print Square Root of Numbers from 1 to 10
fl
f,
fl
f,
I
f,
f,
E
!
f,
8g
'-'r-'r
,r**r*****rfi*r*r**i*****t*i*****t******t********t**t**a*t**a*t*tti*'*'ttt*
I
Description: Program to display the use of meth library functions
*trr***t*t:t*****fir*i***tt*tr*r*r****r**r**ea**ti*{ht***t*t***atar*ati*iirfi/
#include <stdio.h>
#includecconio.h>
#includecmath.h>
void main$
t
int i;
printf("Number \t Square Root\n');
fo(i=1 ;i<=10;i++;
{
printf("%d\t
7ofln", i,sqrtt
ili:
getch0;
Output
Number
1
2
3
4
s
6
7
8
I
10
Square Piooi
1.000000
1.414214
1 .7320513
2.000000
2.236068
2.44949
2.645751
2.282427
3.000000
3.162278
This program prints the square roots of the numbers
a
a
through 10. The value of variable i frorn the loop counter is
passed to sqrt(i).
i is called the parameter passed to function sqrt.
Each time the expression sqrt(x)is evaluated in the for loop,
the sqrt$ function is executed for the value of i passed to itIts actual code is hidden away within the Standard G++
Library.
Following are some of the functions available under the
header file <math.h> and their uses:
90
'lrig***rr+lti{ ,u$ttrcins
1
l;;
.j.::l
,;1::1iii1r' {.1::ii:,,'
.;l,I'. ii..,;.-
rit: {',.;:r' \11:-::i;r1r 1i::'t'l
i l.:liri,r:i:., tii'r'.i!:'i:,tr'.lllliilj
?
iirilti ii,ir'!
.i i,:1if!,.:)r, ,7i Il,.rti$
i.i.1*31i;11,,i?: r*r, 'i.:tr; ]t,,i:i
,.;,y,;r,i,'1. ,;i, .. !:.."'t'.. r.'i,t.;1r :l'i
r
;ri
.:!:;:
;;t';
.rl ,t'
..:,^-.,,
i.';.r':r,:!i..li..ri,' : it .jr:i:: ',yrii, I!,;ii
..ijr::.i.:i.
1r.,;1.131:i
ir'ir "i.i j; ir.'ttli
F*lc*r
{u:lc:lie.,r'is
1.113'iir't : 'llirl i:i;'i'.i
iatgl1li.,:n' ...;:}.:{}'tlir-:l i;:.'l r. li,rlti
.li.,t': lii
ij*,
,._*i
I{*6rrrdin6 ,;t}f*f:{tte ui+l'ie
ilil
"i$ri{
r+Br};fid+r i*rrttiriryr
ilt,i;r'3illi,-.,i.." li,llir:ti;.:r*)
i r-riilr '1, l,'',11,, ,' ,.s.:it l,' i,t:;'i
j il.;r':r'iirii:i I
,i:lri.i!,.1 ifr-l'r;a ;lIi,
;j:
t.,ii>
-..-.*
ji*.":i
,,
{.r.r;11tr1,,riili.ri::}ii':,,1.:r..ri
:i
i'r t:i
f tit
{ i'..1':a
1,.rir.. tl.
liaiirl,',
il;ti,;!; ir,, r'
i{
r.ilti'rl,tli iii.:r'ri iirll\i
;,ili,f.Ii{' ii;.ri}ilir'l ir,:iiir',itii)iiii'.itrii.itrii
t' l{ii,{lii't: i
i.
tii.ii-';
if:l'
i;+
rli
{i(Jti ;
i,ll. ri
i.,!ir,'{:.
!r
i,ri.,.ts rl
:ll
t,
t;',1;
l':tr
;1
ii
!:1i
iir:l ii*tri
1:
i,.'g'.. ;iir;
ri
;r'Il;iir'1.ii rrlr! tt:tli:1,:! il'.:ti"
User defined functlons
These are the functions other than the Standard Library Functions.
These are created by the users and the user has the flexibility to
choose the function name, the statements that will be executed, the
parameters that witl be passed to the user & the return type of the
function.
Any program using functions will have the following three necessary
things:
1. Function prototype or functlon declaration
It is the name of the function along with its return-type and
parameter list.
2.
Functlon call
Any function name inside the mainQ followed by semicolon
(;) is a Function Call.
3. Functlon Detinitlon
A function name.followed by a pair of parenthesis $ including
one or rnore statements.
ln case of built-in functions, function prototype and function
definition are not nece$6ry, they have been already declared
and defined in the libraries.
91
9,4
Greatitrg, Defining And Accesslng Functions
General form of a C function definition:
<retum type, FunctionName (Argumentl, Argument2,
Argurnent3. .. . . .)
{
Statementl;
Statemenl4;
Statement3;
Example
int square(int x)
x'x;
rettim
square of x:
ll
The function retums the square of the integer passed to it.
Thus the call'squarc(3) wouH retum 9.
Consider the following example:
The first line of the above example return-type functionl$;
is called the function prototype or function declaration. lt
is used to declare the funstion to the cornpiler.
This statement is always written outside(before) the main$.
The statement functionl() along with the statements in the
parenthesis shown below is called the function definition.
The function definition contains the instructions to be
executed when the function is called.
functionl0
s2
Function definition is always done outside the mainQ.
The statement functionl$; inside main$ is a func'tion catl.
A function gets called when the function name is follouted by
a semicolon.
When this statement functionl0; is executed the program
control gets transferred to the the function definition of
tunction1$ which is outside the main(). All the statements
inside functionl$ are executed and then the control gets
transfened to the next statement after the function call.
Note:
From this point onwards Function prototype & Function definition
means prototype & definition for a userdefined function, Since only
userdefined functions have function prototype/ declaration and
function definition.
Function Definition:
o . A function is defined when function name is followed by a
pair of bnaces in which one or more statements may be
o
o
prcsent.
A function definition has 2 parts
1. Function head
2. Function Body
Example :
int square(int x)
{
retum
ll
square of x:
x*x;
The function rcturns the square of the integer passed to it.
Thus the call square(3) would retum g.
1.
Functlon Head
The syntax fqllhgtread_d a function is
return-type
namefparameterlist)
The above statement tells the compiler three thlngs about
the function:
Name of the function
ii. lts return-type i.e type of value to be retumed
by the function
iii. lts parameter list.
i.
ln the elomple shoyyn above the tread of the functbn is:
93
int square(int x
i. square is the narne of the function,
ii. int is the type of value that the function
is
retumirq to main$
and the parameter list (int x) contains a single
parameter that is passed to the function square
by the main0
2. Function Body
iii.
o
o
The body of a function is the block of code that follouts its
head.
lt contains the code that performs the function's action.
lt includes the return staternent that specifies the value
that the function sends back to the place where it was
called usually rnain$.
The body of the square function is
x*x;
retum
square of x:
ll
retums
Local Variables in Functions
.
o
A variable can be declared inside a function definition,
but it vrould be only local to the function. lt cannot be
used anywhere outside the function.
They exist only when the funcUon is executing. The
variables in the parameter list of function definition are
called formal arguments and they are also local variables
and exist only for the duration of the function execution.
. The general syntax of a
function prototype
is
returntype function-name
list);
The above statement tells the compiler three things about
the function:
1. Return-type i.e type of value to be retumed by the
l
function
2. Name of the function
3. Parameter list. (the number of parameters the function
will receive and their data-types)
A Function Prototype is temrinated by a semicolon
94
Example: The complete program for finding sguare
of
program is written as follows:
/*ttil******rrttS*it******tt*****i*tt****ti*l*****trHttrt**iatt
Description: Program to display the square of a number entered by
user.
r****ttt****.1
.**r****.....1?.:i}.o.!.ril1t.r..tlH.:3ff .rrl.'JH*i?l,pl"J"tvpe)
#include <stdio.h>
#include<conio.h>
int square(int
Prototype
int main()
m);
ll
Function
int num=O, sqr=0;
printf("\nEnter number to find its Square\t ");
scanf('%d',&num);
printf('\nnumber = olod',num);
sgFsquare(num);
// Function call
printf("\nSquare of %d = 7od",num,sqr);
getch0;
return 0;
x)
(x'x);
int square(int
{
retum
// Function definition
// retums square of
x:
Output:
First Run
Enter number to find its Square 5
Squareof 5 =25
Second Run
Enter number to find its Square
of8=64
The stiatement below is called functlon declaration or
frrnctlon prototype.
int
int m);
The function prototype ln the program above also contains
the same:
1. The function would return an lnteger value, hence, its
retum type ls int
.,
2, The name of the function is
o
squaru
95
3. The function receives one parameter of type integer
from the place where it is called from i.e. main$
Following are some examples of valid function declaration:
float area(float
length,
float breadth);
perimeter(float
side1, float side2);
float
lnside the function declaration each variable must
be
declared independently, the fotlowing dectaration is invalid
float sum_of_angle(int anglel, int
angle2,
);
The parameter names are optional in a function declaration,
they are simply dummy variables.
float sum
of anqle(int.
int. int
The above is valid since a Function prototype expects only
the number of pararneters and its data-types from the
parameter list.
For every function to be used there should be a function
prototype. During program execution when the compiler
encounters a function call, it first matches the prototype
having the same number and type of arguments and then
calls the appropriate function for execution.
A function prototype is different
it(function call) does not indicate
from a function call,
the return-type of the
function.
Actual & Formal arguments: ln the program above, the
statement
sqF square(num);
The variable num being passed to the function square is
called actual parameter & and the variable x in the function
head of function square is called formal parameter.
96
Passlns Arguments
9.7
There are trrrc ways in which we can pass atguments to a
function' theY
are:
1.
2,
Pass by varue
Pass by reference
Pass by value
The examples that we have seen above are all examples of
passing arguments by value. ln this method of calling a
function uve pass the value of variables to the function as
parameters.
Such function calls are called 'call by value'. ln call by value
the changes made to the formal parameters do not change
the actual parameters.
The called function creates a new set of variables and copies
the values of actual arguments into formal arguments.
The function does not have ascess to the varlables declared
in the calling program and can only work on the copies of
values i.e. the furmal arguments.
Example: Consider the following program for swapping of
two numbers.
o
.
ai**ir*tt*tt*t*ffi
rrhtrfi
tt*ffi
Htat*fr
rr*r*ritrtH*ttft
rliiafr ffi ttttffi
P.:.'.:lpi3glr.s.3T.l?.:N?p..*"..:31[".:.?1.Y.".j]g*:*'
ra****tt**r**/
#include <stdio.h>
#include <@nio.h>
void
void main$
swap(int,int);
//prototype
int a,b;
clrscfl;
printf('Please enter 2 positive integers:\t ");
scanf('7d o/od",&a, &b);
printf("\n Values before swapping ar (in main 0):\n ');
printf(' a = olod \t b = 7od\n",a,b);
swap(a,b);
llcall by value, actual arguments
printf(ln Values after swapping are (in ma.in 0):\n ');
printf(" a=olod \tb= 7od\n",a,b);
getch0;
)
void swap(int m,int
n)
//definition, formal arguments
int temp;
printf("\n Values before swapping are (in swapQ):\n ");
m=o/od \tn= 7od\n",m,n
97
temP =
rli
m=n:
n E"temp;
prinff{tr Values after $ rapping are (in srap 0):\n ");
prinfft* m = 96d \t n
7od\n',m,n);
Output:
F$rst Run
Please enter 2 positive integens: 1 4
Values before swapping are (in main 0):
b=4
a=l
Values before swapping are (in swap 0):
n=4
m=1
are (in swap 0):
swapping
after
Values
n=1
m=4
are (in main 0):
swapping
after
Values
b=4
a=1
Second Run
Please enter 2 positive integers: 11 51
Values beforE swapping are (in main 0):
a=11 b=51
Values before swapping are (in swap ()):
n = 51
m = 11
Values after swapping ars (in swap 0):
n = 11
m = 51
Values after swapping are (in main 0):
a=11 b=51
The above program swaps the values of two lntegers taken
by the user using a swap function that performs the
swapping task.
The swap function accepts 2 integers from the main function
as shown in the prototYPe.
Before we do the swapping, we simply print the values of
variables a & b so that ure may know the state of the
variables (i.e. they undergo a change or not).
The statement swap(a,b); is an example of call by value
where the function swap is called by value. Here variables a
& b are astual parameters and their values are passed while
invoking the swap function.
98
The function definition of swapO; shows int m and int llr
these are called formal parameters and they receive the
.
.
values of variables a & b passed from rnainQ.
lnside swap$, before we swap the values of the variables m
&n we print their vatues on the screen. Once the swapping is
done the values of the variables m & n are again printed on
the screen.
When the controt retums back to the main function, the
values of variables a & b are again printed on the screen.
From the above program the following could be noted:
1. The values of actual parameters (a & b) are passed to
the formal parameters(m &n).
2. Any change done to the formal parameters do not
change the actual arguments as shown in the output.
Iffi
Pass by Reference
o
o
o
.
The pass by value mechanism is
read only way of
communication with the function and it does not change the
values of the actual arguments. lt makes the functions more
self-contained, protecting them against accidental side
effects.
But sometimes there may be situations where a function may
need to change the value of the parameter passed to it. This
is done by using the call by reference mechanism.
To pass a parameter by reference instead of by vatue, we
simply append an ampersand to the parameter being passed
in the function call and and append a pointer symbol (.) for
the corresponding variable in the function prototype and
function call.
Now the argument is read-write instead of read-ofllY and
any change.to the local variable inside the function will cause
the same change to the argument that was passed to it.
When parameters are passed by reference, the address of
the actual argument is passed to the formal argument
instead of its value hence making the actual arguments
available for maniPulation.
For ex.
99
#include <stdio.h>
#include <conio,h>
void main$
{
int a,'b;
clrscr0;
a=3;
b=&a;
printf("\n a = o/od", o);
printf("\n b = o/od", b):
printf("\n &a = o/od" , &a);
printf("\n *b = %d', *b);
-(&a));
Printf("\n 6 ='(&a)=7od",
*b=4;
printf("\n a = o/od", a):
getch0;
Output
a=3
b = 62424
&a = 62424
'b=3
5=*(&o)=3
a=4
Example:
int a = 2Oa
int&b=a:
variable
cout<<a<<endl<<cout<<b;
value of 2O
llb is a
reference
//will both print
a=a+1 0;
cout<<b:
llwill print 30
Example : Program for gwapping for two numbers by passlng
parameters by referencc (call by reference)
1f,o
l*fi
ri*ft
*l*!t*trt** ******rtrl****ttttailttittaaitttitHti*r
*ttit$a***lttlt*
Description: Program to swap the values of two numbors using call
by reference
ttt.*ar*rtrfiftffi**/r
include <stdio.h>
#include <conio.h>
void swap(int*,int*);
void main0
//prototypo
int a,b;
clrscr();
printf("Please enter 2 positive integers:\t ");
sca nf("%d7od',&a,&b);
printf('\n values before swapping are (in main 0):\n ');
printf(" a = olod \t b = %d\n",a,b);
llcall by reference,
swap(&a,&b);
actual arguments
printf(ln Values after swapping are (ln maln 0):\n ");
printf(" a=o/od \tb= 7od\n",a,b);
getch0;
)
void swap(int'm,int *n)
arguments
//dbfinitlon,
t
int temp;
printf("\n Values before swapping are (in swap$):\n .);
printf(' rn = o/od \t n = o/od\n','m,tn);
temp - *m;
*m *n;
=
*n temp;
=
printf('\n Values after ewapping ar (ln swap 0):\n ');
printf(" m = o/"d \t n = 7od\no,*ffi ,*n):
Output;
Please enter 2 posftlve lntegers; 1 4
Values before swapplng are (in main 0):
Values before swapping are (ln swap 0):
m=1
!=4
Values after swapplng are (in swap 0):
Values after swapping are (ln main 0):
The above program can be summarized aa
101
lrth*rt rall ir nr
callto
t*r*p{}
r*ai*{}
$i,rl*S{i
V*lu** * ii$.{ srvap$inp.
nrstn{}
r-ml
bEi
Valueo
q^f
&
b assigned
m&n
to
Values of s, b and rn . n are
interrhanged
The following can be concluded:
9;7
.
Using reference variable any changes made to the formal
parameters are reflected on the actual parameters.
Recursion
ln C , a recursive function is one which calls itself. lt is
function being executed where one of the instructions is to
"repeat the process". lt sounds similar to a loop.
o
Ex.
I void iecursive$;
void mainQ
t
recursive0;
)
void recursive$
t
recursive0;
l:_
The above function will logically run in an infinite loop.
l/llarning of r.sing recursive function
Recursive function must have at least one exit condition that
can be satisfied. Othenrise, the recursive function will call
itself repeat until the runtime stack overflowg,
Example : Program to find factorial of a number
fiz
ttt
1itfifitti*rtt*trt*'r$tt'rairttair*tt*ttttttfftttOftaaattmatffttttttoat
Qescrlptlon: Program to dlsplay factorial of
u0er udng racuGlon
a number entered by
*qrltit*tt.attftff*..atart*tt.r*tittttr*tt*titttttfftrtttt.ilttlttatrtftftrr/
#lnclUde *stdls,h>
#inglude (eonlo,h>
int facterlal(int);
rcid main0
t
lnt number,fact;
prlntf('Pleam enter a poeltlve lnteger: ');
sc6nf(nYed',&numbr);
fact{aeto ria l( n u mbe r);
prlntf("%d factorlal is; %d\nn,number, fsct);
getch0;
)
int factorial(int number)
(
int temp;
if(numUer <= 1)
(
retUm 1;
)
else
temp = number' faslorlal(number - 1);
)
retum temp;
outPut'
,rrct Run
Pleace enter a positlve
4 factorlal ls: 24
integer: 4
Please enter a positlve
factorlal is: 1
integer:
Sccond Run
A static functlon is a function with a koyword static in front of it.
Once
function
ls declared static that function can only
Eccessed from the same filo.
be
103
Function definitions are ofren compiled lndependently ln separate
files. Wth such kind of declaration a stratic funcfion wlll glve an
eror.
Ex. This is another of writing functions. Ths deflnition lg separate
from the flle containing rnain$.
llfile 1: square.c
#include <stdio.h>
ffndude<@nio.h>
#includecsquare.h>
int main$
{
int num-O, sqr0;
printf('\nEnter number to find its Square\t ");
scanf("o/od',&num);
prlntf(lnnumber = o/od', num);
sqFsguare(num);
olod
printf('\nSquare of
getch0;
return 0;
// Fundlon call
= %d',num,sqr);
llfile 2: square.h
#ifndef _SOUARE _H_
//inclusion
guard
#define JOUARE_H_
int square(int x); //prototype
#endif//_SQUARE_H#include "souare.h'
llfile3: squarelib.c
#include osquare.h"
int square(int x)
{
return (x*x);
// Function definition
// retums square of
x:
The above program would run fine until uue declare the funstion
square static in file2.
Since sguare would be static, invoking square in
an error.
filel
vuould give
Advantages of separate function compltatlon ane:
a. lnformation hiding
b. Modularization of program structurc enabling separate
compiling and testing.
c. lf a function
change
is
to be changed pailially or totally the
limited to the file contiain the func{ion
needs
implementation only.
104
Roferences & Further Readin
Let us C by Yashwant Kanetkar
Mastering C by Venugopal, Prasad
- TMH
9.11 Review Questions
l.
What is a function?
Explain types of functions?
Explain function prototyping.
Explain user-defined functions
Explain built-in functions with examples
Explaln Call by value
Explain Call by reference
2.
3.
4.
5.
6.
7,
8. Explain the dffierence between call by value and call by
reference
9. Write short notes on:
a. lnline functions
b. Recursion
10, Write a program to swap two numbers without using a third
variable using call by reference.
aa*
10
AKffiAY$
Contents
10.01 Objectives
14.O2 lntroduction
10.03 Concept of an anay
10.04 Declaration of One dirnensional anay
10.05 lnitialization of one dimensional anay
't0.06 Character anays
10.07 Accsssing anray elements
10.08 Passing arays to a function
i.
Passing individual anay elernentm
Passing an entire array
10.09 Multi dimensional arrays.
10.10 References & Further Reading
10.11 Review Questions
ii.
10.1 Objectives
After reading this chapter yo{.! wfll be abie
i*
answer the
folbwing:
1. What is an anay and its types?
2. How do we declare and initialize an anay?
3. What is an character anay?
4. How to pass individual anay elements and entire anays
as argurnents to a function?
5. How to work with Multidimensional anays?
10.2 lntroduction
Arrays is how C provides a way to group elements of similar naturc
or datatype to be more precise. Arrays are collection of similar
elements that have the same name, are stored in consecutive
memory locations and are accessed using index or subscript.
10.3 Concept of Array:
.
.
.
An anay is a collection of similar elements.
An anay is a Linear & homogeneous data structure. Linear
data structure stores its individual elements in sequential
order in the memory, homogeneous rneans all the individual
elements are of the same data type,
The array has one name and the individual elements are
accessed using subscript or index. A subscript'in C starts at
0(zero).
106
Armyr ars of two types:
1.
One dirnensiortal arrays
arrays
2. Multidlmonslonal
10.4 Declaration Of An Array(One Dimenslonal)
Anays must be declared before they can be used in the
program.
declanation is as:
vari$le
type
ex:
it is the type of data to be stored in the
array
variablenarne
lengthofarray
it ls the narne given to the anay
it is the size of the affay, lndicates the
number of elements the
can
hold
int roll_no[5J
affay
roll_no[1]
Here, int specifies the type of the variable ard the word
roll_no specifies the name of the variable.
The number 5 tells how many elements of the type int will be
in our anay, This number is often called the 'dimension' of
the anay. The bracket I !(square brackets ) tells the compiler
that we are dealing with an arl.ay.
The above example shows a set of five roll numbers. The
computer allocates 5 memory locations and are numbered
starting from O(zero) to 4(four).
Any item in the array can be accessed through its index, and
it can be accessed anywhere frorn within the prograrn.
10,5 InitialiZqtion Of Arrays
There are two ways to initialize anayrs:
1. lnitialize every anay element one by one:
arrayname[indexl = value;
roll-no[O] = 1;
roll_no[1|= 2;
roll_no[2J = 3;
roll_no[3] = 4;
roll_no[4J = 5;
2.
lnitialize the entire aray during declaration:
Syntax:
107
type arryanamefiengthJ = {list of values separated by
commal;
Ex:
int rollno[S] = tl, 2,3,4, 5];
The values must be enclosed inside 0 (curly brackets) and
terminated by a semicolon.
roll-no[0] roll_no[1J roll_no[2J roll-no[3J
roll-no[4]
10.6 Declaration & lnitialization Of Character Arrayq
A character array is a collection of characters terminated by
'\0' or null.
char name[S] = {'l', 'D' , 'O' , 'L' , '\0'};
Example
The anay gets stored in the memory as:
'Dt
'l
name[OJ
.L'
'o'
name[l] name[2] name[3]
'\0'
narne[4J
The '\0' is implicitly appended by the compiler when it sees a
character arrdy.
Symbolic constants in array declaration:
Symbolic constants may also be used to speciff the size or
length of an anay.
Example:
#define qty 5
declares item as an anay of 5 elements
int
o
.
item[qtyJ;
Two things worth noticing:
1, The size of anay is optional during anay declaration.
Example:
int roll-no[ = {2,3, 4l;
is same as
int roll_no[3] = {2, a, O}t
2. The array elements are initialized to zero by default if not
explicitly initialized.
Example:
int roll_no[s] = t1, 2,3,1i
roll-no[O] =
roll-no[l] = 2:
rolt-no[2] = 3;
roll-no[3J = 0;
roll-no[4] = 0;
li
10.7 Accessing Elementb Of An Array
108
o
.
.
o
.
ln C Language, arays start at position 0. The elements of
the anay occupy adjacent locations in memory.
Any item in the array can be accessed through its index, and
it can be accessed anywhere from within the program.
Hence, roll_no[3] refers to fourth element and not the third.
Here 3 is the value of index.
Example:
The following program below will declare an anay of five
integers, accept its values from the user and print all the
elements of the anay.
#includecstdio.h>
#includecconio.h>
void mainQ
int in!_array [5];
printf("\n Enter any five numbers : \n');
/* To get values all the elements of the anay from the user
for (int i=0;i<5;i++)
t
sca nf(' %d", &
in[-ana y[il);
)
P To print all the elements of the affay
printf('\n The five numbers are : \n")t
for (int i=0;i<5;i++)
printf("%d\n", int_array[i] );
)
getch0;
)
Enter any five numbers
12 13 14 15 16
The five numbers are :
12
13
14
15
16
{09
10.8 To Passing Array Elements A Function
Anay elements can be passed to a function in tvuo ways
1. Gall by value
#includecstdio.h>
#includecconio.h>
*);
void display(int
void main$
t
int i;
int r[]={1,2,3,4,5,6, 7};
fo(i =0; i<7;i++)
display(&rtil);
getch0;
)
*m)
void display (int
t
printf("%d".*tn)t
1234567
ln the above program, the afiay elements are passed to the
function one at a time and are printed on the screen. The
value of the arruy element being passed gets copied into the
formal argument.
2. Catl by reference
#includecstdio.h>
#includecconio.h>
void display(int');
void main$
(
int i;
int rU{1 ,2,3,4t:
fo(i =O; i<S;i++)
display(&rlil);
getch$;
)
void display (int .m)
printf("%d",*m):
):
110'
1234567
ln the above program, the address of the array element is
passed to the formal argument.
Passing entire afiay to a function
o An entire array can be passed to a function by simply giving
the name of the array as a parameter in the function call.
o This way we send the base address (i.e the address of the
first element of the array) and hence the entire array.
llinclrrde<stdio.h>
llincludecconio.h>
void d isplay(i rrt mll);
void main( )
{
int roll_no[5];
printf ( "\rrEntcr5 integcrs\n " ) ;
for(int i=0;i<5;i++)
(
sca ntl"Yud ", & rol l_n o
IiI);
l
display( roll_no);
gctch0;
)
void display( int mll
t
for(int i-O;i<5;i++)
(
printf l "Y"d ",mIil];
l
l
Outout
l-
11234567 _
__
Multidimensional Arra
.
.
Arrays may have more than one dimensions. Such arrays
with more than one dimension are called Multidimensional
Arrays.
--1
A Two dimensional aray will need 2 subscripts or indexes, l
three dimensional array will need 3 subscripts or indexes
and so on,
Two Dimensional (2D) Array:
o A Two Dimensional afiay could be thought of as a table with
rows or columns or as a matrix of size m x n.
111
Sirnilar to a matrix a 2D anay will need 2 subscripts, one for
row and the other one for column.
S
,J;
arryanameI
Example :
int tablet4ltsl;
will create an away table that has 4 elements and each
element is an arrary of 5 integers or in simple words it
creates an arary of size 4 X 5 that can hold altogether 20
integers as shown below:
Col 2
Col 3
Col 4
table[OJ[2J
table[0][3]
table[0][4]
table[1][0I
table[of[l]
table[l][1]
table[l][21
table[l][3]
rable[l][4]
Row 2
rabre[2][0I
lable[2][1J
table[2][2I
table[2][3]
table[2][4J
Row 3
table[3J[0J
table[3][11
lable[3][2]
table[3][3I
table[3I[4I
Col 0
Col
Bow 0
table[0]01
How
lnitialization of 2D arays
There are two ways to initialize arrays:
'1. lnitialize every anay element one by one:
indexl[index] = value;
int table[4][5];
table[O][0]
table[0][1]
table[Ol[z]
table[Ol[3]
2.
1;
=
=
=
table[1J[OJ =
2i
3;
4,
5; and so on
lnitialize the entire aray during declaration:
S
atry aname Ii nd exJ Ii nd ex]
{list
Ex:
int
table[3][S]
of
values
= {1, 2, 3,
4,
5,6,7,8,9,1 0,1 1,1 2,13,14,1 5);
The values must be enclosed inside
brackets) and terminated by a semicolon.
Or
int table[3][S] = {
{1, 2,3, 4, 5},
t6,7,8,9,1 0),
tl 1 ,12,13,14,15)
(curly
112
);
Note that the values for a specific tow ane
enclosed within their own pair of curly
brackets.
The values must be enclosed inside
0 (curly
brackets) and terminated by a semicolon.
Accessing the elements of a 2D aray:
As in One Dimensional anays, any item in a 2D afiay can be
accessed through its indices, and it can be accessed
anyrhere from within the Program.
The following program below will declare a 2D array of size 2
X 3, accept its values from the user and print all the
elements of the anay.
//Accessing the elements ol a 2D anay:
#inctudecstdio.h>
#include<conio.h>
void main$
{
int int_anay [2][3];
int i,l;
printf("Vr Enter values tor 2 x 3 anay : \n");
To get values all the elements of the array from the user
for (i=0;i<2;i++)
{
for $=0j<3J++1
t
sca nf(' %d
",
&i nl_a
ray[i]
[jJ
);
)
)
/. To print all the elements of the anay
printf("\n The 2 X 3 anay elements are are : \n");
for (i=0;i<2;i++)
{
for 6=gi<3i++1
scanf("%d', &int-aray[i]fl
)
printf(1n');
)
getch0;
)
Output
);
113
Snter values lor 2 X 3 anay:
df
.$
l44
ira
F
los
xBai
3 arrffiy etarnents &rc :
rhe-* X
I Ttle
r2sz
it4#6
--stxample*:
Write a prsgram to add fwo matrices of size 3 X 3 and store the
result in a thid matrix. Use arays and take the values from user.
l,-1".
#includecstdio,h>
#includecconio,h>
void main$
{
int a[3][3], b[3][3], c[3][3];
int ij;
tlTo get values all the elements of the arays from the user
printf(ln Enter values for First 3 x 3 array : \n");
for (i=0;i<3;i++1
{
for fi=0i<3i++1
t
sca nf('olod., &a [i] [il
)
)
printf(ln Enter values for Second 3 x 3 array : \n");
for (i=0;i<3;i++)
for (1=9i<3j++;
(
scanf('%d", & b[iJ[iJ );
)
ll
Add elements of both alrays
for (i=0;i<3;++)
for 6=6i<3i++;
ctiltil=alilffi+blilUl;
)
)
ll To print the elements of the thi.rd anqy
114
printf(h The result of matrix addition is : h");
for (i=0;i<3;i++;
for 6=gi<3i++1
printf('Yod ",clilUl);
printf("\n");
getch0;
)
Enter values
for First
Enter values
for Second
111111111
3 X 3 array:
3 X 3 array:
111111111
The result of Matrix addition is
222
222
10.10 Refe,rences & Further ReadilLg
1. Let us C by Yashwant Kanetkar
2. Mastering C by Venugopal, Prasad - TMH
3. C The Complete Referenc - Herbert Schildt
4. The C Programming Language - Brian W. Kernighan
and Dennis M. Ritchie.
5. Teach yourself C in 21 days Peter Aitken and
Bradley L. Jones
10.1
o
.
o
.
Review Questions
Deftne arays. How to initialize l-D arrays?
How to pass individu al anay elements to a function?
How to pass entire arrays as arguments to a function?
How to work with Multidimensional an:ays?
..r**
11
STRINGS
Contents
11.0 Objectives
11.1 lntroduction
11,2 Strings
11.2.1 Defining strings
11.2.2 tnitializing Strings
11.2.3 Printing Strings to screen
11.2.4 Reading Strings from screen
11.2.5 Using getsQ and puts$
11.2.6 Oper:ations on strings.
11.3 References & Fuilher Reading
I 1.0 Objectives
Afier reading this chapter you will be able to:
1. Create and initialize strings
2. Print strings on the screen and read strings
from
screen
3. Manipulate strings using Standard String Library
Functions
11.1 lntroduction
The previous chapter on anays presented knowledge
on anays. The cunent chapter deals with Strings wttich are a
special type of anay. This chapter introduces strings and
then shows how to use them and manipulate them.
11.2 Strings
11.2.1 Definition of String
o
o
.
A String is an character array.
A character anay is a collection of characters terminated by
'\0' or null.
Example :
char name[SJ;
The above statement declares a string called name that can
taka up to 5 characters. lt can be indexed just as a regular
array as well.
11.2.2 lnitializing String
116
To initialize our name string from above to store the name IDOL,
char name[5] = {'l', 'D' , 'O' , 'L' , '\0'};
The anay gets stored in the memory as:
name[0J
namellJ
name[2J
name[3J
name[41
The '\0' is implicitly appended by the compiler when it sees a
character arrav.
OR
char narne[S; = flIDOL']t
Note: initializing a string is same as with any array. However
we also need to surround the string with quotes.
11.2,3 Printing Strings to the Screen
When we write strings to the terminal, we use a file stream
known as stdout.
%s is used to print a string on the screen. To print a string
from a variable:
printf('Name: %s", name);
IDOL
11.2.4 Readlng Strings from the screen
. When we read a string from the screen we read from a file
stream known as stdin.
scanf("7os", &name);
Following
is a detailed example for reading and writlng
values to/from string on/from screen:
#include <stdio.h>
#include <conio.h>
void mainfi
t
char fname[10J;
lname[10];
",h"r
printf("\nPlease type first name:\n");
scan(i%so', fname);
printf("\nPlease type last name:\n");
scanf('olos", lname);
printf("Your name is: %s %s\n", fname, lname);
getch0;
)
Output:
117
Please type first name:
Gabbar
Please type last name:
Singh
Your name is: Gabbar Singh
11.2.5 gets & puts function
o
The gets0 & putsO can be used to read and write
strings as well
.
The following code is self explanatory:
#includecstdio.h>
#includecconio.h>
#includecstrlng.h>
void main$
(
char name[10J;
printf("enter your name:\n');
gets(name);
printf("\nThe name you entered is : .
puts(name);
);
getchO;
enter your name:
IDOL
The name you entered is : IDOL
.
.
The difference in using gets0 is that it allows you
to store multiword string separated by comma.
puts$ can display only one string at a time and
printing
after
the string it places the cursor on the next line
unlike printf.
11.2.6 Operation on Strings:
.
To operate on Strings, C compiler has a large set
of useful string handling library functions called as Standard
Library String Functions available under the header file
<string.h>
The
commonly used functions
and
their
descriptions are as follows:
strcat
stmcat
Appends one strirlg at the end of another
Appends first
n characters of a string at the end of
{18
strcpy
strncpy
strcrnp
stmcrnp
another
Copies a string into another
Copies first n characters of one string into another
Compares two strings
Compares first n characters of two strings
Compares two strings without regard
strcrnpi
stricmp
stmicm
p
strdup
strchr
stnchr
strstr
strset
stmset
stnev
to case ("i'
denotes that this function ignores case)
Compares two strings without regard to case (identical
to strcmpi)
Compares first n characters of two strings without
regard to case
Duplicates a string
Finds first occurence of a given character in a string
Finds last occurrence of a given character in a string
Finds first occurence of a given string in another strinq
Sets all characters of string to a given character
Sets first n characters of a string to a given character
Reverses
11,2.6.1 Length of a Strlng
We use the strlen function to get the length of a string minus the
null
character.
int strlen(
Syn
Example:
char fname[3O] = {"|DOL"};
int length = strlen(fname);
This vl'ould set length to 3.
'l 1,2,6.2 Concatenation of Strings
The strcat function
nds one stri
Syntax: st
to another.
The first string gets th second string appended to it. So for
example to print a full name frorn a first and last name string we
could do the following:
char fname[3OJ = {"Gabbar"};
char lname[30J = {"Singh"};
strcat(fname, lname)
orintf("%s',ftrame);
The output would be 'Gabbar Singh'
11
.2.6.3 Gompare Two Sti ings
We have the strcmp function to determine if two strings are the
same.
Syntax:
int strcmp(
1, string2);
119
The retum value indicates the relation between two strings.
If they are equal strcmp retums 0.
if stringl is less than string2, the value will be negative.
if stringl is greater than string2, the value will be positive. "
Example:
int d;
d= strcmp(fname, lname);
o0ntf("o/od", d);
or
Drin[("%d", strcmp(fname, lname));
11.2.6.4 Copy Strings
With integers we can usually assingn one value to the other, which
is not the case with strings. To copy one string to another string
variable, you use the strcpy function. This makes up for not being
able to use the "=' operator to set the value of a string variable.
Syntax:
stringl,
Example:
strcpy(fname, Yeru");
// this copies veru to fname in other words assigns "Veru" to fname
OR
strcpy(fname, lname);
fname
// this assigns the conetent of lname
Solved Examples
//Demonstrate ttre use of strcpy
#include <stdio.h>
#nclude <conio.h>
#include <string.h>
void main 0
char strl [f='SamPle string";
char str2[40J;
char strS[40];
strcpy (str2,strl );
strcpy (str3, "copy successful");
printf ('strl : %s\nstr2 : %s\nstB : o6s\n',strl,str2, str3);
getch0;
Output:
to
120
strl: Sample string
str2: Sample string
str3: copy successful
The above program Copies the C string pointed by source into the
affay pointed by destination, including the terminating null
character.
I/ Demonstrate us
of stmcpy
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main 0
char strl [l= To be or not to be';
char sf2[6];
stmcpy (str2,strl,5);
str2[5]=\9"
puts (str2);
getch();
To be
copies the first n characters of source to destination
//Demonstrate use of strca()
#include <stdio.h>
#include <@nio.h>
#lnclude <string.h>
void main 0
char str[80];
strcpy (str,thes ');
strcat (str,'strings ");
strcat (str,'are ');
strcat (str,'ooncatenated.
puts (str);
getch0;
Output:
") ;
t3't
I these strings are concatenatsd
ln the above program, a coBy of tfie *cur*e string is appended to
the destination string. The tenninating nul! character in destination
is ovenrritten by the first character of souroe, and a new nullcharacter is appended at the end of the new string formed by the
concatenation of both in destination.
II Demonstrate use of stmcat
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main 0
t
char strl [20];
char str2[20];
strcpy (strl,"To b" "),
strcpy (str2,'or not to b"');
strncat (strl, str2, 6);
puts (strl);
getch0;
Tq be or not
The above program appends the first num characters of source to
destination, plus a terminating null-character.
11.3 Rqferengesi
1.
& Furthe:' Rqading
Let us C by Yashwant Kanetkar
2, Mastering C by Venugopal, Prasad
.:".&
- TMH
12
FOINTERS
Contents
12.1 Objectives
12.2 lntroduction
12.3 Declarations
12.4 Operations on pointers
12,5 PointerArithmetic
.12.6 Pointers and anays
12.7 Passing pointers to a function
12.8 Anays of polnters
12.9 Function pointers
12.10 References & Further Reading
12.11 Review Questions
12.1 Objectives
ln this chapter you will leam the following things:
1. The definition of a pointer
2. The uses of pointers
3. How to declare and initialize pointers?
4. How to use pointers wlth simpte variables and arays
5. How to use pointers to pass a,rays to functions?
12.2 lntroduction
This chapter introduces you to pointers, an irnportant part of the C
language. Pointers provide a powerful and flexible method of
manipulating data in programs.
A pointer is a variable that contains the address of a variable.
This address is the location of another variable in memory.
For example, if one variable contains the address of another
variable, the first variable is sald to point lo the second. The figure
below explains this point:
123
trlemory Variablein
Address
ft,!
1000
3001
1002
t00t
l00tl
1005
3006
a
.l
t
a
Flgure
: Example of pointer:
One variable points to another
varlable
12.3 Declarations
A pointer declaration contains the following:
i. data type
ii. an * and the
iii. variable narne.
o The syntax for declari
variable is
*variablename;
basetype
where datatype is any valid datatype,
asterislr (.) is the indirection operator and
variablename is the name of the pointer variable.
The base t1pe indicates the Upe of obJect to wttich
the pointer will point.
For Example:
// a is a pointer variable that points to an
integer value
// b is a pointer variable that points to an
float value
ll c is a pointer variable that points to an
character value
int'a;
float'b;
char'c:
12.4 Operations On Pointers
124
Polnter Operators
*
There are two pointer operators, namely : and &.
The & is a unary operator that retums the memory address
i
of its
operand.
&m;
//places into n the memory address of the
n=
variable m.
*,
The pointer operatof, is a unary operator that retums the
value located at the address that follows.
o
a
p = *n;llplaces the value of n into
Pointer Assignments
The value of one pointer can be assbned as an value of
another pointer as shown below:
#include <stdio,h>
#include <conio.h>
void mainfl
int a = 10i
int tm, *n;
m=&a;
n=mi
prinff("m and n: %d o/od\n', *m, *n);
prints the value of a twice '/
printf('Addresses pointed to by m and n: olod o/od', m, n);
/' print the address of x twice */
getch();
m&n:
Addresses
ln the above r
to by m and n: 65510 65510
the following stater.nentsi
m=&a;
n=fiti
makes both m and n poiint to a
12.5 Pointer Arithmetic
125
There are only two arithmetic operations that you can
use on pointers:
poi
1.
2.
3.
4.
5.
nte?:',lH[:[: ;:,?ng?fi
g rures :
Each tirne a pointer is incrernented, it points to the rnemory
location of the next element of its base type.
Each time it is decremented, it points to the location of the
ror rowin
previous element.
lntegers may be added or subtracted to or fiorn pointers.
One pointer can be subtracted from arpther in older to find
the number of objects of their base type that separate the
tl ro.
Pointer comparisons are valld only between pointers that
point to the same array. Under these circumstances, the
relational operators ==, !=, ), (, )=. and <= work properly.
To understand the above rules, lets consider two exarnples:
1. Let m be an integer pointer with a curent value of 65124.
. After the
Also, assume ints are 2
m contains 65126, not 65125. This is because each time
m is incremented, it will point to the next integer which is
of two bytes.
2. Let n be an char pointer with a curent
Also, assume char is of
value of 650M.
. After the
is because each tirne is
point
to the next character which is of
incremented; it wilt
one byte.
The same is true of decrements.
For example:
let m has the value 65120,
contains 65005. This
m-;
causes m to have the value 65118.
The
m=m+5;
makes m point to the Sth element of m's tlpe beyond
the one it currently points to.
12.6 Pointers And Arrays
There
is a strong relationship
between pointers and
atTays.
Any operation on arrays achieved by using subscripts
can also be done with pointers. The pointer version is
faster but harder to understand.
Consider the following code:
126
char name[20], 'Ptl;
ffibeCn
set to the address of the first array
o To access the eighth element i
'(ptr+7)
goth statements will retum the eighth element.
12.7 Passins Polnters To A Function
A pointer is a data type by which we can pass address
to a function.
A typical example of passing pointers to functbn is our
program for swapping of tl,to numbers. We pass the
address of the variables to be swapped to the swap
function in order to change the values in ttle orpinal
variables.
Hence we require two integer pointer variables that can
hold the two addresses separately.
include <stdio.h>
#include <conio.h>
void
void main$
swap(int',int*);
//PrototYPe
int a,b;
clrscO;
printf('Please enter 2 positive integers:\t ');
scanf("%d%d',&a,&b);
print('\n Values before swapping are (in main 0):\n');
printf(' a = o/od \t b = 7od\n",d,b);
swap(&a,&b);
llcall bY reference,
actual arguments
printr(1n Values after swapping arc (in main 0):\n ');
printf(" a=o/od \t b = o/od\n',a,b);
getch0;
void swap(int *m,int
arguments
*n)
//definition, formal
int temp;
printf(ln Values before swapping are (in swap0):\n ");
printf(' m = 7od \t n = 7od\n",'ffi,*n);
=
.Iri
127
tm
'n
*n;
=
= temp;
printf("\n Values after swapping arc (in swap 0):\n ");
printf(" m = o/od \t n = 7od\n','*,*n);
Output:
Please enter 2 positive integers: 1 4
Values before swapping are (in main 0):
b=4
a=1
Values before swapping are (in swap 0):
n=4
m=1
Values after swapping are (in swap 0):
m=4
n=1
Values after swapping are (in main 0):
a=4
b=1
The function
void swap(int',int*);
has two format integer pointers and can hence accept the
addresses of two integer variables.
12.8- ArErys Of
Pointers
.,
An anay of pointers can be created.
For
: The exoression
declares an int pointer anay of size 10.
The array of pointers can be initialized:
For example:
int ml = 10i
int m2 = 100;
int m3 = 1fr)0;
a[0] = &m1;
a[lJ = &m2;
al2l = &m3;
.t
128
12.9 Function Pointers
A pointer that contalns the address of a function is
called a ftrnction polnter,
Fvery furrction has a physical location in memory. This
address is the entry point of the function and it is tlre address
used when the function is called.
This address can be asslgned to a polnter. Once a pointer
points to a function, the function can be called through that
pointer.
Consider the following example:
#include <stdio.h>
#include <conb.h>
int sum(int,int):
void mai()
(
int (*ptr)(int,int); // function pointer declaration
lnt s;
ll address of functlon sum is stored in ptr
s=('ptr)(S,8I
ptr=sumi
printf('Sum =
getch0;
)
or6d
',s);
int sum(int a, int b)
retum (a+b);
ln the above prograrn
1. ptr is e function pointer that contains the address of
function sum. The functbn pointers data type & parameter
list must match with the function it is pointing to.
2. lnt fptr)(int,lntl; indicates that p'.r is a r'Inction pointer
that points to a functbn that accepts 2 integer values and
retums an integer value.
129
12.10 References & Further Reading
1. The C programming Language By Brian W Kemighan and
Dennia M. Ritchie.
2. The Complete Reference C by Herbert Schildt
3. Let us C by Yashwant Kanetkar
4. C for Beginners by Madhusudan Mothe
12.11 Review Questions
1. Why do you need pointer arithmetic ?
2. How do you get access to an element in an array by using a
pointer?
3. How do use arrays of points ?
4. Given a two-dimensional character array. str. that is initialized
as
char str(2)={"You know you are in IDOL"}; write a program to
pass the start address of str to a function that prints out the
content of the character array.
13
STRUCTURES
Contentg
13.0 Oblectives
13.1 lntroduction
13.2 Declaration of a Structure
13.3 lnitialization of a Structure
13.4 Accessing Structure Elements
13.5 Storage of Structure Elements
13.6 Anay of Structures
13.7 Passing Structure Elements to a function
13.8 Pointer to a structure
13.9 Union
13.10 typedef
13.11 References & Further Reading
13.12 Review Questions
13.0 ObJectives
After readlrg this chapter you will be able to:
1. Declare and initialize structures
2. Access structure element i.e. Printing on screen and reading
from screen
3. Urderstand how structure elements are stored in memory
4. Crcate and use aray of structures
5. Pass structure or individual elements to a function
6. Use pointers to structure
7. Understand what is Union and how it is dlfierent from
Structure
13.1 lntroduction
We have seen the use of primary data types like integer,
float and character used to represent slngle entities. Then we
have seen the use of Arrays which are collection of entities of
same data Upe. But in real world we usually encounter
situations where the entities involved in the programming ane
seldom of similar types.
Consider the example of a book: a book may be described
by entities which are of differenl data Upes like number of pages
wouE require an integer, title of the book would require an anay
of character and price would require an variable of type float.
131
C provides us with structures to deal with collection of related
data that is of dissimilar data types.
13.2 Declaratlon Of A Structure
Before proceedlng to the syntax for structure declaration tets
consider the definition of a structure or find the answer to what is
a structure?
Definition:
A structure is a collection of variables possibly of different data
types grouped together under a single name.
Structure Type Declaration:
The syntax for structure type declaration is:
struct <structure name>
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
.
.
o
o
o
The above statement creates a data type called <etruclure
name> and has elementl, element2 and element3 as its
elements.
The elements of a struc'ture have to be enclosed in curly
brackets and terminated by a semicobn.
Once the structure is delined as shown above we can create
its variables just like primary variables.
A structure type declaration does not tell the cornpiler to
reserve any spaoe in memory. All a structure declanation
does is, it defines the 'form' of the structure.
Example:
struct student
t
char name[I0J
float height ;
int age ;
);
struct student sl,
s2, s3
o
.
o
.
The statement above delines a neu, data type called stsuct
student.
Student is a data type that has three elements called
structure elements.
Each variable of this data type student will consist of a
character array called name, a float variable called height
and an integer variable called age.
Once the new structure data type has been defined (student
in our case) one or more variables can be declared to be of
that data type.
132
For example the variable s1, s2, s3 can e declared to be of the
type struct student, as :
struct student s1, s2, s3;
Declaration of structure types and structure variable can be
done together in one statement as shown below :
struct student
(
char name[10];
float height ;
int age;
} s1, s2, s3;
13.3 Initialization Of a Structure
Once the structure type is defined and variables are declared, we
can initialize a structure. Initializing structure is similar to
initializing arrays.
133
Structnre elements are stored in mntinuous memory locations iust
like arrays. Bfi occupies melnory as required by the structure
elements.
Consider the Following example:
#lndudecstdio.h>
fincludecconio.h>
#ncludecstring.h>
vold main$
{
struct stud
(
char name[lOJ;
float height;
int age;
);
SttrCt StJd
pri
sl = fSuhaso, 5.4, 20):
o/ouVt o/ou\n",
ntf(ln/ou\n
&s
na
me, &s 1 height, &sl age):
.
getch0;
65510
65520
65524
im-
etCments via name $fibh is a
ctrarac.ter anay of size 10 will occupy 10 bytes slnce each character
occupies 1 byte, height occupies 4 bytes since lt is a fkcat variable
rnd age occupies 2 bytes since it is an integer
It can be shown in the diagram below
65510
6551
6551 2
6ssl 3
65514
6551 5
sl.name
10
bytes
sl.height
4 bytes
sl.age
2 bytes
65516
65517
65518
6551
65520
65521
65522
65523
65524
65525
15.6 Array ur urrucrures
rr
1*
Struclurcs ane often arrayed. ln our above example to store data of
100 students we would need 100 different structure variabbs from
Bl to s100, which is definitely not very convenient. A better
epprcach ulould be to use an anay of structures.
To dedare an erray of structures, you must first define a structure
and then declare an array variable of that type.
For example, a l00element aney of structures of type stud defined
earller is declared as bltows:
struct stud s[100];
This creates 100 sets of variables that arie organized as defined in
the structure stud.
To access a specific structure, we use the index along with anay
narne. Like all anay varlables, arrays of structunes begin indexing at
0.
The following example shows ruiting values insHe a l0O-element
anray of shrctures of tpe rtud & reading vatues and prrnting the
Bame on the screen.
#include<stdio.h>
#indudecconio.h>
#indude<strir.h>
void main$
(
int i;
struct stud
t
char name[10];
float height;
int age;
);
struct stud s[100];
for( i= 0; i<= 100; i++;
{
printf ( "\nEnter name, height and age ' ) ;
scanf ('o/oco/of a/od, &s[iJ.name, &s[iJ.height, &s[iJ.age )
br(i=0;i<=100;i++1
printf ( 1n%c
getchO;
void linkfloat( )
(
floata=0,*b;
o'/ot
o/td', s[il.name, s[il.helght, s[il.age
)
135
*/
b = &a ; /* cause emulator to be linked
*b
a=
; suppress the warning ' variable not used
'/
ln the above prcgram:
1. The statement struct gtud s[100]; provides space in
2.
memory for 100 structures of the type struct stud.
The syntax we use to reference each element of the arxay s
is similar to the syntax used for arrays of lnts and chatE. For
example, we refer to first student's helght as s[0l.height.
Similarly, we refer eighth student's age as spt.age.
3. The function llnkfloa(
) is used to prevent an enor i
'Ftoating Point Formats Not Linked' which is given with
maprity of C Compilers. lt simply forces formats to be
linked. There is no need to call this fungtion, it just needs to
be defined anynrhere in our program.
13.7 Passing Structures To Functions
We may either pass individual structure elements or the
entire structure variable at one go.
Passing Structure ltiembers to a functlon
When a member of a structure is passed to a function, it is
the value of that member that is passed to the func{ionExample : consider this structure:
struct sttd
{
char name[lO]:
float height;
int age;
) hari ;
Here ars examples of each member being passed
function:
display(hari.name); /' passes address of string name
*l
*/
display(hari.height); /* passes float value of height
display(hari.age); /' passes integer value oI z'l
display(hari.name[3]); /* passes character value
of s[2] */
ln eactr case, it ls the value of a specific element that
is
is
element
the
that
matter
not
passed to the function. lt does
part of a larger unit.
136
Example
*/
/" Passing inOiviOual structure elements
#includecstdb.h>
#includecconio.h>
#includecstring.h>
*,
void display(char float, int);
void main0
struct stud
t
char name[3O];
float height;
int age;
);
struct stud
s1 =
t"Vrjay
Deenanath
Chauhan', 6.2, 20I;
display( sl.name, s1 .height, s1.age ) ;
getch0;
)
*a, float b, int c
void display( char
)
(
printf ( ln%s olot Yod', ?, b, c ) ;
Output
iiav Deenanath Chauhan
6.2000000 20
Passing Entire Structures to Functions
When a structure is used as an argument to a function, the entire
structlre is passed using the normal catl-by-rralue methotl. Herrce
any changes made to the contents of the formal parameter do not
affect the actual parameter (structure) passed as the argument.
Passlng Entire Structures to Functions the following things should
be rcmembered:
When using a structure as a parameter, the type of the
actual argument must match the type of the formal
parameter
Z. The declaration of the structure type should be global so that
all parts of our program can use it. lf the structure type is
declared inside the mainQ it would not be visible to the
function being calted.
l.
Consider the following examPle:
137
138
pcurtiL:,ir: fcir th-l: funetiq:rn
to modify the contents *f the structure
used as the argunient.
Consid*r the fot8cwing examPle:
fstn ct sttil-
Itchar name[30
I
I
I
float height;
int age;
1 ) hari;
struct stud
"p;
/" declaril a $t:'lcture
,ddiess of the structure hari
into the pointer p
To access the members of a structure using a pointer to that
structure, w must use the -) operator. For example, to refer to
the age field we use:
*,
usually called the arow operator, consists of the
minus sign followed by a greater than sign. The alrow is used in
place of the dot operator when you are accessing a structure
member through a pointer to the structure.
The
Consider the following example:
findudecsUio.h>
#includecconio.h>
f,rrcludecstrirlg.h>
rroH main$
struct stud
(
char name[3O];
float height;
int age;
);
struct stud
sl = {a/rjay Deenanath
struct stud
P = &s1;
*p;
Chauhan', 6.2, 2Ol;
139
printf(1n%s\n
p rintf('\n%s\n
getch0;
o/ofln 7od\n",
o/ofl
sl .name, s1 .height,sl .age);
n o/od\n', F>name, p>height,p>age);
Output
Mjay Deenanath Chauhan
6.2000000
20
VUay Deenanath Chauhan
6.2000000
2A
13.9 Union
.
.
o
Unions are similar to structures. A union is declared and
used in the same ways that a structure is. The only
difference between a union and a structure is that with a
union only one of its members can be used at a time.
ln other words a union is a menxlry locaUon fiat is shared by
two or more different types of variables that are its members.
All the members of a union occupy the same area of
memory.
Defining, Declaring, and lnitiatizing Unions
. Unions are defined and declared in the same fashion as
structures. The only difference in the declarations is that the
keyword union is used instead of struct.
. The syntax to define a union is:
union <union name>
type member-name1
type member-name2
type member-name3
;
;
);
For example:
union uni
int i;
char c;
);
The above declaration does not create any variables.
This union, uni, can be used to create instances of a
union that can hold either a character value G or an
integer value i.
140
This is an OR condition. Unlike a structure that would
hold both values, the union can hold only one value at
a
time.
Variables of union are created in the same way as it is done
for structures.
is:
The s
union <union name> <union-variablename>;
For Exam
union uni uname;
ffiment
creates a variable uname of type uni
which is a union.
ln uname, both integer I and character c share the same
memory location.
The variable uname will be large enough to hold the largest
of the two types because when a union variable is declared,
the compiler automatically allocates enough memory to hold
the largest member of the union.
rn by int i and char c for union uname
Fig: Mernory utilization
A union can be initialized on its declaration. Because only
one member can be used at a time, only one can be
initialized.
union uni uname = {'n'};
or
union uni uname = tl0);
Accesslng Union ilembers
o
o
To access a member of a union, WB USe the Same SyntaX
that we usee for structures: the dot and arow operators.
The syntax fpr both ways is shown below:
union-name.member
or
u n io n- po i nte r->me m
ber
141
lndividual union members can be directly accessed in the
same way that structure members can be used--by using the
member operator (.).
However, there is an important difference in accessing union
members. Only one union member should be accessed at a
time.
For example, to assign the integer 10 to element i of uname,
|
,unarne.i = 10
lf the union is accessed through a pointer, we use the arrow
operator.
For example, to assign the integer 10 to element i , a pointer
to uname is passed to a function:
union uni "uname;
*u)
void function(union uname
u-> = 10; /* assign 10 to uname through a pointer "/
13.10Typedef
New data type names can be defined by using the keyword
typedef. When we use typedef we rename an existing data
type rather than create a new one.
The svntax for the typedef statement is
ef typa name;
where type is any valid data type, and name is the new
name for this type. The new name we defined is in addition
to, not a replacement for, the existing type name"
For
e. to create a new name for char :
char address;
The above statement tells the compiler to recognize address
as another name for char.
Next, we create a char variable using address:
151;
address
ln the above statement, streetname is a character anay
variable of type address, which is another word for char.
13.1{ References & Further Readin
1.
2.
The C programming Languagetsy Brian W. Kernighan
and Dennis M. Ritchie.
The Complete Reference C by Herbert Schildt
142
3.
Let us C bY Yashwant Kanetkar
13.l2Review Questions
1.
2.
3.
4.
5.
How is a structure different from an array?
What is the structure member operator, and what purpose
does it serve?
What keyword is used in C to create a structure?
What is the difference between a structure tag and a structure
instance?
How is a union different from an structure?
A.&a
14
FILE STRUCTURES
Contents
14.0 Objectiies
14.1 lntroduction
14.2 Definitions
14.3 Concept of record
14.4 File operations
14.5 Access Modes
14.6 Files with binary mode(Low level),
14.7 Performance of Sequential Files
14.8 Direct mapping techniques
14.8.1 Absolute
14.8.2 Relative
14.9
Sequential files (ISAM)
1 4.10 Concept of index
14.11 Levels of index
14.12 References & Further Reading
14.13 Review Questions
14.0 Obiectives
ln this chapter you will leam,
1. Basics about file structure
2. Different types of files and the way they can be accessed
3. Difference between binary and non binary files
4. Concept of lndex and Multilevel index
14.1 Introduction
Before leaming
file handling
it is worth knowing about file
structures. ln this chapter we will seo some basic definitions,
different types of files, ac@ss modes and indexing.
l4.2Definitions
Flle
A file is a collection of data called contents arrd has a set of
attributes.
The primary pumose of a file is to store and manage data
effectively and reliably.
File system
A file system is the prcgram that controls the access to and
manipulation of set of files.
1U
File identifier
A File identifier or file name is a name that uniquely identifies
a file within a comPuter sYstem.
14.3 Goncept Of Record
record oriented file sYstem.
length.
following ways which will be described in the sections
that follow:
Seguential
Direct
lndexed
Hierarchial
t
,/
{
{
14.4 File Operations
To support necessary file manipulation and management file
systems provide the following openations:
1. Create
Create and name a new file or overwrite an existing file
2.
Delete
Destroy the attributes and contents of a file
3.
Rename
Change the symbolic name refening to a file
4.
Open
Gain access to a file
5.
Close
Relinquish access
6.
Seek
Locate a record within a file
7.
Read
Retrieve one or more records of a file
8.
Write or update
Alter one or more records of a file
to a file
145
$treams and Files
The C l/O system supplies a consistent interface to the programmer
ind*pendent of the actual device being accessed i.e., it provides a
level af a[rstraction between the programmer and the device. This
abstracticln $s called a strean , and the actual device is called a file,
Stroamns
&
I
o
.
A Streaffi can be considered as a one way transmission path
canying rJata frcrn source to destination.. Associated with
svsry stream is e mradq that indicates the direction of data
?ran*f*r. & stramnt having input mode is called as input
straanr anS the *ne having output rnode is called as output
*traarm.
The fi fiie *ysterm works with a wide variety of devices.
$ince *treams *re largely device independent, the same
functtCIn that cari write to a disk file can also write to another
type cf ttmvice, such as the @nsole.
Streams are of two types:
l.
2,
Text Stream
A Text stream is a sequence of characters.
It is organized into lines terminated by
newline
character.
Binary Stream
A Binary stream is a sequence of bytes.
Files
.
.
ln C, a file may bc anything from a disk file to a terminal or
printer.
A stream can be associated with a specific file by performing
an open operation.
14.5 Access Modes
Traditional file systems provide either a record oriented or a
stream oriented interface to access files.
Record Oriented Files
.
.
.
.
Record oriented file systems divide files into records.
A record is the smallest that can be manipulated by a record
oriented file system.
Records can have either fixed length or variable length.
Access to records in a file can be organized in following
ways:
relative position with respect to first record. Also called
Relative access.
key value called index. Also called Random Access
146
organized bY keY values
Files
Oriented
Strearn
o Stream oriented files can be considered sequential or direct,
fixed length record files with single byte records.
14.6 Files With Binary Mode (Low Leveli
.
.
A binary file is contains data as a collection of bytes.
Binary files differ from Text files in the following three
contexts:
1. lnterPretation of newlines
2. Representation of end of file
3. The way numbers are stored
1. tnterpretation of newtines
. Binary files deal with newlines in a different way than text
files.
o To continue further it is necessary to understand the
o'o:*H;[""[ffi
ililii":',},1'[T"ff .'"j,:5ol j'nin"
beginning of the line without advancing to the next
line.
Line Feed (LF) - moves the cursor down to the next
line without returning to the beginning of the line.
End of Line (EOL)
- lt is actually two ASCII
characters and is a combination of the CR and LF
characters. lt rnoves the cursor both down to the next
line and to the beginning of that line.
ln text files :
i. while writing to disk when a newline character is being
writing to disk it is converted to EOL
ii. while reading from disk when a EOL character is read
it is converted to newline
ln Binary files the conversion to and from newline do not take
place
2.
Representation of end of file
o ln a text file the end of file is indicated by special character
whose ascii value is 26 ("2)
o ln Binary files there are no such special character present to
mark the end of file. A Binary file keeps track of the end of
file from the number of characters present in directory entry
of the file.
r File written in text mode cannot be read using binary mode
and vice versa. This is because a binary file opened in text
mode would expect special character for end of file which will
not be present as it was written in binary mode. Also any
147
number 26 may be interpreted as an end of file character
causing an early indication of end of file.
3.
The way numbers are stored
ln text files data is stored or is interpreted as strings of
characters.
Data can be charactrs, integers or floating point
numbers. A character occupies 1 byte, integer 2 & float 4
bytes of memory.
But while storing data on text files one byte per character.
Example:
1. IDOL is 4 characters, each character occupying 1
byte; total 4 bytes
2. 234 is an integer, but contains 3 characters; so total 3
bytes occupied on text file
3. 1 1 1.222 occupy 7 bytes on text file.
On the other hand binary files store data in binary format so
memory is efficiently used cornpared to text file.
o
.
.
o
14.7 Performance Of Sequential Files
.
o
.
We have seen previously that Sequential files are the files
that allow access to consecutive records.
Sequential files provides a straightfonrard way to read from
and write to files.
Write and Read to a Sequential File involves the following
steps:
Wrlting to a sequential flle:
1. Open the file in output mode. Sequential files have
2.
3.
two options to prepare a file for output:
Output: lf a file does not exist, a new file is created. lf
a file already exists, its contents are erased, and the
file is then treated as a new file.
Append: lf a file does not exist, a new file is created.
lf a file already exists, append (adds) data at the end
of that file.
Output data to a file. Writes data to a sequential file.
Close the file.
Reading from a seguential file:
1. Open the file in input mode. This prepares the file for
2.
3.
reading.
Read data in from the file
Close the file
The drawback to sequential files is that we only have
sequential access to our data. We can access one line at
a time, starting with the first line. This means if we want
148
to get to the last line in a sequential file of 5,000 lines, we
will have to read the preceding 4,999 lines-
14.8
Dirgct MaPPing
Techrc
14,8.1 Absolute
o ln absolute mapping the record is accessed directly, i.e
the location of the record has to be exactly known.
. There may be no relation in the value of the location
identifier and the location itself.
14.8.2 Relative
. ln Relative mapping the records are arranged in a relative
fashion. The records may be fixed length or variabte
length but each record has an identifier that is related to
.
.
the location unlike absolute mapping.
For example, record 1 may have a reference number 1,
record 3 may have a referen@ number 3 and record 10
may have a referen@ number 10 and so on.
Relative files can also be accessed in a sequential
manner.
14.9 tndexed Sequential Files (lsam)
An indexed-sequential-access (lSA) file allows both sequential
and direct access to data records. Thus, files must be on a
direct access storage device such as a disk.
ln indexed-sequential files, records are physically aranged on
a storage medium by their primary key, just as they are with
sequential files. The difference is that an index also exists for
the file; it can be used to look up and directy access individual
records.
Files set up to allow this type of access are called ISAM
(lndexed-sequential method) fi les.
Many Database Management Systems (DBMS) use ISAM files
because of their relative flexibility and simplicity. These are
often the best type of files for business applications that
demand both batch updating and on line processing.
14.10 Concept Of lndex
An index is similar to a table of contents found in every book.
It has a list of topics(keys) and the page numbers(r';ference
number) that indicate where to find those topics.
An lndex is a structure containing a set of entries that can
help to identiff a particular record.
149
a
a
Each entry consists of a key field and a reference field,
which is used to locate records in a data file.
Key fleld : - lt is that part of an index which contains keys.
Reference field:- lt is that part of an index which contains
information to locate records.
KEY FIELD
REF. FIELD
A1203
41293
41223
A2313
REF. FIELD
RECORD
ABCDEFG
ABCDEFG
ABCDEFG
ABCDEFG
Fig: Organlzation of lndex file
o ln the above diagram, the top part shows the index file that
contains a key field and a reference field and the lower part
contains the actual records identified by the reference field.
. lndexing is the process of maintaining an index.
14.11 Levels Of lndex
Primary lndex:
lf a Primary key is used to for indexing, the list so obtained
is called a Primary lndex.
This file is called the Second Level lndex and the original
file is called the First Level lndex.
Secondary lndex
It is a file obtained by creating an index file using fields other
than the Primary Key.
It is used to create multiple entry points (search points) to the
fite where records are stored apart from the primary index.
Multilevel lndexes
. Binary search is usually performed on an index to locate
pointer to the desired record. These indexes have simple
array structure.
150
The efficiency associated with searching and
index
of
the
index.
the
size
Once
depends upon the size of the
index file exceeds the size of available main memory, the
performan@ of the index and search operation degrades.
A solution could be to divide the original file into parts and
build a second index that will help index the prlmary index
(i.e. index for our index).
lf the second index file is also very large, we can repeat
the process and create a third index file.
ln fact, we can do this until we have an index that frts in
only one page and can be stored in memory. Using this
multi-level index we can retrieve information from the file
efficiently!
i1
{a
]5
)a
5'l
:.J
- --T-r-
5.5
irl
Fig: tultllevel lndex
l4.13References & Further Reading
t.
File Structures Using C++
Venugppal
2. File structures: an object-oriented approach with C++
Michael J. Folk
14.13 Review Questions
1. What is a file?
2. What are the different wayls in which a file may be accessed?
3. How is a text file different from a binary lTle?
4. What are indexes? Explain Multilevel lndexes.
.:.**
15
FILE HANDLING
Gontents
15.0 Objectives
1
5.1 lntroduction
15.2 File operations
15.2.1 Opening a File
15.2.2 Creating a File
15.2.3 Closing a File
15,2.4 Deleting a file
15.2.5 Renaming a file
15.2.6 Reading from a file
15.2.7 Writing to a file
15.2.8 Copying a file
15.2.9 Seekiqg the location of a specific record (Random
Access)
15.3 Text file & Binary file.
15.4 References & Further Reading
15.6 Review Questions
ln this chapter you will leam:
1. Opening a file
2. Writing data to a file
3. Reading data from a file
4. Closlng a file
15.1 lntroduction
The C programming language provides a set of library functions to
deal with File l/O. Using these functions we can perform various
operations on files either in a binary form or in human readable text
form.
15.2 FILE OPERATIONS
We have already seen in the previous chapter the
operations related to files. They are:
1. Create
Greate and name a new file or ovenrvrite an existing file
2.
Delete
various
152
3.
Let us C by Yashwant Kanetkar
13.12Review Questions
l.
2,
3.
4.
5.
How is a structure different from an anay?
What is the structure member operator, and what purpose
does it serve?
What keyuord is used in C to create a structure?
What is the difference between a structure tag and a structure
instance?
How is a union different from an structure?
*.3.4
lSS
Destroy the attributes and contents of a file
3.
Rename
Change the symbolic nams referrirq to a frle
4.
Open
Gain access to a file
5.
Close
Relinquish access
6.
Seek
Locate a record within a file
7.
Read
Retrieve one or rt<lre records of a ttrle
8.
Write or update
Alter one or more records of a file
9.
Copy
Copy the Contents of one file to another
o
.
to a file
We will @ver each of the above mentioned operations but in a
slightly @nvenient order.
All the Standard Library Functions required for File l/O are
present in the Header file <stdio.h>, hence this file has to be
included in all our programs.
The File Pointer
ln order to read or write files, our program needs to use file
pointers.
A file pointer is a pointer to a structure of type FILE.
lt contains information on various things about the file, like its
name, status, and the cunent position of the file.
The syntax to create a file pointer variable is as follows:
.
.
.
.
F|LE "&;
15.2.1 Openlng a File
. Opening the file is a process of creating a stream tinked to a disk
o
.
.
file.
Once a file is opened, it is available for reading, writing or both.
Once we are done using the file we should close it.
The fopenQ functpn is used in C to open a file.
The fopenO does three things:
154
It searches the file on the disk to be opened'
lf th.g file axists and is found, it is loaded in the memory in a
place called bufier.
3. it retunrs a character ;,rointer that point to the first character in the
buffer.
is as follows:
The
nfilename, const char *mcd,el;
const bhar
FILE
ffinarne is tne name of the file to be opened.
mode specifies the mode in which the ftle has to be opened. The
mode controls whether the lile is binary or text and whether it is
for reading, writing, or both.
The following is a code snippert to open a file named "testfile" in
read mode
l.
",
FILE'fp;
fp=
tn tne above example, the file named testfile is opened in read
mode. There are various modes in which a file may be opened.
The mode to select depends upon the operation we wish to
perform once the file is oPened.
The permitted values for mode are listed below:
r
w
r+
w+
a+
Opens the file for reading.
a
tf the file doesn't exist, fopen$lqtqrns tIULL.
Opens the file for writing.
lf a file of the specified name doesn't exist, it is created.
lf a file of the specified name does exist, it is deleted
without waming, and a new, empty file is created.
Opens the file for appending.
lf a file of the specified name doesn't exist, it is created.
lf the file does exist, new data is appended to the eM of
the file.
Opens the file for reading and writing.
lf a file of the specified name doesn't exist, it is created.
lf the file does exist, new data is added to the beginning
of the file. overwriting existing data.
Opens the ftle for reading and writing.
lf a file of the specified name doesn't exist, it is created.
lf the file does exist, it is ovelwritten.
a
Opens a file for reading and appending.
a
lf a file of the specified name doesn't exist, it is created.
a
lf the file does exist, new data is appended to the end of
the file.
As specified in the table above, fopen$ may return a NULL if
we try to open a file that does not exist.
The situations when fopen$ may return a NULL are:
Trying to open a nonexistent file in mode r.
a
o
o
.
o
o
o
.
e
o
.
.
o
l.
155
2. Trying to open a file in a nonexistent directory or on a
nonexistent disk drive.
3. Using an invalid filename.
4. Trying to open a file on a disk that isnt ready (the drive
door isnt closed or the disk isn't formatted, for example).
This method will detect any error in opening a file:
FILE .fp;
if ((fp = fopen("testfile","f ;;==NULL)
(
printf("Cannot open fi le.\n");
getchQ;
exit(1);
15.2.2 Creating a File
o We can create a file using fopenQ.
o While opening a file, if it is found that the file does not exist, a
file by the given filename will be created if any one of the
following modes are used : a, a+, w, w+ and r+
Example:
a fp = fopen("testfile", 'r*');
a fp = fopen("testfile", "a');
a fp - fopen('testfile', "a+");
o fp - fopen('testfile', '*");
a fp - fopen('testfile', 'w+");
15.2.3 Closlng a File
o The fclose( ) function is used to close a stream that was
opened by a call to fopen( ).
o Not closing a file strearn or failure to close a stream creates
problems like lost data, destroyed files etc.
function has the
The
int fclose(F|LE *fpl;
The
x to close a file is :
Example: fclose ( fp ) ;
15.2.4 Deleting a file
. An existing file can be deleted using the library function
rernove$.
lts prototype is as follows:
int remove( const char *filename l:
where,*filename is a pointer to the narne
deleted
To remove a file it must not be open.
of the file to be
156
a
a
lf an existing file is deleted, remove$ retums 0-
ln other cases like file does not exist, read-only flle,
insuflicient access rights and other erors retums -1.
Consider the following examPle:
#include <stdio.h>
#include <@nio.h>
void main$
t
char filename[8O];
printf("Enter the filename to delete: ');
gets(filename);
if ( remove(filename) -= 0)
printf("The file %s has been deleted.\h", filename);
else
printf("Error deleting the file %s.\n', filename);
getch0;
Output:
Flrst Run
Enter the filename to delete: f2.txt
The file f2.txt has been deleted
Second Run file does not
e.
Enter the filename to delete: f2.brt
Enor deleting the file f2.bct
15.2.5 Renaming a file
o An existing file can be renamed using the library function
renameQ.
lts prototype is as follows:
int rename( const char *oldname, const char *newname
where, oldname is the existing name of the file we want to rename
and
newname is the new name we want to assign.
renameO is bound by a restriction: both names must refer to the
same disk drive; we cant rename a file to a different disk drive.
When successful, renameO retums 0 and -1 ]f an eror occurs.
Causes of errors may be:
Old filename does not exist
2. New file name already exists
3. lf you try to renarne to another disk.
Consider the
#include <stdio.h>
#include <conio.h>
.
.
.
l.
157
voirl main$
t
char oldname[80J, newname[8O];
print('Enter annent filenamo, ');
gets(oldname);
printf('Enter new narne for file: ');
gets(newnare);
if ( renam{ oldname, newname ) == 0 )
printf("7os has been renamed 7os.\n", oldname,
newname);
else
printf( "An
eror has occuned
renaming
o/os.\n",
oldname);
getch0;
)
Ontput:
Flrct Run
Enter cunent filename: idol.txt
Enter new narne for file: udit.txt
ldol.txt has been renamed to udit.btt
rw file name
Enter cunent filename: f1.btt
Enter new name for file: f2.bd
An enor has occuned renaming fl.bd
Second
15.2.6 Readlng a flle
Entire files could be read character by character using getc{)
or fgetc$.
. The
is as folbYrs:
ofc
int getc(FILE "fp);
where fp is a file pointer of type FILE retumed by fopen( ).
The functions getc$ and fgetc() urcrk in the following mannen
1. Read the character at the cunent pointer position
2. Advance the pointer so that it points to the next character
and return the read character
3. When the end of the file is reached (indicated by a
character whose ASCII value is 261 a macro EOF is
retumed.
Consider the following example that opens a file entered by
the user and prints its content on the screen:
#include <stdio.h>
#include <conio.h>
vold main$
t58
char filenarne[8Ol,clu
FILE'fp;
prin('Enter the filename to display contentrs: ');
gets(filename);
if ((fp = fopen(fi lenam,'/'))==NULL)
print('Eror opening file %s',filenarne);
)
chruetdfp);
uilrile (ch!=EOF) {
putcha(m); /'print on screen
'/
ch = getc(fp);
)
fclose(h);
getch0;
Outp$
Enter file name to display contents : fl.txt
Hi how r u?
The EOF macro, often defined as-1, is the value retumed
when an input fundion tsies to read past the end of the file
15.2.7 Wrltlng to a frle
We can write into a file character by chanacter using putc0 or
fputc$.
is as folbtrs:
eof
TIre
cr,, FILE Wl;
int
,r,trere & is the file pointer retumed by fopen( ), and ch is the
character to be output.
For example on writing to a fih consider the bllowing sec{ion
on opying a file which inrrolves readlng characters fiom one
file and writing thern to another.
15.2.8 Copylng a file
The following program inrolves the concepts of readlng fiom and
to a ftle:
#include <stdio.h>
#include <@noi.h>
159
FILE Ts,'ft;
char ch ;
char sfilename[20J,dfilename[20J;
printf('Enter the source filename to copy contents: ');
gets(sfilename);
'f
fs = fopen ( sfilenatne,
);
if ( fs == NULL )
{
printf ( "Cannot open souroe file o/os",sfilename )
ext( );
)
printf("Enter the destination filename to copy contents: ');
gets(dfilename);
ft = fopen ( dfilename,
if(ft==NULL)
t
'uf
printf( "Cannot open target file o6s',dfilename )
fclose(fs);
exit( );
)
while ( 1 )
ch=fgetc(fs);
if ( ch == EOF )
print(lnFile oopy @mpleted successfu
llyf );
getch0;
exit();
)
else
Futc(ch,fr);
)
fclose(fs);
fclose(ft);
Enter the source file name to copy contents : nik2.txt
Enter the destination file narne to copy contents : nik3.btt
File coDv comoleted succe
15.2.9 Seeling the location of a specific record (Randont
Access)
o The operations that we have seen so far are all based on
Sequential access. To move to a particular character we start
160
last
by opening the file and move fiom first character to the
charagter.
The fseek 0 can be used to perform read and write at randorn
locations.
is as follows:
The
*h,
int origin);
long int nu
LE
int
catt to foPenO,
numbytes ii tfre number of bytes from origin, wtrich will
cunent position, and
become the
origin is a macro that can have one of the following
three values
new
ilacro
Origin
Name
Beginning of file
SEEK SET
Cunent position
End of file
SEEK CUR
SEEK END
Hence to seek numbytes from start of the file origin slpuld be
SEEK-SET.
To seek ftom numbytes the cunent position, vve use
SEEK-CUR as or(]in, and
To seek from the end of the file,we use SEEKJND as origin
ConsHer the following ExamPle:
#include <stdio.h>
int main0
FILE I f;
f = fopen('myfile.t{t", 1^f);
opens it
fuuB('Hello',0;
fseek(l 6, SEEKJET);
position
Futs('lndia',0;
at
position
fseek(t 6, SEEK-CUn);
positbn
//Creates a file MYFILE.T}ff and
/Mrites the string "Hello' into it
l/Positions the cunsor at 6th
fiom
ofuin
/Mrites the string 'lndia'
current
//Positions the cursor at 6th
cunent
fiom
position
Futs(' how r u?", 0;
heek(f, 6, SEEKJND);
places ahead
//Writes the string "how r u?" at
cunrent position
/lPositions the cunior at 6
fiom end
161
fputs(" you are the best!",
bestl*
f); /Mrites the string " you are the
at current position
//Closes the file
fcl$se{f};
retunr 0:
OutpqB
hfrYF3t-H.Tm
Hello
lndia
how n u?
you are the best!
15.3 TH}ffi FILES A$EO BINARY FILES
a
o
The opemtions described in the sections above are based on
Text fils. ln thls section we concentrate on working with
binary files"
We have already discussed the differences between text files
and binary files in the previous chapter.
With binary files the operation ls almost same as text files.
To operate on any file we have to open it first. ln case of
binary files we use a function open() and a file handle instead
of a fib pointer.
handle =
, mode);
where, open( ) retums an integer value called file handle, it
is an integer value assigned
to the file which is used later to refer to it.
handle is the integer value retumed when the file is
opened
filename is the file we want to access and
mode is the mode in which we want to access the file.
lf the file open openation is unsuccessful, open$ retums (-1)
Ex:
haMle = open ( "MYFILE.TXf, O:
Here, the file "MYFILE.TXT' is opened in read-only mode
specified by O_RDONLYand in binary mode specified by
O-BINARY.
. The
modes are:
file
O-CREAT Creates a new file for writing
It has no effect if file alrcady exists.
Creates a new file for reading onlY
.RDONLY
O-RDWR
WRONLY
Creates a file for both reading and writing
Creates a file for writing only
-l
162
Opens a file for appending
APPEND
O-BINARY
Creates a file in binary mode
o_TElcr
Creates a file in text mode
To use the modes mentioned above we have to add
.
o
the header file <fcntl.h> to our program.
When two or more modes are to be used together, they are
combined using the bitwise OR operator ( I ).
Consider the followi
handle = open ( filename, O-CREAT I O-BINARY
O_WRONLY, S_IWRITE );
o
o
lf the file we want to access does not exist when it is being
opened we have used the O_CREAT to create it, to only
write to it we use O_WRONLY and since we want to open the
file in binary mode we have used O_BINARY.
When we use O_CREAT we also need to specify the
permission associated with read/write to our file. lt is called
permission argument.
The
to the file oermitted
Readin from the file
itted
Buffer- The operations of reading from and writing to files
involves the use of a buffer where the data is temporarily
stored.
Reading from Files
To read from files we use the read$ function.
Prototype for read function is aq fglllows:
o
o
where handle is the file handle obtained earlier using
creat or open
buff points to a buffer that the function reads
the bytes into
len number of bytes that the function attempts
to read
Ex.
= read ( handle, buffer, 512 ) ;
the above line when executed attempts to read 512
bytes from the file pointed by the handle into the buffer
Writing to files
To write from files we use the write$ function.
llows:
Prototype for write function
o
o
where handle is the file handle obtained earlier using
creat or open
lGl
buff points to a buffer that the function writes
the bytes from
len number of bytes that the function attempts
to write
Ex.
write ( handle, buffer,
t
the above line when executed writes the data assigned
to bytes stored in buffer into the file pointed by the
handle.
Consider the following program that read the data from
source file and writes it into ta
level file
#include <stdio.h>
#include <conio.h>
#include 'fcntl.hn
#include "sys\stat.h'
void main ( )
(
char buffer[ 512 J, source [ 15 J, target [ 151
int shandle, thandle, bytes ;
printf ( '\nEnter source file name" ) ;
gets(source);
shandle = open ( source, O-BDONLY I O-BINARY )
if ( shandle == -1 )
printf( "Cannot open file o/os',source )
exit( ) ;
printf ( lnEnter target file name" )
gets(target);
thandle = open
taryet, O-CREAT
);
O-WRONLY, S-IWRITE
if ( shandle == -1 )
{
printf( "Cannot open file Tos",target )
close(shandle);
exit(
)
);
while ( 1 )
bytes = read ( shandle, buffer, 5121
if(bytes>0)
write ( thandle, buffer, bytes ) ;
else
break ;
)
printf('\nFile Copy S uccessful');
close(shandl");
close(thandle);
O-BINARY
164
getch0;
Enter source file narne:
Filel.txt
Enter target file name:
File2.txt
File cop*/ successful
15.4 References & Further Reading
1. Let us C - Yashwant Kanetkar
2. C The Complete Reference - Herbert Schildt
3. Teach yourself C in 21 days - Peter Aitken and Bradley L.
Jones
15.5 Review QuestionS
1. List and explain in brief the various operations that. can be
2.
3.
4.
performed on files.
Explain with the help of a program how to read from one file and
write to another
Explain the use of fseek$ in random access files
Explain how data is read frorn and written to binary files.
A.&.&
165
2. Trying to open a file in a
3.
4.
nonexistent directory or on a
nonexistent disk drive.
Using an invalid filename.
Tryrng to open a file on a disk that isn't ready (the drive
door isn't closed or the disk isn't formatted, for example).
This method will detect any eror in
FILE -fp;
if ((fp = fOpen("teStfile","r" ;;==NULL)
{
printf("Cannot open file.\n");
getch0;
exit(1);
a file:
15.2.2 Creating a File
o We can create a file using fopen0.
. While opening a file, if it is found that the file does not exist, a
file by the given filename will be created if any one of the
following modes are used : a, a+, w, w+ and r+
Example:
a
fp = foPen("testfile" , ttr+tt);
o
fp = fopen("testfile" , ttatt);
tta+tt);
a fp = fopen("testfile" ,
a
fp = fopen("testfile" , "wtt)l
t'w+");
o
= fopen("testfile" ,
15.2.3 Closing a File
. The fclose( ) function is used to close a stream that was
opened by a call to fopen( ).
o Not closing a file stream or failure to close a stream creates
o
o
problems like lost data, destroyed files etc.
function has the
The fcl
int fclose(F|LE *fp):
Thes tax to close a file is :
fclose(filepointer_
Example: fclose ( fp ) ;
15,2.4 Deleting a file
. An existing file can be deleted using the library function
remove$.
lts prototype is as follows:
where,* filename is a pointer to the name
deleted
To remove a file it must not be open.
of the file to
be
{66
a
lf an existing file is deleted, removeQ retums 0.
ln
other cases like file does not exist, read-only file,
insufficient access rights ard other enors retums -1.
Consider the following example:
#include <stdio.h>
#include <conio.h>
void main$
char filename[80];
printf('Enter the filename to delete: ');
gets(filename);
if ( remove(filename) -= 0)
printf('The file %s has been deleted.\n", fihname);
else
printf("Error deleting the file 7os.\n', filename);
getch0;
Output:
Flrst Run
Enter the filename to delete: t2lrt
The file f2.brt has been deleted
Second Run (fite does not exls
Enter the filename to delete: f2.txt
Enor
the file f2.bd
15.2.5 Renamlng a lile
An existing file can
rename0.
.
.
be renamed using the library
function
lts prototype is as follows:
qt re4eme(
const char'oldname, const char'newname );
where, oldname is the existing name of the file we urant to rename
and
newname is the new name we want to assign.
rename0 is bound by a restriction: both names must refer to the
same disk drive; we can't rename a file to a different disk drive.
When successful, renameO retums 0 and -1 rt an eror occuns.
Causes of errors may be:
Old filename does not exist
2. New file name already exists
3. lf you try to rename to another disk.
Consider the
#include <stdio.h>
#include <conio.h>
o
.
.
l.
167
void main$
{
char oldname[8O], newname[8O];
printf('Enter cunent filenam,');
gets(oldname);
printf('Enter new name for file: ');
gets(newname);
if ( rename( oldname, newnarne ) == 0 )
printf("o/os has been renamed o/os.\n', oldname,
newname);
else
printf( "An error has occurred renaming
o/os.\n",
oldname);
getch0;
Output:
Flrct Run
Enter cunent filename: idol.btt
Enter new name for file: udit.btt
ldol.txt has been renamed to udit.Ott
Second
Enter cunent filename: fl.b<t
Enter new name for file: f2.0d
An enor has o@ured renaming
fl.ffi
15.2.6 Reading a file
Entire files could be read character by character using getc0
or fgetc$.
o The
is as follows:
.fpl;
getc(FILE
int
where fp is a file pointer of type FILE retumed by fopen( ).
The functions getc$ and fget() work in the following manner:
1. Read the character at the cuffrlt pointer position
2. Advance the pointer so that it points to the next character
and retum the read character
When
the end of the file is reached (indicated by a
3.
character wtrose ASCII value is 26) a macro EOF is
retumed.
Consider the following example that opens a fite entered by
its content on the screen:
the user and
<stdio.h>
#include
#include <conio.h>
voirJ
168
t
char filename[8O],ch;
.fp;
FILE
printf("Enter the filename to display contents: ");
gets(filename);
if ((fp = fopen(fi lenam,'1,))==NuLl)
{
printf("Eror opening fi le Tos",filename);
)
ch-getc(fp);
while (ch!=EOF) {
putchar(ch); /* print on screen "/
ch = getc(fp);
)
fclose(fp);
getch0;
Output:
Enter file name to display contents : f1.txt
Hi how r u?
The EOF macro, often defined as-1, is the value returned
when an input function tries to'read past the end of the file
15.2.7 Wrlting to a file
. We can write into a file character by character using putc0 or
fputcQ.
The
is as follows:
.fpl;
int putc(int ch, FILE
where fp is the file pointer retumed by fopen( ), and ch is the
chanacter to be output.
For example on writing to a file consider the following section
on oopying a file which involves reading characters from one
file and writing them to another.
15.2.8 Copylng a flle
The following program involves the concepts of reading from and
writing to a file:
#include <stdio.h>
#include <conoi.h>
void main( )
r09
(o
*fs,
FILE
'ft ;
char ch ;
char sfi lename[20l,dfilename[20];
printf('Enter the source filename to copy contents: ');
gets(sfilename);
fs = fopen ( sfilename,
if ( fs == NULL )
"f ) ;
printf ( 'Cannot open source file Tosn,sfilename ) ;
exit( ) ;
)
printf('Enter the destination filename to copy contents: ');
gets(dfilename);
ft = fopen ( dfilename,
if(ft==NULL)
t
ld
printf( "Cannot open target file Tos",dfilename )
fclose(fs);
exit( ) ;
)
while ( 1
{
ch=fgetc(fs);
if(ch==EOF)
t
printf("\nFile copy completed successfully");
getchO;
exit0
)
else
fputc(ch,ft):)
fclose(fs);
fclose(ft);
Enter the source file name to copy contents : nik2.txt
Enter the destination file name to copy contents : nik3.trt
File copy completed successfull
15.2.9 Seeking the location of a specific record (Random
Access)
. fne operations that we have seen so far are all based on
Sequential access. To move to a particular character we start
170
by opening the file and rnove from first character to the last
character.
The fseek 0 can be ursed to perform read and write at random
locations.
The
is as follows:
int fseek(FILE 'h,
int nu
int
where, fp is a file pointer returned by a call to fopen( ),
numbytes is the number of bytes from origin, which wilr
become the
cunent position, and
origin is a macro that can have one of the following
three values
new
flacro
Origln
Name
Beginning of file
SEEK SET
Cunent position
SEEK CUR
SEEK END
End of file
Hence to seek numbytes from start of the file origin should be
SEEK-SET.
To seek from numbytes the cunent position, we use
SEEK_CUR as origin, and
To seek from the end of the file,we use SEEK_END as origin
Consider the following Example:
#include <stdio.h>
int main$
t
FILE
'f;
f = fopen('myfile.b(t',
opens it
'*");
l/Creates a fite MYFILE.TXT and
/Mrites the string "Hello" into it
!Ruts('Hello", f);
fseek(l 6, SEEK-SET);
//positions the cursor at 6th
position
at
from
fputs(" lndia",
position
fseek(f, 6,
position
f);
origin
/Mrites the string
"tndia,,
cunent
SEEK_CUn);
position
fputs(" how r u?",
//positions the cursor at 6th
cunent
from
f);
/ArVrites the string *how r u?" at
cunent position
fseek(f, 6, SEEK_END); //positions the cursor at 6
places ahead
from end
171
fputs(. you are the best!",
best!'
f); /Ailrites the string " you are the
at current position
llCloses the file
fclose(f)i
retum 0;
Output
MYFILE.TXT
Hello
lndia
how r u?
u are
ttit
best!
15.3 TEXT FILES AND BINARY FILEU
a
O
The operations described in the sections above are based on
Text file. ln this section we concentrate on working with
binary files.
We have already discussed the differences between text files
and binary files in the previous chapter.
With binary files the operation is almost same as text files.
To operate on any file we have to open it first. ln case of
binary files we use a function open$ and a file handle instead
of a file pointer.
handle =
filename, mode
where, open( ) returns an integer value called file handle, it
is an integer value assigned
to the file which is used later to refer to it.
handle is the integer value retumed when the file is
opened
filename is the file we want to access and
mode is the mode in which we want to access the file.
lf the file open operation is unsuccessful, openQ retums (-1)
Ex:
handle = open ( "MYFILE.TXT", O_RDONLY I O_BINARY ) ;
Here, the file "MYFILE.TXT" is opened in read-only mode
specified by O_RDONLYand in binary mode specified by
BINARY.
a The
ible ltle ,tir UI l rnodes are:
O-CREAT Creates a new file for writing
It has no effect if file already exists.
RDONLY
Creates a new file for reading only
O-RDWR
.WRONLY
Creates a file for both reading and writing
Creates a file for writing only
172
Opens a file for appending
O APPEND
O-BINARY
Creates a file in binary mode
O TEXT
Creates a file in text mode
To use the modes rnentioned above we have to add
.
.
the header file <fcntl.h> to our program.
When two or more modes are to be used together, they are
combined using the bitwise OR operator ( I ).
Consider the
handle = open ( filename, O_CREAT I O_BINARY I
O-WRONLY, S_IWRITE );
lf the file we want to access does not exist when it is being
opened we have used the O_CREAT to create it, to only
write to it we use O_WRONLY and since we want to open the
file in binary mode we have used O_BINARY.
When we use O_CREAT we also need to specify the
permission associated with read/write to our file. lt is called
permission argurnent.
Buffer- The operations of reading from and uniting to files
involves the use of a buffer where the data is temporarily
stored.
Reading from Files
To read from files we use the read$ function.
for read function is as follows:
where handle is the file handle obtained earlier using
creat or open
buff points to a buffer that the function reads
the bytes into
len number of bytes that the function attempts
to read
Ex.
bytes = read ( handle, buffer, 512 ) ;
the above line when executed attempts to read 512
bytes from the file pointed by the handle into the buffer
Writing to files
To write from files we use the write$ function.
Prototvpe foryvrite function is as follows:
o
o
where handle is the file handle obtained earlier using
creat or open
173
buff points to a buffer that the function writes
the bytes from
len number of bytes that the function attempts
to write
Ex.
write ( handle, buffer,
);
the above line when executed writes the data ass(;ned
to bytes stored in buffer into the file pointed by the
handle.
Consider the following program that read the data from
source file and writes it into tarqet file (low level file co
#include <stdio.h>
#include <conio.h>
#include "fcntl.h"
#include "sys\stat.h"
void main ( )
char buffer[ 512l, source [ 15 t, target [ 15 ]
int shandle, thandle, bytes ;
printf ( '\nEnter source file name" ) ;
gets(source);
shandle = open ( source, O_RDONLY I O_BINARY )
if ( shandle == -1 )
printf( "Cannot open flle 7os',source ) ;
exit( ) ;
)
printf ( "\nEnter target file nam" ) ;
gets(target);
thandle = open
target, O_CREAT
);
O-WRONLY, S-IWRITE
if ( shandle == -1 )
printf( "Cannot open file o/os",target )
close(shandle);
exit( ) ;
)
while ( 1 )
bytes = read ( shandle, buffer,
51
if(bytes>0)
write ( thandle, buffer, bytes ) ;
else
break ;
)
printf('\nFile Copy Successful");
close(shandle);
close(thandle);
2l
O_BINARY
174
Enter source file name:
Filel.D<t
Enter target file name:
File2.txt
File copy successful
15.4 References & Further Reading
- Yashwant Kanetkar
2. C The Complete Reference - Herbert Schildt
3. Teach yourself C in 21 days - Peter Aitken and Bradley L.
Jones
1. Let us C
15.5 Review Questions
1.
2.
3.
4.
List and explain in brief the various operatior,s that can be
performed on files.
Explain with the help of a program how to read from one file and
write to another
Explain the use of fseekfl in random accegs files
Explain how data is read from and written to binary tiles.
.:.*A