Escolar Documentos
Profissional Documentos
Cultura Documentos
CONTENT
: University of Mumbai
Dr. D. Harichandan
Incharge Study Material
Section IDOL
University of Mumbai,
Mumbai
Incharge
Director,
DTP Composed by :
Printed By :
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)
No
Yes
Yes
No
A typical
'
Arrows
."
'
ltisknownaS,'@''incomputerscience.AnarroW
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,
Junction symbot
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.
$tart
Id*l F*l
ls ful=N?
s?'r
..1:
False
Test
Expressio
n
lnitializatlon
:llt:l-f--__l
Test
Expression
t#r .
lncrement Expression
Suficltmihblc
cqnlsnr*ce*
Sndtdt,vathllt i
equebro@d )
Suttchrnrhbh
cqualt Thlrdcrse
Flowchart (EJtirmolgli
find the sum of first 50 natural numbers.
r
I
I
I
are
of
to
to
Hbl-rlguel Language
Assembly language
Machine Langmge
Binary:
(Hexadecimal: 0xb061)
I
1.4.2 Assemblv Level Lanquaoe:
is used to
convert assembly language statements into the target
(a
rnoval,5
al ; 5 +
or
r
t
t,
r
r
COBOL
to leam by
first-time
problems specific;
FORTRAN is developed
mathematical problems.
// 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
A,
B,
.z
11
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
. 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)
values.
Eg.: 045, 056, 067
.'
o
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
o
.
.
.
o
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,1 ldentifiers:
13
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
14
of
double
else
enum
extern
float
for
goto
if
int
long
register
return
shofi
signed
sizeof
static
Struct
Switch
Typedef
Union
Unsigned
Void
Volatile
While
'
15
lnteger
int
Character
char
Floating Point
float
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
double
16
SIZE
Range
(Blts)
Char or Signed Char
-128 to 127
0 to 255
16
-32768 to 3276V
Unsigned int
16
0 to 05535
-128 to 127
0 to 255
32
-21 47
32
0 to 4294967295
Float
32
Double
64
1.7e-308 to 1.7e+308
Long Double
80
483648 to
21 47
483647
17
,... 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
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
18
is name
Example:
typedef int rollno;
tlryedef float standard-deviation
19
storage class divides the portion of the program within which the
variables are recogni zed.
static : Local variable which exists and retains its value even after
the control is transferred to the calling function.
the program, ?s we
by
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.
Algebralc Expression
C Expression
axb-c
a*b-c
(m+n)(x+y)
axb/c
(m+n)"(x+!/)
a*b/c
Evaluation of Expresslons
Variable = expression;
o
o
x=a"b-c
Y = b I c* a
z=a-blc+d;
2.6 $taternents
21
sepflrate
statement. Therefore a complete C program wpuld comprisg of a
series of statements.
. However,
at which a statement is to
be written. That's why it is often called a free-form language.
statement terminator.
; Thus ; acts as a
.
.
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
#include <stdio.h>
main0
{
int fahrl
22
for
(fahTLOWERIOWER-BOUND;
fahr<=U PPER-BOUND; fah rfahr+ N DD(-STEP)
{
I
pri
n('
o63d
0/o6.
)) ;
)
)
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.
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.
is
statements
are character
apostrophes .
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).
the input
Where string = string
parameters, and Parameter 1, paranneter ? that parameters is to
represent the individual input data item or elernents.
Character
D
I
o
U
int'
26
g,f,g
o/o
D
I
o
U
char
parameterZ,
, parameter n)
27
Fonnat Specifierc
There are many format specifiers defined in C
o/oi
ar
olod
o/oC
o/ol
ololt
%s
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
.
.
.
.
.
.
.
o
2OO;
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
#includecstdio.h>
#includecconio.h>
cl*O;
int main$
{
getoh0;
retum 0;
)
o/o
30
statement:
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
.
.
o
o
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.0 Intrcductlon
- For C preprooe$s&tr,
#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
- 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.
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.
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
35
#define Pl 3.14159
- Wherevet'
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
*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;
rules) as:
*
errea = (3,14159 y) +
(2' y) + 2i
li.'
.,j
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.
37
- Symbolic
float P = 2.5;
float r = 3.5, s, t, u = 1.5, v = 2.5;
38
'
slzeofQ
#if ldefined(NULL)
#define NULL
#endif
*,,.
39
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.
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
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
consider a
display screen.
t
tf
42
algorithm for particular to that problem, then algoritm is translated in
to Sre programming language code.
to
display the
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
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
is a
rl,li
i
il:l
i
;.1..,.|irJ":l I
q:,-
I
i
i+,Jti
i
-?:ri
-'t:- iril
! +,',
46
,-]
is
to
is a
1: #include
2:
3: mainQ
<stdio.F
4:{
5:
6:
7:l
printf("Hello, World!\n");
return 0;
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.
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:
.&AA
6
OPERATORS AND EXPRESSIONS
Comtent$
6.1
operator
i.e.
Arithmetic operators,
and
lncrements
in
50
Arithmetic Operatorc
Operator llleaning
Multiplication
Division
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
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
++
Decrement
Examples
a=a + 1l
a=a-1;
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("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
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
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
54
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
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.
Operator Meaning
&&
Logical AND
il
Logical OR
Logical NOT
or
evaluate
55
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 &&
evaluating
the
expression
&&
of
b:
&A OPERATOR
a
a&&b
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.
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
a<mll
a.n
).
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
s7
nm nt Operators
Operator Meaning
*l=
o/e
+=
((=
))=
$=
A3
l=
x=x+5i
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
la=a-5;
rB-=5,
__-i
iffi.**__Fl
iplse-:-q$:-: l*
:"(.'qlil*J},i
rp:rse: arigs
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
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
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 :
)perator
&
I
A
Meaning
One's Complement Operator
Risht Shift Operator
Left Shift Operator
Bitwise AND
Bitwise OR
Bitwise XOR Operator
int n = 149;
int res;
res=n&0017;
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
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
6.7.3 Right
n=1
0010000=144(decimal)
01001000=7l(decimal)
n>> 1
n>>2
0 0 1 0 0 1 0 0 = 36(decirnal)
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
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
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
Second bit
0
Resultant bit
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
of
1.
2.
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
int main$
(
67
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.
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);
69
printf ("\n");
)
getch ( );
)
OUTPUT OF THIS PROGRAM IS
t**t
***t
::::
7.3.1 Nested Loops
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
*/
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
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
{
statenpntl;
statement2;
additional code goes here
statementni
)
'/
#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)
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
if(condition){
expr_setl;
)
else {
expr_set2;
)
if(x>yX
)
else{
72
retum 0;
)
Output:
Enter value for x :20
Enter value for y: 10
X is large nurnber- 20
tf( expressron )
statementl:
nexlsfatement
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
switch(<variable>){
case this-value:
Code to execute if <variable> == this-value
break;
case that-value:
Code to execute if <variable> == that-value
break;
char.
74
{
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:
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).
#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;".
intn=0;
loop:
printf("\nolod", n);
n++,
if (n<10) {
goto loop;
)
getch0;
return 0;
)
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
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:
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.
79
3.
4.
8.2.1 Automatic
.
.
No
Property
Description
2
3
4
Keyword
Storaoe Location
Default lnitial Value
Scope
auto
Memory
Garbase Value
Life
Local
auto int i = 12 ;
printf ( 1n7od o/od', ij ) ;
)
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
to the block in
ij
ij ) ;
80
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
)
int x=l0;
/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
'
.
.
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
to
register int i
for(i=1;i<=5;i++1
printf
getch0;
('\n%d",i);
82
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
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
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!
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
Dennis M. Ritchie.
Teach yourself C in 21 days
Jones
and
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
9.2 lntroduction
*
*
*
1. What is a function?
2. Why use a function?
3. How does a function work?
E6
1.
What ls a function?
1.
Since a function is
part of
SillflT,j;#on,
3.
debugging effort.
3.
87
lglmain()
{
;;;;;il;-c
contains three
the mainfl function,
seond is fundionl$
functions. First one is
The execution of
of
or
the
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
88
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.
displaying
iil'ff:iliTiF'ffi"ii**5Au'ril"*ftu't
""
tr,r*if i
:t:
*'*t*.*..*,
*H$;ii*ft'{t
I{,e
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
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
*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
90
'lrig***rr+lti{ ,u$ttrcins
1
l;;
.j.::l
,;1::1iii1r' {.1::ii:,,'
.;l,I'. ii..,;.-
;ri
.:!:;:
;;t';
.rl ,t'
..:,^-.,,
..ijr::.i.:i.
1r.,;1.131:i
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
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,',
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
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.
91
9,4
Statementl;
Statemenl4;
Statement3;
Example
int square(int x)
x'x;
rettim
square of x:
ll
functionl0
s2
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.
x*x;
Functlon Head
The syntax fqllhgtread_d a function is
return-type
namefparameterlist)
i.
93
int square(int x
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
x*x;
retum
square of x:
ll
retums
.
o
function prototype
is
returntype function-name
list);
function
94
of
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
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
squaru
95
float area(float
length,
float breadth);
perimeter(float
side1, float side2);
float
be
);
of anqle(int.
int. int
function.
96
Passlns Arguments
9.7
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
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);
)
void swap(int m,int
n)
int temp;
97
temP =
rli
m=n:
n E"temp;
7od\n',m,n);
Output:
F$rst Run
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
.
.
Iffi
Pass by Reference
o
o
o
.
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
a=a+1 0;
cout<<b:
llwill print 30
1f,o
l*fi
ri*ft
*l*!t*trt** ******rtrl****ttttailttittaaitttitHti*r
*ttit$a***lttlt*
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
//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;
=
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
101
lrth*rt rall ir nr
callto
t*r*p{}
r*ai*{}
$i,rl*S{i
r-ml
bEi
Valueo
q^f
&
b assigned
m&n
to
interrhanged
9;7
.
Recursion
ln C , a recursive function is one which calls itself. lt is
Ex.
I void iecursive$;
void mainQ
t
recursive0;
)
void recursive$
t
recursive0;
l:_
fiz
ttt
1itfifitti*rtt*trt*'r$tt'rairttair*tt*ttttttfftttOftaaattmatffttttttoat
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;
(
int temp;
if(numUer <= 1)
(
retUm 1;
)
else
outPut'
,rrct Run
Pleace enter a positlve
4 factorlal ls: 24
integer: 4
integer:
Sccond Run
Once
function
be
103
sqFsguare(num);
olod
printf('\nSquare of
getch0;
return 0;
// Fundlon call
= %d',num,sqr);
llfile 2: square.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
a. lnformation hiding
b. Modularization of program structurc enabling separate
compiling and testing.
c. lf a function
change
is
implementation only.
104
- TMH
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
i.
ii.
10.1 Objectives
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
.
.
.
106
1.
2. Multidlmonslonal
vari$le
type
ex:
array
variablenarne
lengthofarray
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.
2.
107
roll-no[4]
'Dt
'l
name[OJ
.L'
'o'
'\0'
narne[4J
o
.
item[qtyJ;
li
108
o
.
.
o
.
#includecstdio.h>
#includecconio.h>
void mainQ
/* 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
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:
printf("%d",*m):
):
110'
1234567
int roll_no[5];
printf ( "\rrEntcr5 integcrs\n " ) ;
for(int i=0;i<5;i++)
(
IiI);
l
display( roll_no);
gctch0;
)
void display( int mll
t
for(int i-O;i<5;i++)
(
l
l
Outout
l-
11234567 _
__
Multidimensional Arra
.
.
111
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
table[O][0]
table[0][1]
table[Ol[z]
table[Ol[3]
2.
1;
=
=
=
table[1J[OJ =
2i
3;
4,
5; and so on
Ex:
int
table[3][S]
of
values
= {1, 2, 3,
4,
Or
int table[3][S] = {
(curly
112
);
0 (curly
{
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
);
)
)
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
)
)
for (1=9i<3j++;
(
scanf('%d", & b[iJ[iJ );
)
ll
for (i=0;i<3;++)
for 6=6i<3i++;
ctiltil=alilffi+blilUl;
)
)
114
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
222
222
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
from
screen
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
.
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
Following
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
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;
.
.
<string.h>
The
and
their
Appends first
{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
to case ("i'
to another.
int strcmp(
1, string2);
119
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
Solved Examples
//Demonstrate ttre use of strcpy
#include <stdio.h>
#nclude <conio.h>
#include <string.h>
void main 0
Output:
to
120
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
str2[5]=\9"
puts (str2);
getch();
To be
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
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
11.3 Rqferengesi
1.
.:".&
- TMH
12
FOINTERS
Contents
12.1 Objectives
12.2 lntroduction
12.3 Declarations
12.4 Operations on pointers
12,5 PointerArithmetic
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:
varlable
12.3 Declarations
variable is
*variablename;
basetype
where datatype is any valid datatype,
asterislr (.) is the indirection operator and
variablename is the name of the pointer variable.
int'a;
float'b;
char'c:
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;
o
a
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
m&n:
Addresses
ln the above r
m=&a;
n=fiti
125
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.
value of 650M.
. After the
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.
There
is a strong relationship
atTays.
126
char name[20], 'Ptl;
ffibeCn
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;
*n)
//definition, formal
int temp;
.Iri
127
tm
'n
*n;
=
= temp;
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
.,
.t
128
#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);
retum (a+b);
129
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.
131
.
.
o
o
o
Example:
struct student
t
char name[I0J
float height ;
int age ;
);
o
.
o
.
132
133
{
struct stud
(
char name[lOJ;
float height;
int age;
);
SttrCt StJd
pri
ntf(ln/ou\n
&s
na
getch0;
65510
65520
65524
im-
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
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:
#indudecconio.h>
#indude<strir.h>
void main$
(
int i;
struct stud
t
char name[10];
float height;
int age;
);
br(i=0;i<=100;i++1
printf ( 1n%c
getchO;
void linkfloat( )
(
floata=0,*b;
o'/ot
135
*/
b = &a ; /* cause emulator to be linked
*b
a=
; suppress the warning ' variable not used
'/
2.
function:
of s[2] */
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
Output
iiav Deenanath Chauhan
6.2000000 20
l.
137
138
pcurtiL:,ir: fcir th-l: funetiq:rn
fstn ct sttil-
Itchar name[30
I
I
I
float height;
int age;
1 ) hari;
struct stud
"p;
*,
The
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;
139
printf(1n%s\n
p rintf('\n%s\n
getch0;
o/ofln 7od\n",
o/ofl
Output
Mjay Deenanath Chauhan
6.2000000
20
VUay Deenanath Chauhan
6.2000000
2A
13.9 Union
.
.
o
type member-name1
type member-name2
type member-name3
;
;
);
For example:
union uni
int i;
char c;
);
140
time.
For Exam
union uni uname;
ffiment
which is a union.
or
o
o
or
u n io n- po i nte r->me m
ber
141
,unarne.i = 10
13.10Typedef
1.
2.
142
3.
13.l2Review Questions
1.
2.
3.
4.
5.
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
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
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.
t
,/
{
{
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
&
I
o
.
l.
2,
Text Stream
newline
character.
Binary Stream
A Binary stream is a sequence of bytes.
Files
.
.
.
.
.
.
146
.
.
1. tnterpretation of newtines
line.
2.
147
3.
o
.
.
o
.
o
.
2.
3.
2.
3.
reading.
Read data in from the file
Close the file
148
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
.
.
149
a
a
KEY FIELD
REF. FIELD
A1203
41293
41223
A2313
REF. FIELD
RECORD
ABCDEFG
ABCDEFG
ABCDEFG
ABCDEFG
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
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
t.
Venugppal
Michael J. Folk
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.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.
1. Create
2.
Delete
various
152
3.
13.12Review Questions
l.
2,
3.
4.
5.
*.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
.
.
.
.
F|LE "&;
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+
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).
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+");
Example: fclose ( fp ) ;
rernove$.
lts prototype is as follows:
of the file to be
156
a
a
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
e.
renameQ.
lts prototype is as follows:
.
.
.
l.
157
voirl main$
t
char oldname[80J, newname[8O];
printf( "An
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
vold main$
t58
char filenarne[8Ol,clu
FILE'fp;
chruetdfp);
uilrile (ch!=EOF) {
'/
ch = getc(fp);
)
fclose(h);
getch0;
Outp$
Enter file name to display contents : fl.txt
Hi how r u?
159
FILE Ts,'ft;
char ch ;
char sfilename[20J,dfilename[20J;
'f
fs = fopen ( sfilenatne,
);
if ( fs == NULL )
{
printf ( "Cannot open souroe file o/os",sfilename )
ext( );
)
ft = fopen ( dfilename,
if(ft==NULL)
t
'uf
fclose(fs);
exit( );
)
while ( 1 )
ch=fgetc(fs);
if ( ch == EOF )
llyf );
getch0;
exit();
)
else
Futc(ch,fr);
)
fclose(fs);
fclose(ft);
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
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
fiom
ofuin
fiom
position
161
fcl$se{f};
retunr 0:
OutpqB
hfrYF3t-H.Tm
Hello
lndia
how n u?
a
o
, mode);
Ex:
-l
162
Opens a file for appending
APPEND
O-BINARY
o_TElcr
.
o
o
o
o
o
o
o
lGl
gets(source);
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 )
if(bytes>0)
close(shandl");
close(thandle);
O-BINARY
164
getch0;
Filel.txt
Enter target file name:
File2.txt
File cop*/ successful
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
3.
4.
nonexistent directory or on a
a file:
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" ,
o
o
remove$.
lts prototype is as follows:
of the file to
be
{66
a
ln
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
.
.
function
qt re4eme(
o
.
.
l.
167
void main$
{
char oldname[8O], newname[8O];
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
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?
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.
r09
(o
*fs,
FILE
'ft ;
char ch ;
char sfi lename[20l,dfilename[20];
"f ) ;
ft = fopen ( dfilename,
if(ft==NULL)
t
ld
fclose(fs);
exit( ) ;
)
while ( 1
{
ch=fgetc(fs);
if(ch==EOF)
t
exit0
)
else
fputc(ch,ft):)
fclose(fs);
fclose(ft);
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
#include <stdio.h>
int main$
t
FILE
'f;
f = fopen('myfile.b(t',
opens it
'*");
position
at
from
fputs(" lndia",
position
fseek(f, 6,
position
f);
origin
"tndia,,
cunent
SEEK_CUn);
position
fputs(" how r u?",
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
fclose(f)i
retum 0;
Output
MYFILE.TXT
Hello
lndia
how r u?
u are
ttit
best!
a
O
filename, mode
Ex:
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
172
Opens a file for appending
O APPEND
O-BINARY
O TEXT
.
.
o
o
173
gets(source);
gets(target);
thandle = open
target, O_CREAT
);
O-WRONLY, S-IWRITE
if ( shandle == -1 )
close(shandle);
exit( ) ;
)
while ( 1 )
51
if(bytes>0)
close(shandle);
close(thandle);
2l
O_BINARY
174
- 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
2.
3.
4.
.:.*A