Вы находитесь на странице: 1из 494

C

C was developed
was developed in
Laboratories
outgrowth
developed at
developed at Bell
of an
in 1972
Laboratories (( now
1972 by
now ATAT &
earlier
Bell Laboratories.
Laboratories. C
by Dennis
Dennis Ritchie
& TT Bell
language
C was
Ritchie at

called
was largely
B,
at Bell

which
outgrowth of an earlier language called B, which was also
largely confined
confined to
Telephone
Bell Telephone
Bell Laboratories
Laboratories ). ). It

to use
It is
was
is an
an
also
within
use within
Bell Laboratories
Bell Laboratories until
until 1978,
1978, when
when Brian
Brian Kernighan
Kernighan and Ritchie
and Ritchie
published aa definitive
published definitive description
description ofof the
the language.
language. This
This description'
description
is often referred as "K & R
is often referred as "K & R C". C".

And after
And after this
this there
there was
was no looking back,
no looking back, as
as more
more and
and more
more computer
computer
professionals switched
professionals switched over
over to to C.
C. Today
Today there
there are
are C compilers
C compilers
available under
available every conceivable
under every conceivable environment
environment fromfrom DOS
DOS to Win-
to Win-
dows to
. dows Unix, and
to Unix, and onon all
all sizes
sizes ofof computers
computers from micros to
from micros to
mainframes. Power,
mainframes. Power, portability,
portability, performance
performance and and flexibility
flexibility are
are pos-
pos-
sibly the four
sibly the four most
most important
important reasons for C's
reasons for C's popularity.
popularity. C C has been
has been
designed to
designed to have
have aa relatively
relatively good progamming efficiency
good progamming efficiency as com-
as com-
pared to
pared to Machine
Machine oriented
oriented languages
languages likelike Assembly
Assembly or Machine
or Machine
language,
language, and and aa relatively
relatively good
good machine
machine efficiency
efficiency as compared to
as compared to
Problem oriented languages like COBOL
Problem oriented languages like COBOL and FORTRAN. and FORTRAN.

Variables and
Variables Constants in
and Constants in C
C

Simply put,
Simply put, aa variable
variable isis aa tool
tool to
to reserve
reserve space
space in computer's
in computer's
memory. The
memory. The reserved
reserved space
space is given aa name,
is given name, which
which we
we call
call aavariable
variable
The ABC Of C
TheABCO[C 33

name.
name. Constants
Constants areare stored
stored inin this
this reserved
reserved space.
space. The
The constants
constants
stored in the space reserved by the variable may vary from time
stored in the space reserved by the variable may vary from time to
to .
time,
time, hence
hence the
the name
name variable.
variable. The
The name
name once
once given
given to
to aa location,
location,
however,
however, remains
remains unchanged.
unchanged. ThusThus in inthe
the statement,
statement,

ii==55

55 isis aa constant
constant which
which isis being
being stored
stored inin aa location
location which
which hashas been
been
given a name i. So, i is a variable just as a, x, note or str are. They
given a name i. So, i is a variable just as a, x, note or str are. They
all
all designate
designate memory
memory locations
locations that
that will
will hold
hold different
different values
values as-
as-
signed
signed to to these
these variables
variables from
from time
time to
to time.
time.

Depending
Depending on on the
the purpose
purpose forfor which
which you
you want
want to
to utilize
utilize memory,
memory, CC
allows
allows you
you to to decide
decide howhow much
much memory
memory to to allocate
allocate toto aa variable.
variable.
Accordingly
Accordingly memory
memory comescomes in in three
three convenient
convenient versions:
versions: char,
char, int
int
and float, which occupy 1,2 and 4 locations ( bytes ) respectively. A
and Ooat, which occupy 1, 2 and 4 locations ( bytes) respectively. A
char can store values in the range -128 to +127, whereas an int can
char can store values in the range -128 to +127, whereas an int can
store
store values
values in in the
the range
range -32768
-32768 to to +32767.
+32767. When
When do do we
we use
use float?
Ooat?
When
When we we want
want to to store
store numbers
numbers like like 3.1415,
3.1415, oror 0.0005672
0.0005672 in in
memory.
memory. A float can store values ranging
AOoatcanstorevalues from -3.4e+38to +3.4e+38.
rangingfrom-3.4e+38to +3.4e+38.
Now
Now that
that is
is certainly
certainly aa very
very impressive
impressive range!
range!

The
The memory
memory occupied
occupied by
by each
each datatype
datatype can
can be
be found
found out
out using
using an
an
operator
operator called
called sizeof.
sizeof. For
For example,
example, sizeof
sizeof ((i int
n t )) would
would yield
yield 2.
2.
Similarly,
Similarly, sizeof
sizeof (( float
float) ) would
would yield
yield 4.
4. The
The essence
essence of
of these
these
datatypes
datatypes has
has been
been captured
captured inin Figure
Figure.1.1.
1.1.

The chars
chars and ints can also bebe expressed in hexadecimal and octal
octal
notations. For example, 16 can be expressed in hex as 0x10,OxlO, and as
020 in octal. Similarly, 22 can
can be expressed in hex as 0x16,
Ox16, and
and as
026 in octal. A hex number is always preceded by Ox or OXwhereas
Oxor OX whereas
an octal is preceded by 0 ((zero,
zero, not o0 or O ). C doesn't accept floats
0). floats
in hex or octal.
in hex or octal.

With constants out of the way, let us now take a look at the variables.
variables.
Certain rules have been framed
framed to create variable names. A variable
variable'
4 Exploring C
Exploring C

name can
name can be
be any
any combination
combination of
of alphabets, digits and
alphabets, digits and an
an underscore,
underscore,

Underflow -- Seam -- Overflow


+ve overflow
13.4e38

I1.Oel

II.OeO

I1.Oe-l

[@
+ve underflow

Underflow __ Seam -- Overflow


I 0.0 I
-ve underflow

1-1.Oe-q

1-1.0e0 I
1-1.Oel I

I
1-3.4e381
-ve overflow
'Float ranges
Figure 1.1
Figure 1.1 Integer,
Integer, Character and Float
Character and ranges
Float ranges

with aa proviso
with proviso that
that the
the first
first character
character is
is an
an alphabet.
alphabet. The
The length
length of the
of the
variable is
variable is aa compiler
compiler dependent
dependent feature.
feature. Turbo
Turbo C
C accepts
accepts aa variable
variable
name upto
name upto 32 characters.
32 characters.
The ABC Of C
TheABCO[C 5

Operations
Operations on Data

C 'programs
C programs are are concise
concise partly
partly because
because of of the
the large
large number
number ofof
operators available
operators available with it. There
with it. There areare as
as many
many as as 45
45 operators avail-
operators avail-
able in
able in C.
C. For
For starters
starters we
we will
will concentrate
concentrate only
only on on arithmetic and
arithmetic and
assignment operators..These
assignment operators ..These are are shown
shown inin the
the Figure
Figure 1.2. Operators
1.2. Operators
are classified
are classified as
as unary,
unary, binary
binary or or ternary
ternary depending
depending on on the
the number
number of
of
operands they
operands operate upon.
they operate upon. ForFor example,
example, + is is aa binary
binary operator
operator since
since
it operates
it on two
operates on two operands
operands thatthat it
it adds.
adds.

Operators Name Type

Unary minus Unary


+- * /% Arithmetic Binary
= Assignment Binary

Figure 1.2 Arithmetic


Figure 1.2 Arithmetic and
and Assignment
Assignment Operators
Operators

Except for
Except for %
% the
the other
other operators
operators are
are as
as usual.
usual. %% is
is read
read asas 'modulus'
'modulus'
operator, and
operator, it returns
and it returns the
the remainder
remainder onon dividing
dividing an
an int
int with another.
with another.
As against
As against this,
this, aa /I returns
returns the
the quotient.
quotient. While
While evaluating
evaluating an expres-
an expres-
sion,- C gives priorities to some operators above the others.
sion, C gives priorities to some operators above the others. A unary A unary
minus has
minus has the
the highest
highest priority,
priority, followed
followed by by arithmetic
arithmetic operators
operators andand
lastly the
lastly the assignment
assignment operator.
operator. Within
Within arithmetic
arithmetic operators,
operators, *, *, /I and
and
% enjoy
% enjoy aa higher
higher priority
priority than
than + and
and -.-.
66 Exploring C
ExploringC

Integer and Float Co


Integer Conversions
nverslous

is important
It is important to
to understand
understand the
the rules
rules that
that govern
govern the
the conversion
conversion of
of
floating point
floating point and
and integer valuessin
integer value in C.
C. These
These are
are mentioned below..
mentioned below

(a)
(a) An arithmetic
.An arithmetic operation bbetween
etween an an integer
integer and
and integer
integer always
always
yields an
yields integer result.
an integer result.
(b) An
An arithmetic between aa Ooat
arithmetic operation between float and
and Ooat
float always
always
yields a Ooat
float result.
result.
(c)
(c) operationn between
In an arithmetic operatic between an an integer
integer and
and Ooat,
float, the
the
integer is first promoted to to Ooat
float and
and then
then the
the operation
operation is is
carried out. And hence it always
always yields
yields aa Ooat
float result.
result.
(d)
(d) On assigning a Ooatfloat to aann integer
integer (( using
using the =
the = operator)
operator ) the
the
float
Ooat is demoted to an int integer.
eger.
(e)
(e) assigning an integer ttoo aa float,
On assigning float, it
it is
is promoted
promoted to to aa Ooat.
float.

The following figure illustrates these conversions,


illustrate s these conversions, demotions
demotions and
and
promotions. Assume
promotions. i to be an iint
Assume ito and aa to
nt and to be
be aa Ooat.
float.

Operation
Operation Result
Result Operation
Operation Result
Result

ii = = 5/2
5/2 22 aa =5/2
= 5/2 2.0
2.0
ii = = 5.0/2
5.0/2 22 aa =
= 5.0/2
5.0/2 2.5
ii = 5/2.0
5/2.0 22 aa = = 5/2.0
5/2.0 2.5
2.5
ii == 5.0/2.0
5.0/2.0 22 aa =5.0/2.0
=5.0/2.0 2.5
2.5
ii =
= 2/5
2/5 0U aa = = 2/5
2/5 0.0
0.0
ii = = 2.0/5
2.0/5 00 aa = = 2.0
2.0/5
/5 0.4
ii = = 2/5.0
2/5.0 00 aa = = 2/5.0
2/5.0 0.4
0.4
ii = = 2.0/5.0
2.0/ 5.0 00 aa = = 2.0/5.0
2.0/5.0 0.4

Figure 1.3 Integer


Figure 1.3 Integer and
and Float
Float Co
Conversions
nversions
The ABC Of C
TheABCO[C 7

printf() and scanf(


scanf())
printf()
pri ...tf( ) is one of the most versatile statements in C. In fact,
fact, itit is
is aa
standard library function used to display the output onon the screen. TheThe
general
general form
form ofof printf()
printf( ) looks
looks like
like this...
this...

printf ("Format
( "Format string", list
lislofof variables);
variables) ;

And here are a few examples...


examples ...

printf ("%c
( "%c %d %f, name, age, sal);
%f~,name, sal) ;
printf ("name
( "name = %c age ==%d
%c age salary==%f,
%dsalary %f, name,
name,age,
age,salsal);
);
printf ("name %c\nage ==%d\nsalary
("name = %c\nage %d\nsalary==%f',
%f, name,
name,age,
age,sal)
sal);
;

Assuming
Assuming the value of name
name as 'A',
'A', that of
of age as 23,
23, and that of
of sal
as 1500.00, the output of the above printf(
printf( )s would be
be

A 23 1500.000000
A 23 1500.000000
name = = AAage
age==2323salary
salary==1500;000000
1500.000000
name=A
name e A
age = 23
23
= 1500.000000
salary =

The first printf()


printf( ) prints the values of the variables name,name, age and
sal.
sal. As
As against
against this,
this, the
the second would print
second would print messages
messages against
against each
each
value
value displayed.
displayed. InIn the
the third
third printf(),
printf(), the
the \n is
is used
used to
to send
send the cursor
the cursor
to
to the
the next
next line,
line, hence
hence the
the three
three values
values are
are printed
printed on
on three different
three different
lines.
lines. .

Sometimes
Sometimes the list of variables
variables may be dropped, as in,

printf ("Enter
( "Enter values of a and b");
b" ) ;

In this case everything


everything enclosed within the pair of double quotes
would be printed as it is on the screen. '
88 Exploring C
Exploring

Having imbibed
Having imbibed those
those details, now let
details, now let us
us switch
switch over
over to scanf().
to scanf( ).
scanf( ) is
scanf() is once
once again
again aa standard
standard library
library function.
function. It
It is
is used
used to receive
to receive
values of
values of variables
variables from
from the
the keyboard.
keyboard. ForFor example,
example, the following
the following
scanf()) would
scanf( would let
let you supply the
you supply values of
the values variables aa and
of variables and b.
b.

scanf (("%d%f,&a,&b);
scant "%d %f, &8, &b) ;
>
The general form
The general form of
of scanf(
scanf()) is
is almost
almost similar
similar to
to printf(
printf( ),
), except
except for
for
two important
two important differences:
differences:

(a)
(a) Within
Within the
the pair of double
pair of double quotes
quotes there
there should occur only
should occur only format
format
specifications like
specifications like %c,
%c, %d,
%d, %f etc.
%f etc.
(b)
(b) The variable names
The variable must always
names must always be preceded by
be preceded by the
the 'address
'address
of operator
of' operator &.
The ABC OfC
TheABCO/C 9

Exercise
Exercise

[A] Complete
Complete the following:
following:

(1)
(1) developed by
C has been developed in the year while
year_while
working at
working at __.

(2)
(2) Binary equivalent
equivalent of 762 is , its octal.equivalent is
and its hex equivalent
equivalent is __ .

(3) Maximum
Maximum allowable width of a variable in Turbo C is _
characters.
characters.

(4) First character


character in any variable name must always be an aa_. .

(5) C variables
variables are case ( sensitive / insensitive
insensitive).).

(6) A character
character variable can at a time store _ characters).
character(s).

[B] Point out which of the following variable names are invalid:

gross-salary
gross-salary
INTEREST
INTEREST
salary
salary of emp
emp
avg.
thereisagirlinmysoup
thereisagirlinmysoup

[C]
[C) Point out which of
of the following C constants are invalid:

124.567
124.567
0001
0xbc40
Oxbc40
0Xbc40
OXbC40
0x12.45
Ox12.45
. Oxfgff
Oxfgff
10
·10 Exploring/C
E'xplorin&lC

.001
.001
-12e-12
-12e-12

[D]
[D] What will
What will be
be the
the output
output of
of the
the following
following programs:
programs:

(1)
(1) main()
main()
{
{
,
printf (("%d
printf ·%d %d
%d%d
%d%d",
%d",72,
72,072,0x72,0X72);
072, Ox72, OX72) ;
}}

(2)
(2) main()
main()
.{{
printf("%d%o%x",72,72,72);
printf ( "%d %0 %x·, 72, 72, 72) ;
}}

(3)
(3) main()
main()
{{
charch;
char ch;
int a;
inta;
float b;
float b;
printf ( "bytes occupied
printf ("bytes occupied by
by ch
ch ==%d\n",
%d\n",sizeof
sizeof( ch ));
(ch));
printf ("bytes
printf ( ·bytes occupied
occupied by
by aa == %d\n·,
%d\n",sizeot
sizeof( a)
( a ) ); ;
printf ("bytes occupied by b = %d\n", sizeof ( b ) ); ;
printf (·bytes occupied by b = %d\n", sizeof (b)
}}

(4)
(4) main()
main()
{{
printf (·char occupies
printf ("char occupies %d
%dbytes\n",
bytes\n",sizeof
sizeof( (char));
char) ) ;
printf (Oint occupies %d bytes\n·, szeot (int)
printf ("int occupies %d bytes\n", sizeof (int)); );
printf ("float
printf ( "float occupies
occupies %d
%d bytes\n·" sizeof (float)
bytes\n"„sizeof );
(float));
}}

main()
main()
{
printf ("bytes
plrntf occupied by
( ·bytes occupied by '7'
7' ~= %d",
%d",sizeof
sizeof( '7'
( T) )) ); ;
printf ("bytes occupied by
(·bytes occupied by 77 =\%d",
=i%d",sizeof
sizeof (7)
( 7 )));;
The
The ABC
ABC Of
Of C
C 11
11

printf ("bytes by 7.0 == %d",


( "bytes occupied by %d",sizeof
sizeof(7.0))
(7.0));
;
I1

(6) main()
{{
char ch
char ch == 291
291;;
printf ("%d
( "%d %d %c", 32770, ch, ch);
ch) ;,
}}

(7) main()
{{
printf ("%d%c\n");
printf ( "%d %c\n" ) ;
printf (("%d%c\n");
"%d %c\n" ) ;
}}

(8) main()
{{
int a == 33000
int 33000;;
float bb==3.4e1
float 00 ;
3.4e100;
printf ("a = %d
printf("a = %db b ==%f\n", a, b) ;
%f\n",a,b);
printf ( "%d %d", sizeof ( a), sizeof (( b)
printf ("%d %d", sizeof (a), sizeof b ) )) ;;
}}

(9) main()
{{
int a,
int a, b;
b;
aa=-3--3;
= -3--3;
= -3-3--(-3);
bb = - -(-3) ;
printf
printf("a( "a == %d
%dbb ==%d", a, b) ;
%d",a,b);
}}

(10) main()
main()
{{
tnt x;
intx;
x = 3*4%5;
x=3*4%5;
printf ("x
printf = %d";
( "x = x) ;
%d",x);
12
12 Exploring
Exploring C

}}

(11) main()
(11) main()
{{
intx;
intx;
x = 3 + 4-7*8/5%10;
x=3+4-7*8/5%10;
printf ("x
printf = %d",
( "X = %d",x)x );;
}}

(12) main()
(12)
{{
intx;
intx;
x = -3 + 4 - 7 * 8 / 5 % 1 0 ;
x=-3+4-7*8/5%10;
printf ("x
printf ( "x = %d",x)i
= %d", x) ~
}}

(13) main()
(13) main( )
{{
intx;
int x;
x = 4%5 + 6%5;
x=4%5+6%5;
printf (·x
printf (*x == %d",
%d",x);
x) ;
}}

(14) main()
(14) main( )
{{
intx;
int x;
x = -3M%-6/-5;
x=-3*-4%-6/-5;
printf ("x
printf = %d",
( 'x = %d",x);
x) ;
}}

(15) main()
(15) main()
{{
printf (("%d
printf "%d .,",4/3);
4/3) ;
printf ("%d", 4/
printf ( "%d ", 4 / --3)
3 ) ;;
printf ("%d ",-4/3);;
printf ( "%d ", -4/3)
printf ('%d
printf ("%d",-4/-3);
" -4/-3) ;
The ABC
The ABC Of
0/ C
C 13
13

(16)
(16) main()
main()
{
{
printf ("%d",
printf ("%d ", 44% % 3)
3 ) ;;
printf ("%d ",4%-3);;
printf ( "%d ., 4 % -3)
printf ("%d
printf ( "%d .,, -4
-4 %
M % 3)
3 ) ;;
printf ("%d ",-4%-3);;
printf ( "%d ., -4 % -3)
}

(17)
(17) main()
main( )
{{
ffloat
loat aa == 5,
5, b
b ==22;;
int c;
int c;
cc== a%b;
a% b;
printf ("%d",
printf ( "%d", cc)) ; ;
}

(18)
(18) main()
main()
{{
intx;
int x;
xx==33**** 44 -- 77 88,;
;
A1\

printf ( 'x==%d",x);
printf("x %d·, x) ;
}

(19)
(19) main()
main( )
{ {
300 ** 300
intintg9==300 /300 ;
300/300;
printf ( "9 = %d·,
printf ("g = %d",g); g) ;
} }

(20)
(20) main()
main()
{ {
float a = 1.5;
floata=1.5;
intintbb== 3;
3;
a=b/2tb*8/b-bta/3;
a = b/2 + b * 8 / b - b + a / 3 ;
1414 ExploringCC
Exploring

printf u
a ==%f
printf( ("a %f', aa);
,
I );
}
}

(21) main()
(21) main()
{
{
intinti i== 3,3, aa == 4,
4, nn;;
float t =
float t = 4.2.; 4.2.;
nn=a*a/i+i/2*t+2+t;
= a * a / i + i/2*t + 2 + t;
printf ("n
printf ( nn== %d",
%d", nn)) ;;
}

(22) main()
(22) main()
{
{
intqq== 2,
int 2, dd == 3,
3, st;
st; .
st=q*d/_4-12/12+12/3*16/d;
st = q*d/4-12/12+ 12/3*16/d
printf ( ·st== %d",
printf ("st st) ;
%d", st);
}
}

(23) main()
(23) main()
{{
inta,at b;
int b;
a =
a = 5.999999;;
5.999999
bb == 5.000001;
5.000001 ;
printf ( "a== %d
printf {"a %d bb == %d",
%d", a.
a, b)
b ) ;;
}
}

(24) main()
(24) main()
{
{
floata;a;
float
aa=4/2;
=4/2;
printf ( "%1%1·, a. 4/2) ;
.. printf("%f%f,a,4/2);
}}

(25) main()
(25) main()
{{
printf ("%d
printf ( "%d %An",
%1\n", 4,
4 , 4)
4 ) ;;
TheABCO[C 15

printf
printf ("%d%f\n",
( ·%d %1\n',4.0,4.0);
4.0,4.0) ;
}}

(26)
(26) main()
main()
{{
f1oala=4;
float a = 4;
int i ==2;2;
inti
printf ("%f
printf ( "%f %d",
%d", i/a,
i / a, ii // aa)) ;;
printf("%d%',
printf i/a, i/a};
("%d%f,i/a,i /a);
}

(27) main()).
(27) .main(
{{
printf ("%d
printf ( "%d Vsizeof
",rsizeof (4)
( 4 ) // sizeof
sizeof (2.0));
(2.0) ) ;
printf ("%d",
printf ( "%d ., sizeof
sizeof (2.0)
( 2.0) // sizeof
sizeof (( 44)) )) ;;
}}

(28)
(28) main()
main()
{{
printf ("nn
printf ( "nn \n\n
\n\n nn\n");
nn\n") ;
printf ( "nn Inln nn/n·
printf ("nn /n/n nn/n"););
}}

(29) main()
main()
{{
int p,
int P, q;
q;
scant ( "Enter values
scanf ("Enter values of
of pp and
and qq %d
%d %d",
%d", &p,
&p,&q) ;
&q);
printf ( 'p = %d q = %d·, P,
printf ("p = %d q = %d", p,q); q) ;
}}

(30) main()
main()
{{
int a,
int a, b;
b;
printf ( "Enter values
printf ("Enter values ofof aa and
and b·)
b " ) ;;
scant (' %d %d ",
scanf (" %d%d ",&a,&b); &a, &b) ;
printf ("a
printf ( "a = %d bb ==%d",
= %d %d",8, b) ;
16
16 Exploring C
Exploring C

}}

(31) main()
(31) main()
{{
int p, q;
q;
printf (("Enter
"Enter values
values of p and qq");.) ;
scant ("%d\n\n%d",
( ·%d\n\n%d &p,&q);
&p, &q) ;
U
,

printf ("p
('p = %dqq ==%d",
= %d %d",p,p,q)q );;
}}

(32) main()
(32) main()
{{
int p, q;
q;
prinff (("Enter
printf "Enter values
values of
of pp and
and qq");
") ;
scant ("%d
scant ( "%d %d·,
% d \ p,
p ,q)
q ) ;;
( "p == %d
printf ("p %dqq ==%d·,
%d",p,p,q);
q) ;
}}

(33) main()
(33) main()
{{
1*
/* This
This program
program attempts
attempts to
tofind
findwhat
whathappens
happenswhen
when
integer range 1* -32768 to +32767 */
integer range I* -32768 to +32767 */ is is exceeded */ */
exceeded

int
int aa = 330000;
= 330000;
float b == 3.4e100
3.4e100;;
printf("a
printf ( "a = %db
= %d b ==%1\n·,
%f\n"a,a,b);
b) ; I

}}

(34) main()
.(34) main( )
{{
printf
printf (("Menu
"Menu is
is aa list
list of options you
of options you have
have atat aa \\
particular point in a program. It is
particular point in a program. It is just \ just \
like
like aa restaurant
restaurant menu
menu -- everything
everything hashas aa \\
misleading name and what you
misleading name and what you want is want is never
never \\
available .•
available."); ) ;
}
}

L
The ABC O[C 17

fE]
[E] Attempt
Attempt the following:
following:

(1) Write a program to round off an integer ii to the next largest


multiple of
multiple of another
another integer
integer j.
j . For
For example,
example, 256
256 days
days when
when
rounded off to the next largest multiple divisible by a week
rounded off to the next largest multiple divisible by a week
results
results into 259.
into 259.

(2) Temperature
Temperature of a city in farenheit degrees is entered through
through
the keyboard.
the keyboard. Write
Write aa program
program toto convert
convert and
and print the
print the
temperature in centigrade
temperature in degrees.
centigrade degrees.

(3) Two variables


variables a and b contain values 10 and 20. Write a
program to
program to interchange
interchange the
the contents of aa and
contents of and b
b without using
without using
a third variable.
variable.

(4)
(4) Write aa program
Write program to find out
to find how many
out how many days
days and
and how
how many
many
weeks have
weeks passed between
have passed between the
the dates
dates 01/01/92
01/01/92 to
to 31/05/92.
31/05/92.
Also find out
Also find out how
how many
many days
days could
could not
not get
get evened
evened out
out into
into
weeks.
weeks.
18
18 Exploring
Exploring C

Answers
Answers

Answers to [A]
Answers to [A]

(1)
(1) Dennis R
Dennis i t c h i e , 1972,
Ritchie, 1972, A merican
American Telegraph
Telegraph &
&
Telecommunication's
Telecommunication's Bell Laboratories
Bell Laboratories

(2)
(2) 1011111010,1372, 2FA

The way
The way to to convert
convert aa decimal
decimal number
number to to binary,
binary, octal or
octal or
hexadecimal is
hexadecimal is as
as shown
shown in in Figure
Figure 1.4.
1.4. Take
Take the
the case
case ofof
conversion to
conversion to binary first. Since
binary first. Since binary
binary numbering
numbering system
system isis aa
base 22 numbering
base system, we
numbering system, we carry
carry out
out divisions
divisions successively
successively
by 22 till
by till we
we get
get aa zero.
zero. The
The remainders
remainders obtained,
obtained, when
when written
written
in reverse
in reverse direction yield the
direction yield the binary
binary equivalent.
equivalent. Similar proce-
Similar proce-
dure is
dure is carried
carried out
out for
for conversion
conversion to to octal
octal and
and hexadecimal,
hexadecimal,
only difference
. only difference being
being instead
instead of of 22 we
we carry
carry out
out divisions
divisions byby 88
and 16
and 16 respectively
respectively for for octal
octal and and hex.
hex. Also
Also note
note that octal
that octal
numbering system
numbering system is is aa base
base 8 8 numbering
numbering system,
system, and hence
and hence
any number
any number in in this
this system
system is is built
built asas aa combination
combination of of digits
digits 00
to 7. Similarly, hex is a base 16 numbering
to 7. Similarly, hex is a base 16 numbering system, and any system, and any
number in
number in hex
hex is constructed using
is constructed using 1616 digits 0 to
digits 0 to 9
9 and
and A A to
to FF
( A being
(A being 1010 and
and FF being
being 15 15 ).).

Once we
Once we have
have obtained
obtained thethe binary
binary equivalent there is
equivalent there is aa simpler
simpler
and faster
and faster way
way ofof obtaining
obtaining the the octal
octal and
and hexadecimal
hexadecimal
equivalent. Let
equivalent. Let us
us first
first convert
convert 1011111010Ao
1011111010 to octal.octal. All
All that
that
we need
we need to do is
to do is pick
pick up
up 33 digits
digits at
at aa time
time (( from
from right
right to left)
to left)
and then
and then go
go on
on writing
writing their
their octal
octal equivalents
equivalents as as shown below.
shown below.

11 011
011 111010
111 010
1 33 7 22
1

For example,
For example, octal
octal equivalent
equivalent ofof 010
010 is 2, whereas
is 2, whereas octal
octal
equivalent of 111 is 7 and so on.
equivalent of 111 is 7 andso on.
The ABC oic
Of C 19
19

The same method can be used to convert 011111010


011111010 to its
hex equivalent.
equivalent. Only difference being this time we would take
at a time.
4 digits ilt time. This is shown below.
below.

101111 1010
1011111010
2 F A

22 762
762 8
8 762
762 16 762
2
2 381 00 8
8 95 2
2 16 47 A
16 47
16~ A
22 190 11 88 11 77 16
16 2 FF
22 95 00 88 1 33 0 22
22 47 11 0 11
22 23 11
22 11 11
22 5 11
22 2 11
22 1 00
0 11

1.4
Figure 1.4

(3) characters
32 characters

This maximum allowable


allowable width changes from from compiler to
compiler. Some
compiler. Some compilers like Turbo
compilers like Turbo CC allow
allow the
the user
user to
to set
set
this maximum width
this maximum width through
through its
its Integrated
Integrated Development
Development En- En-
vironment
vironment (( IDE
IDE) ) by
by selecting
selecting items
items from
from the
the menu
menu inin the
the
order: Options, Compiler,
order: Options, Compiler, Source,
Source, Identifier
Identifier length.
length.

(4) alphabet
alphabet

(5) sensitive. This means that variables sal, Sal and SAL would
sensitive.
be treated as different variables
variables in C.
20
20 Exploring
Exploring C
C

(6)
(6) only
only one
one character.
character. In
In fact,
fact, if
if we
we execute
execute the
the following
following state-
state-
ments,
ments, what
what gets
gets stored
stored inin variable
variable ch
ch is
is not
not really
really the character
the character
constant,
constant, but
but the
the ascii
ascii value
value ofof 'A', which
which is is 65.
65.

char ch;
ch;
ch =='A';
,
A; 1

Answers
Answers to
to [B]
[B]

gross-salary
gross-salary - Because
Because aa minus
minus (( --) ) is
is not
not allowed
allowed inin
the
the variable
variable name.
name. However
However an an under-
under-
score
score (_
( _ )) is
is acceptable.
acceptable.

salary
salary of em
empp - Because
Because spaces
spaces are
are not
not allowed
allowed within
within aa
variable
variable name.
name. Thus, salaryofemp
Thus, salaryofemp
would
would have
have been
been acceptable.
acceptable.

avg. - Because
Because aa V
'.' is
is not
not allowed
allowed in
in the
the vari-
vari-
able name.
able name.

Answers
Answers to [q
to [C]

0x12.45
Ox12.45 - Because
Because C C accepts
accepts only
only integers
integers in
in octal
octal
and
and hexadecimal
hexadecimal numbering
numbering systems,
system!',
not floats.
not floats.

Oxfgff
Oxfgff - Because
Beca use ''g'
g ' cannot
cannot be
be aa part
part of of aa
hexadecimal number. Only alphabets al-
hexadecimal number. Only alphabets al-
lowed
lowed in
in aa hex
hex number
number are
are aa to
to f,f, or
or A to
A to
F.
F.

Answers
Answers to fD]
to [0]

(1) Output
Output

/258 114 114


1258114114
The ABC Of Cotc 21

Explanation
Explanation

C accepts integer
C accepts integer constants
constants in
in three
three numbering
numbering systems
systems --
decimal, octal and hexadecimal.
hexadecimal. To differentiate between the
three, C
C specifies that the octal integer must be preceded by a
0, whereas
whereas a hex integer must be preceded by Oxor
Ox or OX.
OX.

In this example,
example, we are printing 072,
072,0x72 and OX72using
Ox72and 0X72 using %d.%d.
%d specifies
%d specifies that
that the
the value
value should be printed
should be as aa decimal
printed as decimal
numbering
numbering system
system integer
integer (( hence
hence the
the dd ).
). Therefore,
Therefore, decimal
decimal
equivalents
equivalents ofof octal
octal 072,
072, hex
hex 0x72 and 0X72
Ox72and get printed.
OX72get printed.

(2)
(2) Output
Output

7211048
7211048

Explanation
Explanation

Here %d%d prints out as a decimal number, whereas %0


%o prints
octal
octal equivalent
equivalent of
of 72
72 and
and %x
%x prints
prints hexadecimal equivalent
hexadecimal equivalent
of 72.
of 72.

(3)
(3) Output
Output

ch == 11
bytes occupied by ch
bytes occupied by a == 22
bytes occupied by b == 44

Explanation
Explanation .

sizeof is an operator which yields the memory occupied ( in


bytes)) by
bytes by its
its argument.
argument. In
In C,
C, aa char
char is
is always
always 11 byte
byte long, an
long, an
int is always
int is always 22 bytes
bytes long,
long, and
and aa float is always
float is always 44 bytes
bytes long.
long.
Hence the output.
Hence the output.
22
22 Exploring C
Exploring C

(4)
(4) Output
Output

char occupies 11 bytes


char occupies bytes
int occupies 22 bytes
int occupies bytes
float occupies
occupies 4 bytes

Explanation
Explanation

sizeofisis an operator
sizeof operator which yields the memory occupied by its
argument
argument in in bytes.
bytes, sizeof
sizeof can
can take
take asas its
its argument
argument not
not only
only
variables (( as
variables as shown
shown in in the previous example
the previous example ), ), but
but also
also the
the
datatypes themselves. Output,
datatypes themselves. Output, as
as expected,
expected, would
would bebe 1,
1, 22 and
and
4,
4, confirming
confirming thethe fact
fact that
that in C, aa char
in C, char isis always
always 11 byte
byte long,
long,
an int is
an int is always
always 22 bytes
bytes long,
long, and
and aa float
float is
is always
always 44 bytes
bytes long.
long.

(5)
(5) Output
Output

bytes occupied by
bytes occupied by 7' = 22
'7' =
bytes by 77 ==22
occupied by
bytes occupied
bytes occupied by
bytes occupied by 7.0
7.0 ==88

Explanation
Explanation

A small surprise!
surprise! Size of '7' is reported as 2. How come? come?
Because when
Because when we we say '7', we
say '7', we arereally
are really specifying
specifying the the ascii
ascii
value
value ofof 7,
7, which
which isis 55,
55, an
an integer,
integer, and
and hence
hence itsits size
size is
is 2.2. The
The
second output is
second output as expected
is as expected -- an
an integer
integer 77 being
being reported
reported as as
occupying 2 bytes in memory. Third output is of
occupying 2 bytes in memory. Third output is of course unex-course unex-
pected.
peered. We We were
were really
really expecting
expecting 44 instead
instead of of 8.
8. This
This soso
happens because aa floating
happens because floating point
point constant
constant by
by default
default isis stored
stored
as
as an
an 88 byte
byte number.
number. TheThe same floating point
same floating point constant,
constant, if if stored
stored
in
in aa float
float variable,
variable, would
would bebe stored
stored as
as aa .4
4 byte
byte number.
number.
Consider
Consider the following example.
the following example.
The ABC Of
O[ C
C 23
23

float aa =
float = 0.7;
0.7;
printf ((*%d %d", sizeof
"%d %d", sizeof ((a), sizeof ((0.7));
a), sizeof 0.7) ) ;

Here the output would


would be 4 and 8, confirming the fact men-
tioned above.
tioned above. •

(6)
(6) Output
Output

-32766 35 #
-3276635#

Explanation
Explanation

32770 falls outside


32770 falls outside the
the integer
integer range
range (( -32768
-32768 to
to +32767
+32767 ))
hence goes to the
the other side and becomes an appropriate
I

negative number (-32766)


negative number which gets
( -32766 ) which gets printed.
printed.

Same thing
Same thing happens
happens toto 291,
291, which
which also
also falls
falls outside
outside the
the range
range
of char
of char (( -128
-128 to
to +127
+127 ),), hence
hence goes
goes to
to the
the other
other side and
side and
becomes
becomes 35,35, which
which is
is then
then printed.
printed. The
The third
third output
output is
is the hash
the hash
character.
character. This is nothing
This is nothing but
but the character corresponding
the character corresponding toto
ascii value 35. %c always prints the character corresponding
ascii value 35. %c always prints' the character corresponding
to the ascii
to the ascii value.
value.

(7)
(7) Output
Output

-22A
-22 A
-22A
-22 A

Explanation
Explanation

Here, even
Here, even though
though we have not
we have supplied any
not supplied any variables
variables to
to
printf( ), still
printf( ), still some
some garbage
garbage integers
integers (( for
for %d
%d )) and characters
and characters
((for
for %c)
%c ) get printed.
printed. This is however true only of cnaracters
characters
and integers.
integers. For example try the following statement:
statement:
24
24 Exploring C
Exploring Q

printf (("%f%f);
"%f %f ) ;

This statement
statement gets compiled,
compiled, but during run-time
run-time it flashes
it flashes
the error message:
message: printf:
printf: floating point formats not linked,
Abnormal program termination.
termination.

(8)
(8) Output
Output

aa == -32536 b ==tlNF
-32536b +INF
24
24

Explanation
Explanation

33000 exceeds the valid integer range, whereas 3.4el003.4elOO ex-


ceeds the valid float range. In the first case the number from
the other side of the range is picked up, which in this case turns
out to be -32536.
-32536. However,
However, in case of 3.4el00
3.4elOO the printf(
printf())
simply prints out +INF, which should be read as 'plus infinity',
infinity',
telling
telling us
us that
that we
we are
are going
going beyond the valid
beyond the valid float
Ooat range
range on
on
positive
positive side.
side. If
If we
we attempt
attempt to
to print
print out
out -- 3.4el00,
3.4eloo, printf(
printf( ))
would
would output
output -INF.
-INF.

Whether the range is exceeded or not, the number


number. of bytes
occupied by variables
variables a and b in memory remains unchanged
- 2 for an int
int and 4 for a Ooat.
float.

(9)
(9) Output
Output

aa=Ob=-6
= 0b = -6

Explanation
Explanation

'Minus ofof minus is plus'.


plus'. This
This, is true in
in usual
usual arithmetic, so
also in C. Hence -3
·3 -• -3
·3 becomes -3 ·3 ++ 3, which is equal to 0,
is.equal
and is assigned to variable a. Similarly, while evaluating the
The ABC Of C
O[ C 25
25

next statement,
statement, -(-3) becomes
becomes +3 and therefore the statement
gets reduced
reduced to -3 - +3, which is equal to -6. This -6 is assigned
to variable
variable b. The values
values of a and b are then outputted through
printf().
printf( ).

(10) Output
(10) Output

xx=2
=2

Explanation
Explanation

The first operation performed here is multiplication, which


yields 12. And then 12 % % 5 is performed, which yields the
the
remainder
remainder 2. This 22 is assgined to the variable x and
and then
then
printed
printed out.
out.

(1.1) Output
(11) Output

xx=6
=6

Explanation
Explanation

While
While evaluating
evaluating an an expression,
expression, the
the order
order in
in which
which the
the opera-
opera-
tions
tions are
are performed
performed dependsdepends upon
upon the
the priority
priority ofof operators
operators
involved.
involved. In In this
this example,
example, the the operations
operations are
are performed
performed inin the
the
order
order **,, //,, %
%,, ++ and
and -.-. Thus, the evaluation proceeds as follows:

xx == 33 ++ 44--556
6 //5
5 %%1 10
0 operation: **
operation:
xx=3+4-11%10
=3+ 4-ll%10 operation:/
operation: /
xx=3+4-1
= 3 + 4 -1 operation
operation: : %%
x == 77-1
x -1 operation : +
operation.: +
xx=6
=6 operation
operation :: --
26
26 Exploring C
Exploring

Note that 556/


6 / 55 yields 11, since 56 and 5 both are integers,
integers, and
hence must yield an integer on performing any arithmetic arithmetic
operation
operation on them.
on them.

(12) Output
Output

xx=o
=0

Explanation
Explanation
I

Here, the unary - gets the highest priority while evaluation,


« evaluation,
/, %,
followed by *, /, %, +
+ and the binary minus.
minus. Stepwise,
Stepwise, these
operations would be performed as follows:
follows:

xx = --3
3 ++ 44 -- 77 * 88/5
/5%
% 10
10 operation
operation: : unary
minus
minus
xx=-3+4-5615%10
= -3 + 4 - 56 / 5 % 10 operation:
operation : *
x== -3
-3 + 44 -- 1111%
% 10
10 . operation://
operation:
xx =
= -3
-3 ++ 44 - 11 operation : %
operation:
=
xx = 11-- 11 operation:
operation: + +
xx=O
=0 operation
operation : -

(13) Output
Output

xx=5
=5

Explanation
Explanation

%
% has a higher priority than +. But in the above expression
which %% gets the priority? The one which occurs earlier. Thus
4 %
% 5 is performed before 6 % % 5.
S. 4 %% 5 yields 4, whereas 6
%
% 55 yields
yields 1,
1, which
which when
when added
added results
results into
into 5,
5, which
which is
is
assigned
assigned to
to x.
x.
The ABC Of C
C 27

(14) Output
Output

xx=o
=0

Explanation
Explanation

Going by priorities
priori ties of evaluating arithmetic expressions, firstly
first}y
the
the unary
unary minuses
minuses areare bound toto their
their operands.
operands. This would
make
make 33 as
as -3,-3,44 as
as -4,
-4,66 as
as -6
-6 and
and 55 as
as -5.
-5. This
This is
is followed
followed by
*, %
*, % and
and /./. The
The step-by-
step-by- step evaluation
evaluation isis shown
shown below.

-3 ** -4
xx == -3 -4 %
% -6
-6 // -5
-5 operation:
operation: unary
minuses
minuses
xx == 12
1 2 % --6/-5
6/-5 operation:
operation: **
xx == 00/-5
/ -5 operation:
operation: %%
xx=O
= 0 operation:
operation: //

(15)
(15) Output
Output

1-1-11
1 -1 -11

Explanation
Explanation

On
On dividing
dividing two two integers
integers wewe always
always get
get anan integer.
integer. IfIf you
you
imbibe
imbibe this
this fact,
fact, then
then the
the above
above program
program isis aabreeze.
breeze. 44// 33 will
will
resultinto
result into 1,1,and
andnot
not 1.333333.
1.333333. Whenever
Whenever either
either the
the numerator
numerator
or
ordenominator
denominator isisnegative,
negative, the
theanswer
answerwill
willbebenegative. If both
negative.lfboth
are
are negative,
negative, thenthen they
they cancel
cancel out,
out, and
and the
tlie answer
answer would
would be be
positive.
positive.

(16)
(16) Output
Output

11-1-1
11 -1 -1
28
28 Exploring
Exploring C

Explanation
Explanation

% operator
% operator always
always returns
returns the
the remainder
remainder on
on dividing
dividing the
the first
first
integer by
by' the second. If If one of them is negative,
negative, then the result
takes the
takes sign of
the sign the numerator.
of the numerator. Once
Once these
these facts
facts sink
sink in,
in, the
the
above output
above output is fairly straight-forward.
is fairly straight-forward.

(17) Output
Output

Error message:
message: Illegal use of floating point in function main.
main.

Explanation
Explanation

The %
The operator works
% operator works only
only on integers, never
on integers, never on
on Boats.
floats. Here
Here
we are using it with floats
Boats a and b.
h. Hence the error message.
message.

(18) Output
(18) Output

Error message:
message: Invalid indirection
Invalid indirection

Explanation
Explanation

The culprits
The culprits here
here are
are ** and
and". . Unlike
A
Unlike many
many other
other languages
languages
where exponentiation operator ( usually ** or " )) is
exponentiation operator A
is available,
available,
C doesn't
doesn't offer this facility. An omission
omission which
which seems all the
more surprising
surprising when weighed
weighed against the fact that C offers as
many as 45
many as 45 operators!
operators!

(19) Output
(19) Output

g9 == 81
81

Explanation
Explanation
The ABC Of
The ABC Of C
C 29
29

On first analysis,
analysis, we would have expected the output to be 300.
But
But then
then the
the least
least that
that C
C langauge
langauge doesdoes is
is spring
spring surprises
surprises on
on
you when you
you when you least
least expect
expect them., forcing you
them.. forcing you to
to analyse
analyse things
things
aa little
little more
more carefully.
carefully. Here,
Here, on on actually
actually carrying
carrying out
out the
the
multiplication
multiplication ( 300 300 ), the result exceeds the range of
( 3 0 0 * 300 ), the result exceeds the range of
integers
integers (-32768
( -32768 to to +32767),
+32767), hence
hence goes
goes to
to the
the pther
other side and
side and
becomes
becomes an appropriate number,
an appropriate number, which
which isis certainly
certainly not
not 300.
300.
Hence,
Hence, dividing this number
dividing this number by 300 doesn't
by 300 doesn't yield
yield 300.
300.

(20) Output
Output

6.500000
6.500000

Explanation
Explanation

Steps involved
involved in the evaluation
evaluation of the expression are given
below. Note
below. Note the
the following
following points
points carefully:
carefully:

(a)
(a) An operation
An between an
operation between an int and
and an
an int would
would result
result into
into
an int.
an Thus, 33/2
into Thus, / 2 would
would give
give 11 and
and not
not 1.5.
1.5.

(b)
(b) An
An operation
operation between
between aa Ooat
float and
and an
an int would
would result
result
into a Ooat.
float.

Let us
Let us first
first replace
replace the
the variables;
variables in
in the
the expression
expression by
by their
their
values and
values and then proceed with
then proceed evaluation.
with evaluation.

a = 33 // 22 + 33 * 88 // 33 --33 + 1.5
1.5/3
/3
a = 11 + + 33 *·8
* 8 // 33 -- 33 +
+ 1.5
1.5/3
/3 operation: //
operation:
a = 11 + + 24
2 4// 33 -- 33 ++ 1.5
1.5/3
/3 operation:
operation: *
a = 11 ++ 88 -- 33 ++ 1.5 1.5/3
/3 operation:
operation: //
.1 +
a =.1 +8 8 --33 + 0.50.5 operation:
operation : //
9 - 3 +
a = 9 - 3 + 0.5 0.5 operation:
operation: ++
a = 66++ 0.50.5 operation:
operation: --
a=6.5
a 6.5 operation:
operation: +
30
30 Exploring C
Exploring

(21) Output
(21) Output

n
n ==15
15

Explanation
Explanation

As in
As in the
the previous
previous example,
example, let
let us
us first replace the
first replace the variables
variables
with their actual
with their actual values
values and
and then
then evaluate
evaluate the
the expression
expression step
step
by step.
step.

nn = 4 ** 44 // 33 +
+ 3 // 22**4 4.2
.2 + +2++ 4.2
n=
n = 1 6/3 +
16/3 + 3 //22 **44.2
.2 ++2+ + 4.2 operation:
operation: *
nn = =5+ + 3 / 22**44.2.2 + + Z2 +
+ 4.2
4.2 operation:
operation: /
/
nn = =5+ + 1 * 4.2 + +2+ + 4.2
4.2 operation:
operation: /
/
nn = 5 + + 4.2 + +2+ + 4.2
4.2 operation:
operation: *
nn = = 9.2 + 2 + 4.2 operation:
operation: +
nn = 11.2
11.2 + 4.2 operation:
operation: +
+
nn = 15.4
15.4 operation:
operation: +

When 15.4
When 15.4 is
is to be assigned
to be assigned to
to n,
n, it
it is
is demoted
demoted to
to 15
15 before
before
assignment, because n is an int,
assignment, because int, and hence can hold only
integer values.
integer val ues.

(22) Output
(22) Output

st = 21
st=21

Explanation
Explanation

Replacing the values


~eplacing the values of
of variables
variables in
in the
the expression,
expression, we
we get,
get,

st==22**3/4
St 3 / 4-12/12
- 1 2 / 1 2++12/3
1 2 / 3** 16/3
16/3
The ABC Of C
TheABCO[C 31
31

Let us
us now evaluate the the expression, keeping in mind the
priorities
priorities of
of operators and integer
integer and float
Ooat conversion rules.

st = 66/4/ 4 --112/
2 / 112 2 / 3 ** 16/3
2 ++112/3 16/3 operation: * .
operation:
st == 11 --112/
st 2 / 112
2 ++ 112/32 / 3 ** 16/3
16/3 operation : //
operation:
st 2 / 3 ** 16/3
st = 11--11 ++ 112/3 16/3 operation: //
operation:
st 1 - 1 + 4 * 16/3
st = 1 - 1 + 4 * 1 6 / 3 operation: //
operation:
st
st = 11 --11 ++ 646 4// 33 operation : *
operation:
st
st = 11 -- 11 + 2121 operation: : //
operation
st
st = 00 + 21
+ 21 operation:
operation: --
st
st = 21
21 operation:
operation: ++

(23) Output
Output

a8=5b=5
=5b=5

Explanation
Explanation

Whenever a floating point value is assigned to an integer


variable,
variable, the fractional part
part is always truncated, and never
rounded off to the next integer. Thus, 5.999999 as well as
5.000001,
5.000001, both are truncated to 5 when assigned to integer
integer
variables,
variables, a and b, which are then printed out.

(24) Output
Output

2.000000-1.4746701 e+308
2.000000 -1.47467019+308

Explanation
Explanation

41
4/ devaluates
2. evaluates to 2, and when assigned to a, a float variable,
Ooat variable,
is promoted
promoted to 2.000000.
2.000000. Value of a is printed correctly by
printf(
printf().). Where printf()
printf( ) falters is while printing the result of
4/2.
4/2. The reason is, 4 / 2 evaluates
4/2 evaluates to 2, which is an integer and
32
32 Exploring C
Exploring

we are. attempting
attempting to print this integer using %f. Hence the
erratic behaviour.
behaviour. Moral is, do not rely on the format specifica-
specifica-
tions in
tions in printf(
printf( )) to
to carry
carry out the conversions.
out the conversions. DoDo them
them
explicitly through the assignment statements.
explicitly statements.

(25) Output
(25) Output

44512.000001
512.000001
04.000000
04.000000

Explanation
Explanation

In the first printf(


printf(), ), the first output ((i.e.
i.e, 4 ) is alright but the
second one, 512.000001,
second one, 512.000001, is is unexpected.
unexpected. Reason
Reason is,
is, we
we left
left it
it
to printf( )) to
to printf( to first
first convert
convert 44 toto 4.0 and then
4.0 and then print
print itit out
out as
as aa
float using %f.
Ooat using %f. And here lies
And here lies the
the mistake. The printf(
mistake. The printf()) isis not
not
intelligent enough to
intelligent enough to perform
perform thisthis conversion
conversion properly,
properly, andand
hence
hence wewe get
get the
the absurd result. Same
absurd result. Same is the story
is the story of
of the second
the second
printf(). Here, the first output is faulty, whereas the
printf(). Here, the first output is faulty, whereas the second is second is
as
as expected.
expected. Once
Once again
again for
for the
the same
same reasons
reasons -- aa misplaced
misplaced
trust in printf(
trust in printf( )) to
to carry
carry out
out the
the conversion
conversion before
before printing.
printing.

(26) Output
(26) Output

0.500000 0
0.5000000
00.000000
00.000000

Explanation
Explanation

When the
When the first
first division
division in in the
the printf(
printf( )) takes
takes place,
place, since
since ii is
is
an integer
an and aa aa float,
integer ana float, ii is
is first promoted to
first promoted to float.
Ooat. Thus, the
Thus, the
actual division takes
actual division takes place
place between
between 2.000000
2.000000 and 4.000000,
and 4.000000,
which yields 0.500000,
which yields which is
0.500000, which printed out.
is printed out. InIn the
the second
second
division also, the
division also, the result
result is
is 0.500000,
0.500000, butbut since
since it
it is
is being
being printed
printed
out using %d,
out using %d, onon conversion
conversion it it turns
turns out
out to
to be
be O.0.
The ABC 0/
Of C
C 33
33 %

If the
If the first
first printf(
printf( )'s
)'s output
output is
is 0.500000
0.500000 andand O.
0, then
then its
its natural
natural
for us
for us to
to expect the second
expect the second printf(
printf( )'s
)'s output
output to be 000.500000.
tobe 0.500000.
However,
However, the the results
results above
above do
do not
not confirm
confirm this.
this. The
The reason
reason is,
is,
once printf( )) messes
once printf( messes upup one
one conversion
conversion thethe output
output of of the
the
subsequent variables to
subsequent variables to be
be printed
printed in
in that
that printf()
printf() are
are likely
likely to
to
get
get messed
messed up too.
up too.

(27) Output
(27) Output

04
04

Explanation
Explanation

sizeof (( 44 )) would
sizeof would yield
yield 2,
2, whereas
whereas sizeof
sizeof (( 2.0)
2.0 ) would
would yield
yield
8. Therefore,
8. Therefore, thethe printf(
printf( )s
)s are
are reduced
reduced to,
to,

printf ("%d", 2 / 8 ) ;;
( "%d ., 2/8)
printf (("%d",
printf 8 / 2 ) ;;
"%d ., 8/2)

which results
results into 0 and 4, which are then printed out. Notice
that in 2/8,
1.'8, since both are integers,
integers, the result is an integer.
integer.

Also notice that a float memory,


fleat variable occupies 4 bytes in memory,
whereas
whereas a floating point constant by default is stored as an 8
byte number.
number.

(28) Output
(28) Output

nn

nn
nn In/n nn/n
nn /n/n nn/n
Explanation
Explanation
34
34 Exploring C
Exploring

The output highlights


highlights the difference between a \n and a In. In. A
when used
\n, when used in
in printf(
printf(), ensures that
), ensures that the
the subsequent
subsequent output
output
goes to the
goes to the next
next line.
line. As
As against
against this,
this, aa /n
/n is
is treated
treated asas two
two
ordinary characters, and
ordinary characters, and if
if they
they occur
occur inin printf(
printf( ),), they are
they are
outputted as they
outputted as are on
they are the screen.
on the screen. Once
Once this
this difference
difference isis
understood, the above
understood, the above output
output would
would appear
appear quite logical.
quite logical.

(29) Output
(29) Output

p== 1562q=
p 1562 q =1686
1686

Explanation
Explanation

We got
We got the
the above result when
above result when wewe entered
entered 10
10 and
and 20
20 as
as values
values
of p and q.q. Surprising?
Surprising? This
This so happens
happens because
because of the message
message
'Enter val....
'Enter vaL .. q' written inside the scanf(seanf( ), due to which it
behaves erratically. To
behaves erratically. get rid
To get rid of
of the
the problem,
problem, either
either we
we should
should
drop the
drop the message
message from scanf(),
from seanf( since it
), since it is serving no
is serving no mean-
mean-
ingful purpose,
ingful purpose, or or while
while entering
entering the
the values,
values, before
before the values
the values
we must type
we must type the
the message
message through
through the keyboard as
the keyboard as it
it is.
is. For
For
example,
example, if if we
we supply
supply through
through the
the keyboard
keyboard thethe following
following to to
scanf( ),
seanf( ), it
it would
would match
match the message with
the message with the
the message
message in in
scanf(
seanf( )) and
and ignore
ignore it,
it, whereas
whereas itit would
would store
store 10
10 and
and 2020 inin pp
and
andq.q.

Enter values of
Enter values of ppand
andqq1020
10 20

(30) Output
(30) Output

No output

Explanation
Explanation

The seanf()
scanf() just doesn't
doesn't seem to work. Once again the reason
is the spaces
is the spaces immediately
immediately after
after the
the ""
" " and
and the
the spaces
spaces immedi-
immedi-
The ABC O[
The ABC Of C
C 35
35

ately before the


ately before the "".
"". seanl(
scanf( )) works
works in"a
in a peculiar
peculiar way
way if
if you
you
write anything
write anything other
other thanthan format
format specifications
specifications like
like %d
%d %c%e
%f within the
%f within the II" '',
". IfIf it
it finds
finds anything
anything other
other than
than format
format
specfications
specfications (( even
even spaces
spaces ),), then
then it
it expects the same
expects the same charac-
charac-
ters to be
ters to be typed
typed through
through the the keyboard,
keyboard, such
such that
that it
it can
can match
match
them with
them the ones
with the ones inin the
the format
format string,
string, and
and ignore
ignore them.
them. Thus,
Thus,
if we supply the input as follows, the scanf() seanf( ) would work
correctly.
correctly.

<space><space>10 20<space><space>
20<spacexspace>

Since this
Since this seems
seems to to be
be quite
quite unnecessary,
unnecessary, we
we can
can make
make aa
ground rule that
ground rule that in
in the
the format
format string of scanf(),
string of seanf( ), do not write
do not write
anything except the
anything except the format
format specifications.
specifications. However,
However, spaces,
spaces, if
if
they occur
they between two
occur between two format specfications, do
format specfications, do not
not create
create any
any
kind of problem.
problem.

(31) Output
(31) Output

Enter values
Enter values of
of ppand
andqq10102020
p = 10 q = 20
p=10q=20

Explanation
Explanation

If between two format specifications of seanf(),


Ifbetween scanf(), anything other
than spaces,
than spaces, \ns
\os or
or \ts occurs,
occurs, then
then the
the scanf()
seanf() doesn't
doesn't work as
work as
expected. However,
expected. However, any any number
number of
of spaces,
spaces, \ns
\os or
or \ts between
\ts between
two format specifications
two format specifications would
would not
not mess up the
mess up the working
working of of
scanf(),
seanl(), irrespective
irrespective of of whether
whether we
we supply
supply values
values in
in the same
the same
line, on different
line, on different lines,
lines, separate
separate them
them by tabs, or
by tabs, or any
any other such
other such
format.
format.

(32) Output
(32) Output

Enter values
Enter values of
of ppand
andqq11
1112
12
p = 105 q = 1666
p=105q=1666
36
36 Exploring C
Exploring C

Explanation
Explanation

When we supplied
supplied the values as 11 and 12, we got the above
result. The reason
result. The reason for
for this
this absurd
absurd result
result is
is the
the missing
missing & before
before
the variables used
the variables used in
in scanf().
scanf(). && before
before the
the variables
variables is
is aa must.
must.
The reason for
The reason for this
this can
can be
be understood
understood onlyonly after
after we learn
we learn
pointers.
pointers.

(33)
(33) Output
Output

Error message:
message: Expression
Expression syntax in function main

Explanation
Explanation

A comment
A comment cannot
cannot occur
occur within
within another
another comment.
comment. And
And this
this is
is
what has
what has been
been done
done in
in our
our program.
program. Hence
Hence the compilation
the compilation
error. In
error. In other
other words, nested or
words, nested or embedded
embedded comments
comments are not
are not
acceptable
acceptable in C.

(34) Output
(34) Output

Menu isis aa list


Menu list of
of options
optionsyou
youhave
haveatataaparticular
particularpOint
pointinina aprogram.
program.It It
is just
just like
like aarestaurant
restaurantmenu
menu--everything
everything has
hasaamisleading
misleadingname nameand
and
what
what youyou want
wantisisnever
neveravailable.
available.

Explanation
Explanation

printf( ) can be split over multiple lines. However,


printf() However, at the end
of each
of line, it
each line, is necessary
it is necessary to
to give
give aa '\',
'V, which
which tells
tells the
the compiler
compiler
that
that what follows on
what follows on the
the next
next line
line isis the
the continuation
continuation of
of the
the
previous line.
previous line.

Solutions [E]
Solutions to [E]

(1)
(1) Program
Program
·The ABCOf
The ABC OiCC 37
37

m ain()
main()
{ int i, j, k;
{

int i, j, k;
pprintf
rintf (("·\nEnter
\nEntervalues
valuesofoifandi ajn•d) ;j");
.scant
scant ( (" %d%d*&i.,&&j)
·%d %d·, i,&j);;
kk=i+j-i%j;
= i + j-i%j;
pprintf
rintf ((""'nNext
\nNextlargest
largestmultiple
multip=le%d", =% k)d"
; , k);
}
}

Sample run
Sample run

Enter values
Enter valuesofoifand
i an d j7256 7
j 256
Next largest multiple 259
Next largest multiple = = 259
Explanation
Explanation

Suppose
Suppose value of ii and
value of and jj are
are entered
entered asas 256
256 and
and 7,
7, then
then kk
evaluates to 259 which is the
evaluates to 259 which is the next largest multiple of 77 after
next largest multiple of
256.
256.

(2)
(2) Program
Program

m ain())
main(
{ float f, c:
{

float f, c;
pprintf
rintf (("·Enter
Entertemperature
temperaturein farenhen
in farenhdegrees
eit degrees");
•) ;
scant ("%f,&f);
scant ( "%f, &f) ;

cC ==5/9.0
5/9.0*(f-32);
* (f - 32) ;
printf ( "Temp. in centigrade degrees = %f, C ) ;
1 printf ("Temp, in centigrade degrees = % f, c);
\
38
38 Exploring C
Exploring C

Sample run
Sample run

Enter temperature ininfarel)hen


Enter temperature farenheitdegrees
degrees212
212
Temp,
Temp. inin centigrade degrees ==100.000000
centigrade degrees 100.000000

Explanation
Explanation

Once the
Once the temperature
temperature in in farenheit degrees is
farenheit degrees is entered
entered through
through
the keyboard,
the keyboard, all all that
that we have to
we have to do
do is,
is apply
apply the
the standard
standard
formula
formula toto get
get the temperature in
the temperature in centigrade
centigrade degrees.
degrees. TheThe only
only
catch
catch here is, while
here is, while using the formula
using the formula isit
is it necessary
necessary to use 9.0,
to use 9.0,
or
or 99 would
would do? do? IfIf wewe use
use 9,9, then
then irrespective
irrespective of of what
what is the
is the
value
value of f, c would always tum out to be 0, This is because 55
of f, c would always turn out to be 0. This is because
and
and 99 both
both are are integers,
integers, and and hence
hence mustmust always
always return
return anan
integer. Therefore 55 // 99 would
integer. Therefore would yieldyield O.0. To
To avoid
avoid this
this integer
integer
division
division wewe use use 9.0,
9.0, such
such that
that before
before division
division 55 would
would getget
promoted
promoted to 5.0 and
to 5.0 and thenthen 5.0/9.0
5.0 / 9.0 would
would be be evaluated,
evaluated, which
which
would
would return
return aa float
float value.
value. This
This float value is
float value is then
then multiplied
multiplied '
by the result
by the result of of (( ff -- 32
32 ),
), and
and the
the answer
answer is is stored
stored in
in e,
c, which
which
is
is ultimately
ultimately printed
printed out. out.

(3)
(3) Program
Program

main()
main()
{{
int aa ==10,
int 10,bb==2020;
;

printf (("Before
printf "Before interchanging^");
interchanging\n") ;'
prinrf("a = %d
printf ( "a = %db b ==%d",
%d",a,b);
a, b) ;

a s= aa+
e bb;:
b =
b=a-b;a-b;
a e= a-b
a a-b;:

printf ("\nAfter
printf ( "\nAfter interchanging^");
interchanging\n" ) ;
The
The ABC
ABC OfC
O[ C 39
39

printf ("a %d bb == %d",


( "a = %d %d , a,a, b)b) ;;
B

}}

Sample run
Sample run

Before interchanging
aa=10b=20
= 1 0 b = 20
After interchanging
aa=20b=10
= 20b = 10

Explanation
Explanation

To begin with, we initialise variables a and b to values 10 and


20. The printf()
printf() then prints out these values Then come the
valuess'Ihen v

three arithmetic statements. a == a + b stores 30 in a. Thus, the


arithmetic statements,
next statement b == a -• b becomes b == 30 -• 20, yielding 10, 10,
which is assigned to b. Then a = a -• b is executed, which is
equivalent
equivalent to a = = 30 -10.
• 10. Therefore 20 is assigned to a. Having
thus
thus interchanged
interchanged the the contents,
contents, the
the interchanged
interchanged values
values are
are
displayed
displayed using printf().
using printf( ).

(4) Program
Program

main()
main( )
{
{
int days,
int days, weeks,
weeks, leftoverdays
leftoverdays;; .

days == 31
31 ++29
29 ++31 31++30
30 ++3131
weeks
weeks = days
days// 77;;
= days
leftoverdays = days % %77;;

printf ("days
( "days = %d",
%d", days)
days);;
printf ("weeks
( "weeks = = %d",
%d",weeks)
weeks);;
printf ("left = %d",
( "left over days = %d", leftoverdays)
leftoverdays);;
}
40
40 ..
_ ._o_r_in.g~C~
_
-.~ oring- C
__

Sample run
Sample run

days = = 152
152
weeks
weeks = = 21
21
left over = 55
over days =

Explanation
Explanation

Calculation of days
days is straightforward.
straightforward. To calculate weeks, we
divide days
days by 7, whereas to calculate leftoverdays,
leftoverdays, we use
the modulus operator. This is because while calculating left-
overdays,
overdays, we are not interested in the quotient, but in the
remainder.
remainder.
-Steering
Steering the
the Control
Control
E
E
you do
you
veryone
veryone of
changing
would stay
would
it so
do it
of us

stay at
so would
would I.
is called
us is called upon
changing circumstances.
circumstances. If
home; if
at home;
I. Put
Put all
upon to

if II get
all these
to take
If there
take decisions
there is
get aa visa
decisions in
is aa good
good movie
visa II would
these statements
statements in
would fly
in the

fly next
the face
movie on
face of
on TV
next month;
in spotlight
spotlight and
of
TV II
month; if
and you
if
you will
will
notice that
notice that the decisions depend
the decisions depend on on certain
certain conditions
conditions being
being met.
met.

C, too,
C, too, must
must be
be able
able to
to perform
perform different
different sets
sets of
of actions
actions depending
depending
on the
on the circumstances.
circumstances. CC has
has three
three major
major decision
decision making media:
making media:

(a)
(a) if-else statement
if-else statement
(b)
(b) switch statement
switch statement
(c)
(c) Conditional operators
Conditional operators

In this
In this chapter
chapter wewe will examine the
will examine if-else and
the if-else and the conditional
the conditional
operators. Figure
operators. Figure 2.1
2.1 shows
shows the
the if-else
if-else at
at work.
work. From
From thethe figure
figure one
one
can observe
can observe that
that if
if the
the condition
condition after
after ifif is
is satisfied
satisfied one
one set
set of
of
statements gets
statements gets executed,
executed, otherwise
otherwise aa different
different set
set of
of instructions gets
instructions gets
executed.
executed.

But how
But how dodo wewe express
express thethe condition
condition itself
itself in
in C?
C? And
And how
how do we
do we
evaluate its
evaluate its truth or falsity?
truth or falsity? As aa general
general rule,
rule, we
we express
express aa condition
condition
using C's
using C's Relational
Relational operators.
operators. TheThe relational
relational operators
operators allow
allow us to
us to
compare two
compare two values
values to to see
see whether
whether they
they areare equal
equal to
to each
each other,
other,
unequal, or
unequal, or whether
whether one one isis greater
greater than
than the other. The
the other. various rela-
The various rela-
tional operators
tional operators areare shown
shown in in Figure 2.2.
Figure 2.2.
Steering the
Steering the Control
Control 43
43

ifW (condition)
(condnion)
{{
statement 1;
statement 1;
statement 22;;
statement
false true statement3;
statement 3;
}
else
{
statement 44;;
statement
statements statements;
statement 5;
statements }
4 and 5 1, 2 and 3

Figure 2.1 Working


Figure 2.1 Working of
of if-else
if-else

this expression
this expression fi true
is if
true if

xx==y
==y xx is is equal
equal to
to yy
xx !=y
!= y xx is is not
not equal
equal toto yy
x <y
x<y xx is is less
less than
than y)-
x >y
x>y xx isis greaterthan
greater than yy
x <= y
x<=y xx is
is less
less than
than oror equal
equal toto yy
x >= y .
x>=y. xx is
is greater
greater than
than or or equal
equal toto yy

Figure 2.2
Figure 2.2 Relational
Relational operators
operators
44 Exploring C
Exploring

Points
Points to Note
Note

A few tips are in order:


order:

(a) Whenever a condition is evaluated


evaluated in C, it is given a value 1 if
the condition is satisfied, and 0 if it is not satisfied.
satisfied.

(b) Any non-zero number is always treated as truth, whereas a zero


is treated as falsity.

(c) The group ofof statements


statements after the if,
if; upto and not including
ineluding the
else is known as the "if
"if block". Similary, the statements after
the else form
form the "else block".
block".

(d)
(d) If
If there
there is
is only
only one
one statement
statement in
in the
the if
if block
block then
then the
the pair
pair of
of
braces can be dropped.
braces can be dropped.

(e)
(e) If
Ifthere
there is
is only
only one
one statement
statement in
in the
the else
else block
block then
then the
the pair
pair of
of
braces can be dropped.
braces can be dropped.

(f)
(f) IfIf there
there is
is no
no statement
statement to
to be
be executed
executed in
in the
the else
else block
block then
then
the keyword else can also be
the keyword else can also be dropped.

(g)
(g) ItIt is
is perfectly
perfectly valid
valid to
to write
write an
an entire
entire if-else
if-else construct
construct within
within
an if block or an else block. This is called' nesting'.
an if block or an else block. This is called 'nesting'.

(h)
(h) More
More than
than one
one condition
condition can be combined
can-be combined together
together using
using
logical operators && (AND), II
logical operators && ( AND ), || ( OR ),! ( NOT ). For example,
(OR ), !(NOT). For example,

ifittt (per
( per >= 50) &&
>= 50) &&( (per
per <<60
60))
))
printf
printf ("Second
( ·Second division");
division· ) ;

On
On execution,
execution, 'Second
'Second division'
division' would
would be be printed
printed ifif both
both
conditions,
conditions, (( per
per >=
>= 50
50 )) as
as well
well as
as (( per
per << 60
60 )) evaluate
evaluate toto
Steering
Steering the
the Control
Control 45
4S

true.
true. Even if one of
of the conditions evaluates to false, then
then the
the
printf() would not be executed.
executed,

Let us look at another example:

if ((code
( ( code >= && key == 5) ||II (code
>= i1 &&key==5) ( code << 55 &&
&&val
val==
==11))
))
printf ("Whisky
( ·Whisky is Risky");
Risky" ) ;

Here there are four conditions being checked. They have been
split into two groups by the ||II operator. "Whisky is Risky"
Risky".
would be printed if any one group evaluates to true. In
anyone In each
group there are two conditions separated by && && operator. For
each
each group
group to
to evaluate
evaluate to
to true,
true, both
both the
the conditions
conditions in
in the
the group
group
must
must be satisfied.
be satisfied.

(i) The !!operator


operator reverses the value, of the expression it operates
value,of
on. It
It makes a true expression false
false and a false expression true.
Consider the following example.
example.

!(y<10)
!(y<10)

This is read as "not y less than 10".


10'\ In other words, if y is less
than 10, the expression will be false, since ( yy < 10)
10) is true.
We can express the same condition as ((yy >= 10).

The !!operator
operator is often used to reverse the logical value of
of a
single variable,
variable, as in the expression,
expression,

if (I flag)
( !flag)

saying
which is same as saying

if (flag ==0)
( flag == 0)

(j)
G) Your understanding
understanding of complex conditions using &&, || and!
&&.11and!
can be improved
improved if
i f you
y ou follow
follow the following
following figute
figure step
step by step.
step.
It summarizes the usage of &&,
It summarizes &&, IIand
|| and !.
46 Exploring C .
Exploring

Operands
Operands Results
Results

X
x yy !x
Ix ly
Jy && y
xx&&y x||y
xlly

0
0 0
0 1
1 l
1 0
0 00
00 non-zero 1
1 00 00 00
non-zero 00 00 I1 00 11
non-zero non-zero
non-zero 00 00 11 11

Figure 2.3 Logical


Figure 2.3 Logical operators
operators

Hierarchy of
Hierarchy of Logical Operators
Logical Operators

Since we
Since we have
have nownow added
added the
the logical
logical operators
operators to the list
to the list of
of operators:
operators;
that we
that know, it
we know, it is
is probably
probably time
time to
to review
review all
all these
these operators and
operators and
their priorities.
priorities. Figure
Figure 2.4 summarizes
summarizes the operators
operators we have learnt
so far. The higher an operator
operator is in the table, the higher
higher is its priority.
priority.
A full-fledged precedence
A full-fledged precedence table
table is
is given
given in
in Chapter
Chapter 3. 3.

But can
But arithmetic operators
can arithmetic operators and
and logical
logical operators
operators be
be combined
combined in
in aa
statement? Yes,
statement? Yes, as
as shown below:
shown below:

a == ((y!=3)&&(3
y != 3 ) && ( 3 ++44>>x)x ) ;;

( a == 411 ( b =
ifrf(a==4||(b = xx ++yy>>33)) )
printf ( "e n
printf ("C it for
for yourself)
yourself);;

x II y && ( a +
rfif ((x||y&&(a + bb >=
> =Cc**dIe)
d / e ) ))
printf (("Foxed?");
printf "Foxed?" ) ;
Steering
Steering the
the Control
Control 47

Operators
Operators Type

! Logical
Logical NOT
NOT
* //%
% Arithmetic and
Arithmetic and modulus
modulus
++-- Arithmetic
Arithmetic
<
< >><=
< = >>=
= Relational
Relational
-- .-
==
--!-!= Relational
Relational
&&||
&&11 Logical
Logical AND
AND and
and OR
OR
= Assignment
"Assignment
ti

Figure
Figure 2.4
2.4 Hierarchy
Hierarchy of
of operators
operators

The Conditional Operators


Conditional Operators"

The
The conditional
conditional operators
operators? ? and
and ::" are
are sometimes
sometimes called
called ternary
ternary
operators
operators since
since they
they take
take three
three arguments.
arguments. Their
Their general
general form
form is:
is:

expression
expression 11 ?? expression
expression 22:: expression
expression 33

What
What this
this expression
expression says
says is:
is: "if
"if expression
expression 11 is
is true
true (that
( that is,
is, if its
if its
value
value is
is non-zero
non-zero ),), then
then the
the value
value returned
returned will
will be
be expression
expression 2, 2,
otherwise
otherwise the
the value
value returned
returned will bebe expression
expression 3".
3".

Consider
Consider the
the following example.
following example.

yy=(x>5?3:4);
= (x>5?3:4);

This
This statement
statement will store
store 3
3 in
in y if
if x
xisis greater
greater than
than 5,
5, otherwise
otherwise it
it will
store 4 in
store 4 in y.
48 Exploring C
Exploring C

The following points may be noted auout the conditional operators:


operators:

(a)
(a) Its not
Its not necessary that the
necessary that the conditional
conditional operators should be
operators should be used
used
only in arithmetic
only in statements. This
arithmetic statements. This is
is illustrated in the
illustrated in follow-
the follow-
ing examples:
ing examples:

(k ==
(k == 1 ??printf
printf (nAmn"
("Amit") :printf (("All
) :·printf andsundry")
"All and sundry"));
);
printf("%c",(a>= 'a'?? aa:'!'));
printf( "%c· , ( a >= 'a' : 'I') ) ;

(b) conditional operators


The conditional operators can be nested.
nested.

big == ((aa>>bb?? (( aa >> Cc ? 33 :: 44 )) :: (( bb >


big > Cc ? 66 :: 88 )) )) ;;

(c)
(c) The
The limitation
limi tation of
of the conditional
the condi operators is
tional operators is that
that after
after the?
the ? or
or
after the:
the : only one C statement can occur.
Steeringthe
Steering theControl
Control 49
49

Exercise
Exercise
fA] What
[A] Whatwill
willbebethe
theoutput
output ofofthe
thefollowing
following programs:
programs:

(1)
(1) main()
main()
{
{
int x = 10, Y = 5, p, q ;
intx = 10,y = 5, p,q;
p=x>9;
p=x>9;
qq=x>3&&y!=3;
= x>3&&y!=3;
( "p== %d
printf("p
printf q ==%d",
%d q %d",p,p,q q);
);
}

(2)
(2) main()
main()
(
{
intaa== 30,
int 30, bb == 40,
40, xx;;
xx== (a!=10)&&(b
( a != 10 ) && ( b == 50);
50) ;
printf ("x = %d·,
printf ("x = %d",x); x) ;
}

(3)
(3) m~inO
main()
{
{
int a = 100, b = 200, c ;
int a = 100, b = 200, c;
c == (a==100||b>200);
c ( a == 100 II b > 200) ;
printf ("C = %d", c) ;
printf ("c = %d",c);
}

(4)
(4) main()
main()
{
{
int x = 11, Y = 6, Z ;
intx = 11,y = 6,z;
== 511
zZ == xx == 51|Yy!=!=4 4; ;
printf ( HZ = %d", z) ;
printf ("z = %d",z );
}
}
(5)
(5) main()
main()
{
{
50
SO Exploring C
Exploring C

int aa == 300,
int 300, bb=10,
= 10, Cc ==20
20;;
if(!(a>=400))
if ( !( a >= 400 ) )
b = 300;
b=300;
c = 200;
c=200;
printf (("b
printf %dc
·b = %d c ==%d",
%d",b,b C, c) ); ;
}

(6)
(6) main()
main()
{{
int
int aa == 500,
500, bb ==100, c;
100,c;
( ! a >= 400 )
ifif(!a>=400)
b=300;
b = 300;
c=200;
c = 200;
printf ("b
printf ( lib =
= %d
%dc c ==%d·, b, c) ;
%d",b,c);
}

(7)
(7) main()
main()
{{
int
intxx == 10,
10,yY == 100% 90 ;
100%90;
ifif(x!=y);
(x!= y) ;
printf =
("x = %dy
printf ("x =
%d y =%d",
%d",x,x,y);y ) ;
}}

(8)
(8) main()
main()
{{
int
int xx == 10,
10,Yy==-20 ;
-20;
x=!x;
x = !x;
y =!Y;
y=!y;
printf 'x == %d
printf (("x %dyY ==%d\n·,
%d\n",x,y);
x, y) ;
}

(9)
(9) main()
main()
{{ .
= =
int xx = 0,0,yy =11;
int ;
yY =!x;
= !x;
x = !y;
x=!y;
Steering the Control 51
51

printf ("x
printf (·x = %dYy==%d\n",
= %d %d\n",x,x,y);
y) ;
}}

(10) main()
(10) main()
{{
if(!3.14}
if (13.14)
printf
printf (("I
"I have
have robbed and killed...•
robbed and );
killed...");
else
else
printf ("Until
printf ( "Until my
myevil
evilpurse
pursewas
wasfilled" );
filled");
}}

(11)
(11) main()
main()
{{
int xx ==3,3,Yy==4,4,Z z==4 4;
int ;
printf ( 'ans =
printf("ans %d",z>=y&&y>=x?1:0);
= %d", Z >= Y && Y >= x? 1 : 0) ;
}}

(12) main()
(12) main(}
{{
int xx ==3,3,Yy==4,4,Z z==4 4;
int ;
printf ("ans =
printf("ans %d",(z(z>=y>=x?100:200));
= %d", >= y >= x? 100: 2(0) ) ;
}}

(13) main()
(13) main()
{{
float a =
float = 13.65;
12.25, bb=
= 12.25, 13.65;
if(a=b)
if (a = b)
printf ( "a and
printf ("a b are
and b areequal" );
equal");
else
else
printf ("a
printf and b
( "a and are not
b are notequal"
equal");
);
}}

(14)
q4) mainQ
main()
{{
if('Z'<'z')
if ( 'Z' < 'z' )
printf ("Pilots
printf are on
( "Pilots are on strike..."
strike...");
);
52
52 Exploring
Exploring CC

else
else
printf
printf ("for
( "for absolutely
absolutely outlandish
outlandish demands")
demands· ) ;
}}

(15)
(15) main()
main()
{
{
int = 10;
int xx = 10;
ifx >=
if x >= 22
( "%d\n", x
printf ("%d\n",x);
printf r;
}}

(16)
(16) main()
main()
{{
int ii == 10,
int 10,j j==4040;
;
if ( (j - i) % 10)
if((j-i)%10)
printf ("man
printf ( "man sees
sees your
your actions..");
ectlons.," ) ;
else
else
printf ("god
printf ( "god sees
sees your
your motives..");
mofves.." ) ;
}

(17) main()
main()
{{
lnt i =
inti = -4, num == 10
-4, j,j, num 10;;
jj=i%-3;
= i%-3;
. jj == (j(j ??00:: numnum**numnum););
printf ( "j =
printf ("j = %d",j);%d", j) ;
i1J
/

(18) main()
mainO
{
{
float a =
float = 0.7
0.7;;
ifif (a<
(a < 0.7)
0.7)
printf (("Stoned");
printf "Stoned") ;
else
else
p[intf (("Avenged");
printf "Avenged" ) ;
}
Steering
Steering thethe Control 5353
Control

(19) main()
(19) main()
{
{
int i = 400*400 /400;
inti = 400 * 400/400;
if (i == 400)
if (i == 400)
printf ( "Filibusters" ) ;
printf ("Filibusters");
else
else
prinff ( ·Sea gherkins· ) ;
printf ("Sea gherkins");
}

(20) main()
(20) main()
{
{
int k = 12, n = 30 ;
intk = 12,n = 30;
k k==(k>5&&n
( k > 5 && n== 4?100:200);
4? 100: 200) ;
printf ( ok = %d", k) ;
printf ("k = %d*,k);
}

(21) main()
(21) main()
{
{
illt c = 0, d = 5, e = 10, a;
int c = 0, d = 5, e = 10, a;
a = c > 1 ? d > 1 "e > 1 ? 100 : 200 : 300 ;
= c>('a1 ?= d%d·,
aprintf > 11|a)e;> 1 ? 100:200:300;
} printf ("a = %d", a ) ;

(22) main()
(22) main()
{
{
int a = 10, b = 10 ;
inta = 10, b = 10;
printf ( 'sns == %d",
printf ("ans %d aa>> bb ?? aa** aa :: bbIb)
H
,
/ b ) ;;
}
}
(23) main()
(23) main()
{
{
intx=10,y=20;
intx
x=!x;
= 10, y = 20;
x = !x;
y =!x &&!y;
y = !x&&!y;
printf ( "x = %d Y = %d", x, Y ) ;
} printf ("x = %d y = %d", x,y);
54
54 Exploring
Exploring CC

(24) main()
(24) MAIN()
{{
int
IN T xX==10,10,YY==2020;;
if(!(!x)&&x)
IF (! (!X) && X)
Pprintf =
RINTF (("X
"x = %d", x) ;
%D",X);
else
ELS©
Pprintf =
RINTF (("Y
"y = %d", y) ;
%D",Y);
}}

(25)
(25) MAIN()
main()
{{
Ffloat =
LOAT aA =0.5, =
0.5,bB =0.9 ;
0.9;
if ( a && b > 0.9
IF (A && B > 0.9) )
Pprintf "Idleness isISaAvirtue..·)
RINTF (("IDLENESS ;
VIRTUE..");
else
ELSE
Pprintf
RINTF (("..SO
"..so isISstupidity!"
STUPIDITY!");
);
}}

(26)
(26) MAIN()
main()
{{
INTX =
int x = 100;
100;
if ( !Ix
IF (!!X) )
printf
P "x ==%d",
RINTF (("X %D", !x)
!X);;
else
ELSE
printf
P =
RINTF (("X
"x =%d", x) ;
%D",X);
}}

[B]
[B] Improve
Improve the
the following
following programs
programs by
by reorganising
reorganising the
the state-
state-
ments:
ments:

(1)
(1) main()
MAIN()
{{
NT iI= =10;
Iint 10;
it(i>10)
IF(I>10)
i

ELSE
Steering the Control
Steering Control 55
5S

printf (("Hello
printf Cocaine!");
"Hello Cocaine!" );
}}

(2)
(2) main()
main()
{{
int ii ==5,5,j j= =30,30,k =k5=; 5;
int
if (i < 30)
if(i<30)
{{
if(j<20)
if (j < 20 > ;
{
{
ifif (k == 40)
(k == 40)
printf ( nHi Computerist!" ) ;
printf ("Hi Computerist!");
else
else
t

}}
else
»

}}
}}
else
else
i

}}

[[C]
Q Attempt the following:
Attempt following:

(1) A semiconductor
semiconductor manufacturer
manufacturer sells
sells three
three types
types of
microprocessors: 8-bit,
microprocessors: 16-bit and
8-bit, 16-bit and 32-bit.
32-bit. It
It differentiates
differentiates be-
be-
tween
tween three
three types
types of
of customers:
customers: industry,
industry, government,
government, and and
university.
university. It
It has
has the
the following
following discount
discount policy
policy that
that depends
depends onon
the
the type
type of microprocessor, the
of microprocessor, the amount
amount ofof order,
order, and
and the type
the type
of customer:
of customer:

For 32-bit
.For 32-bit microprocessor,
microprocessor, ifif the order is
the order is for
for less
less .han
.han Rs.
Rs.
50,000, allow
50,000, allow 55 %
% discount
discount to
to industrial
industrial customers
customers andand 6.5
6.5 %
%
discount to the
discount to the government
government agencies.
agencies. Ifthe
If the order
order is
is Rs.
Rs. 50,000
50,000
or more,
or more, aa discount
discount of
of 7.5
7.5 % and
and 8.5
8.5 % respectively
respectively is is given
given
to the industrial
industrial customers government agencies. A
customers and the government agencies.
56 Exploring
Exploring C

discount of 10
discount of 10 % is given
% is given to
to both
both industrial
industrial customers
customers and
and
government agencies if the order is more than Rs. 1,00,000.
government agencies 1,00,000.
Universities get a discount of 7.5 % irrespective
irrespective of the amount
of order.
order.

For 16-bh
For 16-~it microprocessors,
microprocessors, nono discount
discount is given for
is given for orders
orders less
less
than Rs
than 10,000. For
Rs 10,000. For orders
orders ofRs
of Rs 10,000
10,000 or
or more,
more, 55 % discount
% discount
is
is given
given to
to the industrial customers
the industrial customers and
and universities,
universities, and
and 66 %
%
discount
discount is given to
is given to the
the government
government agencies.
agencies.

For 8-bit microprocessors,


microprocessors, a flat discount of 10 % is given to
all the three types of customers
customers for any order.
order.

Write a program that reads the type of the customer,


customer, the type
of the
of product, the
the product, the amount
amount of
of the
the order,
order, and
and prints
prints the net
the net
amount payable
payable by the customer.
customer.

(2)
(2) The
The following rules enable
following rules enable an
an insurance
insurance company
company to determine
to determine
the type of
the type of motor-insurance
motor-insurance to to issue,
issue, and the cost
and the cost of
of the
the
premium with
premium any excesses
with any to its
excesses to its clients.
clients.

If the
If the age
age of
of the
the driver
driver is
is 25
25 years
years or
or more,
more, the
the car
car is manufac-
is manufac-
tured in
tured in India and the
India and the accident
accident record
record of
of the
the car
car is
is good,
good, the
the
premium charged
premium charged is
is 66 %
% of the declared
of the declared value
value of
of the
the car and aa
car and
comprehensive
comprehensive policy
policy isis issued.
issued. If
If the
the accident
accident record
record is not
is not
good,
good, the premium is
the premium is raised
raised to
to 77 %,
%, the
the policy
policy holder
holder pays
pays the
the
first 100 rupees
first 100 rupees of
of aa claim
claim and
and aa comprehensive
comprehensive policy
policy isis
issued.
issued.

If the
If the age
age of
of the
the driver
driver is 25 years
is 25 years oror more,
more, the car is
the car is not
not
manufactured
manufactured in in India and the
India and the accident
accident record
record of of the
the car
car is
is
good,
good, the
the policy
policy holder
holder pays first 100
pays first 100 rupees
rupees ofof any
any claim and
claim and
a
a comprehensive
comprehensive policy
policy of
of 66 %
% premium
premium is is issued.
issued. IfIf the
the above
above
conditions
conditions apply
apply except that the
except that the accident
accident record
record isis not good,
not good,
the premium is
the premium is raised
raised to
to 77 % and aa third
% and third party
party policy
policy is is issued.
issued.
Steering the Control
Steering Control 57

If the age of the driver


driver is less than years, the car
than 25 years, car is
is manufac-
manufac- .
tured
tured in India
India and
and the accident record
the"accident record of the car is good, the
premium
premium charged
charged is 6 % of ofthe
the declared
declared value of the car and
and aa
comprehensive
comprehensive policy
policy is
is issued
issued with
with the
the holder paying the
holder paying the first
first
100 rupees of a claim.
100 rupees of a claim.

If
If the age of the driver
driver is less than 25 years, the car is not
manufactured
manufactured in India and the 'he accident record of the car is
good, the premium
premium charged
charged is 8 % ofof the
the declared
declared value
value of
of the
car, the policy holder
holder pays the first 100 rupees of any claim
and a comprehensive
comprehensive policy is issued. If If the accident record is
not
not good
good and
and all
all other
other conditions
conditions apply,
apply, then
then considering
considering the
the
risk, no policy
risk, no policy car
car be
be taken
taken out.
out.

Assume
Assume that if a person has not had
had an
an accident
accident in
inthe
thelast
lastthree
three
years then the condition
condition of the car is considered
considered good. Write a
program
program to
to output
output the following:
the following:

(a) type of motor insurance


insurance policy
(b) the amount
amount of the premium
(c) excess payable
payable on any claim if applicable

(3) A number
number is entered through the keyboard. The number may
contain
contain 1,2,3,4,
1, 2, 3, 4, or 5 digits. Write a program
program to
tofind
findthe
thenumber
number
of digits
digits in the number.
number,
58 Exploring C
Exploring

Answers
Answers

Answers to [A]
Answers to [A]

(1)
(1) Output
Output

pp=1q=1
=1q=1

Explanation
Explanation

Since x is greater
greater than 9, the condition
condition evaluates
evaluates to true. In C,
while checking
while checking aa condition if it
condition if evaluates to
it evaluates to true,
true, the
the result
result of
of
the test is
the test is treated
treated as
as 11 otherwise
otherwise it isis treated
treated as
as O.
0. Hence
Hence pp
contains, value 1.
contains, value 1.

In the
In statement,
the statement,

qq == xx>3&&y !=3;
> 3 && Y != 3;

the first condition


condition evaluates
evaluates to true, hence is replaced by 1. 1.
Similarly, second
Similarly, second condition
condition also
also evaluates
evaluates to
to true
true and is
and is
replaced
replaced by
by 1. Since the
1. Since the conditions
conditions are
are combined using &&
combined using
and since both
and since both are
are true,
true, the
the result
result of
of the entire expression
the entire expression
becomes 1, which is assigned
becomes 1, which is assigned to q. to q.

(2) Output
Output

x= 1

Explanation
Explanation

aa != 10
10 evaluates
evaluates to
to true
true and
and is
is replaced
replaced by
by 1.
1. bb = 50
50 uses
uses an
an
assignment operator ( = ), hence 50 is assigned to b. Therefore
assignment operator Therefore
the condition
the becomes,
condition becomes,
Steering
Steer-ing the
the Control
Control 59
S9

Xx== 1 &&
&&5050

Since
Since 11 and
and 5050 both
both are
are truth
truth values
values (( any
any non-zero
non-zero number
number is is
treated
treated as
as truth
truth in
in C ), the
C), the result
result of
of the
the entire
entire condition
condition is
is truth,
truth,
i.e.
i.e. 1,
1,which
which is is assigned
assigned to to x.
x.

(3)
(3) Output
Output

c=1
C =1

Explanation
Explanation

Here
Here thethe condition
condition aa == == 100
100 evaluates
evaluates to
to true
true and
and isis therefore
therefore
replaced
replaced by by 1.1. The
The two
two conditions
conditions aa ==== 100
100 and
and bb >> 200
200 are
are
combined
combined using using ||II operator,
operator, andand since
since thethe first
first condition
condition
evaluates
evaluates to to true,
true, the
the second
second condition
condition doesn't
doesn't getget tested
tested at
at all.
all.
The
The truth
truth value,
value, 1,1, of
of the
the first
first condition
condition isis therefore
therefore assigned
to
to C.
c.

(4)
(4) Output
Output

z == 11
Z

Explanation
Explanation

The
The first
first condition
condition x == 55 fails
fails since
since value
value ofof x is
is 11,
11, and
and is
is
therefore replaced by a o.
therefore replaced by a 0. However, the second condition is
However, the second condition is
true,
true, and
and isis replaced
replaced by
by 1.
1. Therefore
Therefore the
the statement
statement gets
gets reduced
reduced
to,
to,

Z = 0||1
z=01l1

Since
Since the
the conditions
conditions are are combined using ||II operator
combined using operator and
and since
since
one
one of
of them
them is
is true
true (( second
second one
one ), the whole
). the whole thing
thing is
i$ treated
treated as
as
true
true and
and hence
hence 1 is assigned
assigned to z.
660
0 Exploring
Exploring C

(5)
(5) Output
Output

B = 300C = 200
b=300c=200

Explanation
Explanation

THE CONDITION (( •A>=


The condition > = 400
4 0 0 )) evaluates
EVALUATEStoTOfalse
FALSE SINCE
since a isA neither
IS NEITHER
equal T
EQUAL toO NOR
nor GREATER T
greater HAN 400. THE
than' The CONDITION
condition IS is Ttherefore
HEREFORE
REPLACED
replaced by BY O.But
0. BUTthe
THENOT OPERATOR( (!)negates
N O Toperator ! ) NEGATES theTHE RESUL
result ofT OF
THIS CONDITION.This
this condition. THISmeans
MEANSitITreverses
REVERSEStheTHE RESUof
result LTthe
OF THE CONDITION
condition
(( 00)) T
toO 1.
1. Thus
THUSthe
THEifIFgets
GETSreduced
REDUCEDto,TO,

1if ((11))
B = 300;
b=300;

OBVIOUSLY, =
Obviously, Bb = 3300
0 0 WOULD GETexecuted,
would get EXECUTED,followed
FOLLOWEDby
BYeC =200,
200, =
HENCE THEoutput.
hence the OUTPUT.

(6)
(6) Output
Output

B = 100C = 200
b=100c=200

Explanation
Explanation

ACCORDING
According TtoO precedence
PRECEDENCE of OFoperators
OPERATORSinINC,C,outOUT !and
ofOF! AND >=,> =!, !
ENJOYS
enjoys Aa HIGHER
higher PRIORITY.
priority. THEREFORE
Therefore !1500
5 0 0 IS
is PERFORMED FIRST
performed first
WHICH
which MAKES
makes itIT0,0,which
WHICHisISthen
THENcompared
COMPARED WITH
with 400.
400. SINCE
Since 0 IS
0 is
NEITHER
neither G REATER than
greater THANnorNORequal
EQUALtoTO400,
400,the
THcondition
E CONDITION FAILS
fails andAND
THE
the Ccontrol
ONTROL STRAIGHTAWAY
straightaway JUMPSjumps TtoO THE statement Ce == 200,
the STATEMENT 200,
FOLLOWING
following WHICH
which itITprints
PRINTSthe
THEvalues
VALUES ofOF B AND
b and c. C.

(7)
(7) Output
Output

xx=10y=10
= 10y = 10
Steering Control
Steering the Control 61

Explanation
Explanation

Contrary to
Contrary to usual belief, the
usual belief, the statement
statement y y = a 100
100 % 90 is
% 90 is
perfectly acceptable.
perfectly acceptable. It It means
means while
while declaring
declaring aa variable, not
variable, not
only can
only can itit be
be initialised
initialised to
to aa particular
particular value,
value, but
but also
also to
to an
an
expression which
expression which onon evaluation
evaluation gives
gives aa value.
value. In
In this
this case
case 100
100
%
% 9090 isis evaluated
evaluated andand the
the remainder
remainder obtained,
obtained, i.e.
i.e. 10,
10, is
is
assigned to
assigned to y. y.

Since the
Since the variables
variables xx and and yy both
both have
have the
the same
same value
value the
the
condition (( xx !=
condition != yy )) fails.
fails. Therefore
Therefore thethe control
control jumps
jumps to to the
the
printf(
printf()) and
and prints out values
prints out values of
of xx and
and y.
y. Note
Note that
that there
there is
is aa; ;
after the
after the if.
if. This
This is called aa null
is called null statement.
statement. Due
Due toto the
the ;; the
the
condition becomes:
condition becomes:

if(x!=y)
if (x != y)

printf ( 'xx = %d
B
%dYy==%d",
%d ,x, y) ;
n

(8)
(8). Output
Output

x=0y=0

Explanation
Explanation

!! operator
operator reverses
reverses the
the truth
truth value
value to
to falsity
falsity and
and false
false value
value toto
truth. Here,
truth. Here, since
since xx to
to begin
begin with
with has
has aa truth
truth value
value (10),
(10), it is
it is
negated to
negated to 0
0 by
by !x and then
!x and then stored
stored in
in x.
x. Thus
Thus aa 00 is
is stored
stored inin x.
x.
Same thing
Same thing happens
happens forfor the
the next
next statement.
statement. !y !y yields
yields aa 00 and
and
this 00 is
this stored in
is stored in y.
y. Note
Note that!
that. I when
when applied
applied toto aa non-zero
non-zero
negative or
negative or aa non-zero
non-zero positive
positive value
value results
results into
into aa O.
0.

(9)
(9) Output
Output

x= 0y= 1
62
62 Exploring C
Exploring C

Explanation
Explanation

To begin
To begin with
with xx is
is zero,
zero, therefore
therefore !x !x would
would give
give 1, which is
1, which is
stored in y.
stored in y. This value of
This value of yy is
is then
then negated,
negated, yielding
yielding 00 in
in the
the
process which is
process which is stored
stored in
in x.
x.

(10) Output
(10) Output

Until my
Until evil purse
my evil purse was
was filled
filled

Explanation
Explanation

3.14, being a positive


positive number,
number, is a truth value, value, and on negating
negating
it using
it using the
the !" operator itit results
t operator into aa o.
resjults into 0. Thus
Thus the
the result
result of
of the
the
condition is false,
condition is false, hence
hence the the second
second printf(
printf()) is
is executed.
executed.

(11) Output
(11) Output

ans
ans =
= 11

Explanation
Explanation

Let us
Let us isolate
isolate the condition for
the condition for closer examination,
closer examination.

z >=y
>= y&&y
&& y>=x
>= x

If we replace
If replace the variables
variables with their values,
values, the condition
condition
becomes,
becomes,

4>=4&&4>=3
4 >=4&&4 >=3

Since both
Since both the
the conditions
conditions are
are true
true and
and they
they have
have been combined
been combined
using &&,
&&, the whole
whole thing evaluates
evaluates to true. This is deduced
fmm the fact that
from
Steering the
Steering Control
the Control 63

truth &&truth
truth && truth

yields truth.
truth.

Thus the
Thus printf()) is
the printf( is reduced
reduced to,
to,

printf ("ans = %d",


( Dans = %d",truth?
truth? 11:0);
: 0) ;

Hence ans = 11 gets


Hence ans gets printed.
printed. Note
Note that
that conditional,
conditional, relational
relational or
or
logical operators, or
logical operators, or for
for that
that matter
matter any
any other
other operators can
operators can
occur in
occur printf()) without
in printf( any problem.
without any problem.

(12) Output
(12) Output

ans == 200
ans 200

Explanation
Explanation

Look carefully
Look carefully at the condition:
at the condition:

(z>=y>=x?100:200)
(z >= y >= X ? 100 : 200 )

Here, first
Here, first zz is
is compared
compared to
to y and
and the
the result of this
result of this condition is
condition is
then compared
compared with x. Since z and yare y are equal, the first
condition
condition is satisfied and is hence replaced by 1. 1. Thus the
condition is now reduced to,
condition

(1 >=x?100
( 1 >= X ? 100 :: 200
200))

Since 11 is
Since is neither greater than
neither greater than nor
nor equal
equal to
to the
the value
value of
of x, the
x, the
condition fails
condition and the
fails and the conditional
conditional operators
operators now
now go
go into
into action
action
and yield 200,
and yield which is
200, which is printed
printed by
by printf().
printf().

(13) Output
(13) Output

a and
and bb are
areequal
equal
64 Exploring
Exploring C

Explanation
Explanation

To begin with a and b are not equal. The catch here is the
assignment operator
assignment operator used in the if statement. It
It simply assigns
the value of b to a, and hence the condition becomes,
becomes,

if ((13.65)
13.65)

The condition
The condition evaluates
evaluates to
to true
true since
since 13.65
13.65 being
being aa non-zero
non-zero
positive constant isa
positive constant is a truth
truth value
value and
and hence
hence executes
executes the
the first
first
printf().
printf( ).

(14) Output
(14) Output

Pilots are
. Pilots on strike...
are on strike ...

Explanation
Explanation

Any character
character enclosed
enclosed within a pair of quotes is replaced by
the ascii value
the ascii value of
of the character. For
the character. For example,
example, the
the ascii value of
ascii value of
Z is 90
Z is 90 whereas
whereas that
that of
of zz is
is 122.
122. Thus
Thus the
the condition
condition becomes,
becomes,

ifif(90<122)
( 9 0 < 122)

Since the condition


Since the is satisfied,
condition is satisfied, 'Pilots
'Pilots...strike' gets printed.
...strike' gets printed.

(15) Output
(15) Output

Error message:
message: if statement
statement missing
missing ((in
in function main

Explanation
Explanation

You guessed
guessed it right! What is missing is a pair of parentheses
parentheses
surrounding the condition, which Dennis Ritchie says is a
surrounding
Steering
Steering the
the Control
Control 65
6S

must.
must. The
The cryptic
cryptic error
error message
message says
says that the iiff statement
that the statement used
used
in function m
in function a i n ( )) has
lDain( has aa missing
missing parentheses.
parentheses.

(16) Output
Output

sees your
god sees your motives..
motives ..

Explanation
Explanation

This
This is
is quite straight-forward ((jj --ii)) %
quite straight-forward. % 10,
10, on
on substituting
substituting the
the
values
values ofof jj and
and i, becomes (( 4400 -- 110)
i, becomes 0) %% 10.
10. That is 3300 %
That is % 10,
10,
which
which gives
gives the
the remainder
remainder asas 0. Thus the
O.Thus the condition
condition would
would nownow
become,
become,

1if(O)
(0)

Since
Since 00 is is treated
treated as
as falsity
falsity in
in C,
C, the
the control
control reaches
reaches the
the second
second
p r i n t f ( which prints out the philosophical message.
printf( ) which prints out the philosophical message.

(17) Output
Output

1j =0
=0

Explanation
Explanation

Look
Look at at the statement jj == ii %
the statement % --4.
4 . On substituting
substituting the
the value
value of
of
i,i, it becomes,
becomes,

jj=-4%-3
= -4%^3

Usual
Usual arithmetic
arithmetic would
would have
have prompted
prompted usus to
to cancel
cancel the minus
the minus
signs
signs from
from numerator
numerator and
and denominator
denominator and and then
then perform
perform the
the
division.
division. ButBut not
not C.
C. In
In C,
C, first
first division
division is
is carried
carried out assuming
out assuming
that
that there
there areare no
no signs
signs and
and then the sign
then the sign of
of the
the numerator
numerator is is
assigned to
assigned to the
the remainder
remainder obtained.
obtained. Thus
Thusj j is
is assigned
assigned aa value
value
66 Exploring
Exploring C

- 1 . Then comes the statement involving


-1. involving conditional operators.
operators.
Here jj is checked
checked for truth or falsity. Since jj is -1, it is treated
as truth and hence 0 is assigned to jj,, which is printed out
through printf().
through printf( ).

(18) Output
(18) Output

Stoned
Stoned

Explanation
Explanation

The output is very surprising!


surprising! 0.7 is never less than (}.7,so
0-.7, so the
condition should evaluate to false. But that doesn't
condition happen.
doesn't happen.
Reason is, when 0.7 stored in a, due to precision considera-considera-
tions, it
tions, is stored
it is stored as as something
something less
less than
than 0.7.
0.7. Naturally-when
Naturally, when
value stored
value stored inin aa is compared with
is compared with 0.7,
0.7, the
the condition
condition evaluates
evaluates
'stoned'
to true and 'stoned' gets printed.
printed.

To get rid of this problem there are two solutions:


solutions:

(a)
(a) Declare
Declare aa as
as aa long
long double
double as
as shown below:
shown below:

long double
double aa ;

(b) Typecast 0.7 to a float while comparing as shown below:

if ( aa << (float)
(float) 0.7
0.7))

Typecasting means
Typecasting converting to
means converting to the
the specified
specified datatype.
datatype. For
For
example, in the above condition 0.7 is converted from
example, from long
double
double to
to aa float
float before comparison.
before comparison.

Moral of the story is: exercise utmost care while comparing


floating point values in an jf
if statement.
statement.

(19) Output
(19) Output
Steering
Steering the
the Control
Control 67

Sea gherkins
gherkins

Explanation
Explanation

Can a variable be initialised to an an expression? The answer is


yes. Thus the statement iint n t ii == 4400
0 0 ** 4400
0 0 //400
4 0 0 is quite alright.
But on evaiuating the expression it doesn't turn tum out to be 400.
Reason
Reason is,
is, when 0 0 **4400
when 4400 0 0 iis
s done
done we we don't
don't get
get 160000 because
160000 beca use
160000
160000 falls
falls outside
outside the
the integer
integer range
range (( -32768
-32768 to to +32767
+32767 ). ).
Whenever
Whenever aa number
number exceeds
exceeds 32767,
32767, it it goes
goes toto the
the negative
negative side
side
and
and picks
picks up
up the
the appropriate
appropriate number. number. For For example,
example, 32768
32768
would
would become
become -32768.
-32768. Similarly,
Similarly, 32769 32769 would
would become
become --
32767.
32767. Likewise,
Likewise, 32770
32770 would become -32766
would become -32766 and and so
so on.
on.

0 0 ** 4400
Thus in our program 4400 0 0 would exceed the integer range
and hence some appropriate number would be picked after
going to the other side of the range. When this, this number is
divided by 400 it would not yield 400. Naturally, the condition
would fail, and therefore 'Sea gherkins'
gherkins' would get printed.

Output
(20) Output

Error message:
message: Lvalue required in function main

Explanation
Explanation

First let us understand the meaning of the word lvalue^


lvalue, An
lvalue
Ivalue is any variable whose value can change ( have a new
value assigned to it).
it ). As against this, an rvalue
rvalue is a variable
variable
whose value cannot change. The easiest way to differentiate
differentiate
between the two is to remember that an rvalue goes to the right
of the assignment
assignment operator, and an lvalue to the left.

Back to the current problem:


problem:
668
8 Exploring
Exploring C
C

k = (k
(k>5&&n
> 5 && n == 4?
4?100:200);
100: 200) ;

Go to the precedence table. It


It will tell you that && enjoys a
higher priority compared to the assignment operator =.
=. Hence
the condition becomes something like this,

(k>5&&n)=4
(k>5&&n) =4

Naturally, this cannot be evaluated since the compiler will not


know to which variable 4 should be assigned.
assigned And it certainly
cannot assign it to the expression ((kk >
>55 && n ). In other words,
D). words,
there
there is
is no
no lvalue
Ivalue to
to which
which 44 can
can be
be assigned.
assigned. Hence
Hence thethe error
error
message 'Lvalue
'Lvalue required in function
function main'.
main'.

The problem can be eliminated by parenthesising the condition


as shown below:
below:

kk-=
= (k
(k>5&&(n
> 5 && (n ==4)?
4)?100:200);
100: 200);

Here assignment
assignment gets a preference over &&, hence the prob-
lem of lvalue is avoided.
avoided.

(21) Output
Output

a8=300
= 300

Explanation
Explanation

c > 11 fails since


since value
value of c is 0, and the control reaches
reaches 300
300
which is assigned to a. It
It would become easier to understand
understand
the statement
statement if we parenthesise the expression as shown
below.
below.

a8=(c>1
= (c>1 ?(d>ll1e>l
? ( d > 1 ||e>1?100:200):300);
?100:200):3OO):

Moral is, the conditional operators


ooerators can be nesfp.ci
n e a i p d
Steering the Control
Steeringthe Control 669
9

(22)
(22) Output
Output

ans == 1
ans

Explanation
Explanation

No,
No, this
this doesn't
doesn't give
give an
an error
error message.
message. Conditional
Conditional operators
operators
can
can very
very well
well be
be used
used within
within printf()
printf() statement.
statement. In
In fact,
fact, any
any
other operators can also be used within
other operators can also be used within printf().

Since
Since the
the condition
condition aa >> bb fails,
fails, the
the statement
statement after
after the
the :,:, i.e.
i.e. bb
// bb is
is evaluated
evaluated and
and its
its result
result is
is printed
printed byby printf().
printf( ).

(23)
(23) Output
Output

xx=Oy=o
=0y=0

Explanc: tion
Explanation

!! reverses
reverses the
the value
value of
of its
its operand.
operand. Thus
Thus !x
!x becomes !20 which
becomes !20 which
is
is equal
equal to o. This
to 0. This 00 isis assigned
assigned to
to x.
x. Consider
Consider the
the next
next
statement:
statement:

yy=!x&&!y
= !x && !y

Substituting
Substituting the values
values of x and y, the statement
statement becomes,
becomes,

yy=!O&&!20
= !0&&!20

!0
!O is 1 and !20 o. Thus
!20 is 0. Thus the statement
statement is now,
now,

= 1 && 0
yy=1&&O

which
which evaluates
evaluates to
to falsity
falsity and
and hence
hence 0
0 is
is assigned
assigned to
to y.
70 Exploring C .

(24) Output
Output

x = 10

Explanation
Explanation

Firstly (!x
Firstly ( !x)) is evaluated. Since
is evaluated. Since xx has
has aa truth
truth value
value (( aa non-zero
non-zero
positive value
positive value ),) , !! negates
negates this
this value
value and
and yields
yields aa O.
0. Thus
Thus the
the
condition is
condition is reduced
reduced to, to,

if (!(0) & &xx )


( !(O)&&

!(0) yields
!(O) yields aa 1.
1. Note
Note thatthe
that the value
value of
of xx is
is still
still 10,
10, hence the
hence the
condition becomes,
condition becomes,

ff(1 &&10)
if(1&&10)

Since both
Since both conditions
conditions yield
yield truth
truth and
and they
they have
have been combined
been combined
using &&,
using &&, the
the whole
whole thing
thing is
is treated
treated as
as true,
true, and
and hence
hence the first
the first
printf() is
printf() executed, printing
is executed, printing the
the value
value ofof x
x in the process.
in the process.

(25) Output
Output

..so is stupidity!
stupidity!

Explanation
Explanation

Let us
Let carefully go
us carefully go over
over the
the condition
condition step
step by
by step.
step. Since
Since aa is
is
0.5 which
0.5 which isis aa truth
truth value,
value, the
the first
first condition
condition in
in the
the statement
statement
evaluates to
evaluates to true.
true. Thus
Thus the
the if
if statement
statement now
now becomes,
becomes,

if (truth & &bb > 00.9


( truth && .9)

The contents
The contents of
of variable
variable bb are
are something
something less than 0.9.
less than 0.9. This
This is
is
because any
because any real
real number
number isis treated
treated as
as aa long
long double
double by C, and
by C, and
SteeringthetheControl
Steering Control 7 171

whenthis
when longdouble
thislong doubleis isstored
storedin ina afloat,
float,due
dueto toprecision
precision
considerations the value stored in the float variable is issome-
considerations the value stored in the float variable some-
thingless
thing lessthan
thanthe
theactual
actualreal
realnumber.
number.Therefore
Thereforethe thecondition
condition
now becomes,
now becomes,
if {truth && (0.9 - small value) > 0.9)
if (truth && (0.9 - small value) > 0.9)

Obviously, the
Obviously, thesecond
second condition
condition would
wouldevaluate
evaluate totofalse and
falseand
the if would now look like,
the if would now look like,
if ( truth && falsity )
if (truth &&falsity)

Naturally, the
Naturally, thewhole
whole condition
condition evaluates
evaluates totofalse
falsesince
sincethe
the 2 2
conditions have been linked together using the
conditions have been linked together using the && operator. && operator.
Thus the
Thus theififfails
failsand
andhence
hence the
thesecond
second printf()
printf( )gets
getsexecuted.
executed.

(26) Output
(26) Output

x=O
x=0

Explanation
Explanation

xxtoto begin
begin with
with isis 100,
100, and
and hence
hence aatruth
truth value.
value. !x!xnegates
negates this
this
truth value and makes it false, i.e. O. !O-once
truth value and makes it false, i.e. 0. !0#nce again negates and again negates and
yields aa truth
yields value, 1.1.Thus
truth value, Thus the the condition
condition isis satisfied
satisfied and
and the
the
control reaches the first printf(). Here, we
control reaches the first printf(). Here, we print the value of print the value of
!x. Remember the value of x is still 100, since
!x. Remember the value of x is still 100, since while performing while performing
llx no
!!x no value
value was
was assigned
assigned to to x;
x; the
the value
value ofof xxwas
was simply
simply used
used
to evaluate !!x and hence !x gives 0 and printf(}prlnts
to evaluate !!x and hence !x gives 0 and printf() prints it out. it out.

Remember that
Remember that !x
!x will
will negate
negate the
the value
value of
of xx temporarily
temporarily for
for
checking the condition. Value of x will change only if
checking the condition. Value of x will change only if we use we use
a statement like,
a statement like,
x=!x;
x = !x;
772
2 Exploring
Exploring C .

Solutions to [B]
Solutions to [8]

(1)
(1) main()
main()
{{
int i == 10;
int 10;
if(i~=10)
if(i*=10)
printf (("Hello
"Hello Cocaine!")
Cocaine!");;
}}

Explanation
Explanation

If the
the condition
condition is
is satisfied,
satisfied, only
only the
the null
null statement
statement (( ;;)) isto
is to be
be
executed. Therefore
executed. Therefore itit is
is better
better to
to reverse the condition,
reverse the condition, so so that
that
the else
the else block
block gets
gets completely
completely eliminated.
eliminated. •

(2)
(2) main()
main()
{{
int ii = 5,
int =
5, jj == 30,
30, kk == 55 ;;
ifif (( ii<< 30
30 && jj << 20
&& 20 &&&& kk ==
== 40
40))
printf ( "Hi Computerist!"
printf ("Hi Computerist!"); );
}}

Explanation
Explanation

Since after
Since checking the
after checking the three
three nested
nested conditions
conditions only
only one
one
printf( ) is
printf( is to
to be
be executed,
executed, itit makes
makes sense to combine
sense to combine the
the
conditions using
conditions using the
the logical operator &&. As
logical operator As there
there are
are no
no
statements to
statements to be
be executed
executed inin the
the else
else block,
block, the
the else
else block can
block can
as well
as well be dropped.
be dropped.

Solutions to
Solutions IC]
to Ic]

(1)
(1) Program
Program

main()
main()
Steering
Steeri,,& the
the Control
Control 773
3

{
char
char customer;
custOl1ler ;
float
flam order,
Ofder, discount
ciSCOUI1 ==0,0, amt;
amt ;
int
int mptype;
mptype;

printf
printf ("\nEhter
( "\nE'nter microprocessor
microprocessor type,
type, customer
customer type
type \
and order amourt\n");
and order amOUr1\nio) ;
I

scanf
scant ("%d
( .~ %c%c %f,
%', Amptype,
&mplype, &customer,
&customer, Aorder)
&order) ;;

ifif (mptype
( mptype ==== 3322 ))
{{
( customer ==
ifif (customer == '•.,.)
'if)
d~unt=7.5;
discount = 7.3;

ifif (customer =='f)


( customer == 'i')
o{ ,
{
( order << 50000)
ifif (order 50000 )
=
discount = 55 ;;
discount
else
else
discount == 7.5;
discount 7.5 ;

if (order
( order>> "100000
100000))
discount
discount == 1100 ;;
}}

if (customer
( customer =='g')==
'g')
{{
ifif (order
( order << 50()00
50000))
discount =
discount = 6.5
6.5;;
else
else
discount == 8.5
discount 8.5;;

if (order
( order>> 100000)
100000)
discount
discount == 10
10;
}}
}}
74
74 Exploring C
Exploring

if (mptype
if.( = = 16)
mptype == 16)
{{
ifif ((order
order>> 10000)
10000)
{
{
il
if ( customer == 'u' customer == 'i' )
if (customer == 'u' || customer == T )
, discount = 5 ;
» discount = 5 ;
else
else
discount = 6 ;
discount = 6 ;
}
}
}}

if ((mptype == 88 )
mptype ==
discount =
discount = 10
10;

=order** (100
amt = order ( 100 - discount) /100;
discount) /100

printf.("\nCustomer
printf.( "\nCustomer = %c Order = %f, customer, order)
%1",customer, order);;
printf (("\nMp
"\nMp == %d bit Amount
Amount == %f, mptype, amt)
%1",mptype, amt);
}}

Sample run
Sample run

Enter microprocessor
microprocessor type,
type, customer
customer type
type and order amount
amount
65000
32 i 65000
Customer = i Order = 65000.000000
Customer 65000.000000
Mp = 32 bn
bit Amount
Amount = 60125.000000
60125.000000

Explanation
Explanation

The first
The first few
few lines
lines are
are straight-forward.
straight-forward. Once
Once the
the customer
customer
type,
type, microprocessor
microprocessor typetype andand the
the order
order amount
amount have
have been
been
scanned from the
scanned from the keyboard,
keyboard, the the control
control reaches
reaches the
the cluster
cluster of
of
if statements. Firstly
if statements. Firstly the
the microprocessor
microprocessor type
type is
is checked,
checked, fol-
fol-
lowed
lowed by the type
by the type of
of customer.
customer. AndAnd then
then depending
depending on the j
on the
order amount, discount
order amount, discount is is assigned
assigned an
an appropriate
appropriate value.
value.
Steeringthe
Steering theControl
Control 7 575

Towards the
Towards theend
endthe
theactual
actualamount
amounttotobebepaid
paidisiscalculated
calculated and
and
displayed on the screen.
displayed on the screen.

(2)
(2) Program
Program

main( )
mainQ
{
{
int age, ace, excess 0 ;
int age, acc, excess = 0 ;
=
float cost, prper, amt ;
float cost, prper, amt;
char type, inout ;
char type, inout;

printf("\nEnter
printf ( "nEnter age
ageofofdriver");
driver • ) ;
scanf ( "%d~, &age
scanf ("%d", & a g e ) ; ' ) ; •
printf("AnEnter
printf ( "~nEnterno.no.ofofaccidents
accidentsininlast years • ) ;
last33years");
scanf ( "%d",
scanf ("%d",&acc); &ace) ;
printf("\nEnter
printf costofofccar
( "nEnter cost a r "•)); ;
·scant 1"%f,
scarrft"%f,&cost); &cost) ;
printf("\nCar
printf ("\nCar mfd.
mfd.ininororoutside
outsideIndiaIndia(i/o)");
(i/o) • ) ;
scanf ( "%c", &inout)
scanf ("%c", &inout); ;

ifif(age
( age>=
>= 225
5 ))
{
{
if ( jnout
if (inout == T )
== 'j')
{
{ if (ace == 0)
if (acc = = 0 )6;
prper::
else prper = 6 ;
else
{
{ prper = 7;
excess= 7= ;100 ;
prper
} excess = 1 0 0 ;
}type = 'C';
} type = C ' ; ,

}else
else
{
{ if (ace == 0)
if (acc == 0 )
--- _ --------------
..
76 Exploring
Exploring C

{
prper:=6;
prper 6;
type
type:= 'C'
C
,

excess 1 0 0;;
excess = 100
}}
else
else
{
{
prper: 7;
prper = 7;
type=T;
type = T ;
}
}
}
}
}
}
else
else
{
{ if ( inoIJ == ,')
if(inout==T)
{
{ if( ace == 0)
rf{ ( a c c = = 0 )
prper = 6;
{
type = 'C';
prper = 6 ;
excess = 100 ;
type = 'C;
}
excess = 1 0 0 ;
}
}
else
}
{
else
if (ace == 0)
{ -
type - 'C" ,-
(acc==0)
ifelse
type
type:= 'R';
'C;
else
type = 'R';
-prper=8;
excess= =8 ;100 ;
prper
} excess = 1 0 0 ;
}
}
}
amt cost **prper/100;
amt == cost prper /100 ;
Steering the Control 77

printf ("\nC
( ·\nC -- Comprehensive
Comprehensive TT -- Third party");
party. ) ;
printf ("\nR
( ·\nR -- Risk, no policy");
policy· ) ;
printf ("\n\nType =
(·\n\nType of policy = %c",
%c·, type);
type) ;
printf ("\nAmount
( "\nAmount of premium = %f,= %r, aamt)
m t ) ;;

if (excess
( excess !=!= 0 ))
printf ("\nExcess
( ·\nExcess amount on claim == %d",
%d·, excess);
excess) ;
}
}
Sample run
Sample run
Enter age of the driver 30
Enter
Enter age
no. ofof accidents
the driver in30last three years 0
Enter no.
costofofaccidents
car 100000in last three years 0
Enter costinoforcar
Car mfd. 100000
outside India (i/o) i
Car mfd. in or outside
C - Comprehensive T -India
Third(i/o) i
party
C Comprehensive T - Third party
R - Risk, no policy
R - Risk,
Type of policy =
no policy C
Type
Amountof policy =
= C 6000.000000
of policy
Amount of policy = 6000.000000
Explanation
Explanation

The program opens with a group of scanf(


scanl( )s which receive the
inputs to the program.
program. The conditions are plenty and you can
understand
understand them if you follow the guideline - first check {or for
age,
age, then
then where
where the
the car
car is
is manufactured
manufactured and
and then
then the accident
the accident
record.
record. Once
Once the
the premium
premium percentage,
percentage, type
type of
of policy
policy and the
and the
excess
excess amount,
amount, ifif any,
any, have
have been
been determined,
determined, the
the amount of
amount of
premium
premium isis calculated
calculated and
and then
then these
these details
details are printed.
are printed.

(3) Program
Program

-main(
main())
{{
int n, count =
count = 1 ;
78
78 .Exploring
Exploring CC

printf ("\nEnter
printf ( "\nEnter aa number");
number I ) ;

scant C%d",&n);
scanf ( "%d", &n ) ;

nn=n/10;
= n/10;
i iff ((nn! !=
= 00))
count
count ==count
count ++·1
1 ;;
n=n/10;
n = n/10;
iiff ((n!=
n ! = 00))
count ==count
count count ++ 11;;
n=n/10;
n = n/10;
ifif ((n
n t= f= 00))
count=
count = count
count ++ 11;;
n=n/10;
n = n/10;
ifif(n!=O}
( n != 0 )-
count == count
count count ++ 11 ;;

printf { "'nNO. of
printf {"\nNo. of digits
digns == %%d
d " ",
, count);
count ) ;
}}

Sample run
Sample

.Enter
Enter aa number
number 1235
1235
No. of
No. digits == 4
of digits

Explanation
Explanation

The program begins with With a scanf()


scanf( ) which receives a number .
entered through the keyboard into the variable n. The number
The 'number
is 'then
then successively
successively divided by 10 four times, and each time if
the quotient obtained is non-zero
non-zero then count
couat is incremented
incremented to
count the digit. At the end of all divisions count
count contains the
number
number of digits in the number,
pf'dig,ts number, which is then printed out.
Merry go Round
A
loop involves
involves repeating
repeating some portion of the program either

A
achieved
a specified
specified number
number of times,
times, or until a particular condition
is being satisfied. This repetitive
achieved in C through a for
condition
repetitive operation ( looping ) is
for or a while or a do-w~le.
do-while.

Examine explains
Examine Figure 3.1 carefully before reading any further. It explains
working while, for
the working of while, for and do-while
do-while by taking a simple example
example
of printing
of numbers from
printing numbers from 11 to
to 10.
10.

Having understood
understood the basic working
working of the loops, let's
let's understand.
understand .
their finer points.
their finer points.

Any while,
Any while, for and do-while
for and do-while loops
loops would
would more
more or
or less
less take
take the
the form
form
shown
shown in in Figure
Figure 3.1.
3.1. The initialisation, testing
The initialisation, testing and
and incrementation
incrementation
hold the key
hold the key to
to the
the working
working ofof the
the loop.
loop. Before
Before wewe complete
complete outout
discussion
discussion ofof loops
loops it
it would
would be
be worthwhile
worthwhile to to imbibe
imbibe the
the following
following
details:
details:

The statements
statements within the loop would keep getting executed executed
till the condition
tiJIthe condition being
being tested
tested remains
remains true.
true. When
When the condition
the condition
becomes false, the
becomes false, the control
control passes
passes to
to the
the first
first statement
statement that
that
follows
follows thethe body
body of the loop.
of the loop.

The condition
The condition being tested may
being tested may use relational or
use relational or logical
logical
operators.
operators.
Merry go
Merry Round
go Round 81
81
(

start ) start
>

1 = 1
1 i= !--> is I no
i=j+n ' < i i i —

yes (stop)
no
<i < 11 > /
yes | C

i =i+ l|

main()
main() main()
main() main()
main()
( {
{ {
{
i;
int i; int i;
inti; int
inti; i;
=
i1 =11; ; for
for (i=1 ; k11 ;;i=i+1)
(i=1 ;i<11 i=i+1) ii e= 1t;;
while(i<11)
while ( i < 11) printf ("%d\n", ii)) ;
printf (^dVi", do
do
{ } {
{
printf C%d\n",i);
printf{"%d\n",~; printf ( "%d\n", i) ;
printf ("%d\n",i);
i = i + 11 ;;
i=i =
i i+ 1 ; .
i=i+1;
} }while(i<11);
} } while (i < 1 1 ) ;
}
Notes
N o t e s Notes
N o t e s Notes
N o t e s

- Init.alization,
- I n i t i a l i z a t i o n , testing
t e s t i n g -- Initialization,
I n i t i a l i z a t i o n , testing
t e s t i n g - Initialization,
- I n i t i a l i z a t i o n , test-
t e s t -

& incrementation
& i n c r e m e n t a t i o n of o f & incremenlation
& i n c r e m e n t a t i o n of o f i n g &.
ing & incrementa-
i n c r e m e n t a -

-
lloop
o o p ccounter

sseparate

before
b
o u n t e r done

e p a r a t e steps,

- Condition
e f o r e executing

o d y of
body
b o f the
d o n e in

s t e p s .

C o n d i t i o n tested
t e s t e d

e x e c u t i n g

t h e loop.
l o o p .
i n loop
l o o p counter

ssame

-- Condition
c o u n t e r done

a m e statement.

C o n d i t i o n tested

executing
ooff tthe
h e loop.
d o n e in

s t a t e m e n t .

t e s t e d before

e x e c u t i n g bodyb o d y

l o o p .
i n

b e f o r e
tion
t i o n o

ccounter

- Condition
-
off loop
o u n t e r d
l o o p

done
o n e in

s e p a r a t e s t e p s .
separate steps.
C o n d i t i o n tested

after executing
a f t e r
t e s t e d

e x e c u t i n g
i n

j
body
b off the
o d y o t h e loop.
l o o p .

'------
while, for and do-while
Figure 3.1 Working of whiJe, do-while loops
82
82 Exploring C
Exploring

For example,
example,

(a) w h i l e (i
while ( i <<=
= 10)
10)
(b) for ( ii = 0 ;; i <= 10 && jj <= 15
1S;; i = ii ++ 11))
(c)
(c) while(j>10&&(b<15||c<20))
while(j>10&&(b<15I1c<20))

The statements
statements within the loop may be a single line or a block
block
of statements.
statements. In the first case the braces are optional.
optional. For
example,
example,

while ( ii<=
< = 10
10))
=i+1
i =i+ 1 ;;

is the same as

while ( ii<<= = 1010))


{{
i == ii ++ 11;;
}}

As a rule a loop must test a condition that eventually becomes


becomes
false, otherwise
otherwise the loop would be executed forever, i.e.i.e, in-
definitely.
definitely.

Instead of incrementing
incrementing a loop counter,
coroner, we can decrement it
and still manage
manage to get the body of the loop executed repeated-
repeated-
ly.-
l v

It is not necessary
necessary that a loop counter must only be an into
int. It
could even be a Ooat.
float Even floating point loop counters can be
decremented. Once again the increment and decrement could
decremented.
be by any value,
value, not necessarily 1.
1.

In the for statement


statement the initialisation,
initialisation, testing and incrementa-
incrementa-
tion may be dropped, but still the semicolons are necessary.
necessary.
For example,
example,
Merry go
Merry go Round 83
83

main()
main( )
{{
int =
int ii = 11 ;;
for(;;)
for(;;)
{
{
printf ( '%d', i ) ;
printf ("%d", i ) ;
ii == i+ 1;
i+ 1 ;
if(i>10)
if ( i > 10)
r
break ; takes control out of the loop */
break; /* takes control out of the loop */
}}
}}

In the
In the for loop,
loop, more
more than
than one
one variable
variable can
can be
be initialised and
initialised and
incremented. While
incremented. While doing
doing so
so the
the multiple
multiple initialisations
initialisations (( or
or
the multiple
the multiple incrementations
incrementations )) must
must be
be separated
separated by the comma
by the comma
( , )) operator.
(, operator. For example,
For example,

main()
main()
{{
int
int i,i, jj ;;
for (i = 1,
for(i 1 0 ; ii + j < 225;
1,jj = 10; 5 ; ii = i + 1,
1 , j ==jj + 11))
printf ("%d %d U
i,
printf ("%d % d \ i , j ) ;
, j) ;
}}

The way
The way if statements
statements can
can be
be nested,
nested, similarly
similarly while,
while, for~
for and
and
do- while
do- while statements
statements can
can also
also be nested.
be nested.

More Operators
Operators

Operators areC's
Operators are C's forte. C is
forte. C exceptionally rich
is exceptionally rich in
in operators.
operators. These
These
operators fall
operators into distinct
fall into categories, as
distinct categories, as Figure
Figure 3.3
33 would
would confirm.
confirm.
To understand
To understand them
them thoroughly
thoroughly consider
consider aa problem
problem wherein
wherein we
we want
want
to display
to display numbers
numbers fromfrom 11 to
to 10
10 on
on the
the screen.
screen. Figure
Figure 3.2
3.2 shows
shows the
the
various ways of writing this program, introducing new
various ways of writing this program, introducing new operators operators
^ ^ every
^ time.
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
84
84 Exploring
Exploring CC

main()
main() main()
main( )
{{ {
int ii== 11;;
int ^ inti = 1;;
inti=1
while (i<=
while ( i<= 10)
10 ) while
while (i<=
(i <= 10)
10)
{
{ Drintf
orintf ("%d",
{
("%d", i)i);; {
printf
printf ("%d",
( "%d", i)i);;
if+; i+=1;
1+= 1 ;
} }
} }

++
++ is
is an
an increment
increment operator.
operator. ItIt +=
+= isis aa compound
compound assignment
assignment
increments
increments thethe value
value of
ofii by
by 1.
1. operator.
operator, ItIt increments
iocrements the
the
value
value of of iiby
by 1.
1.
--- is
is another
another such
such operator
operator
which
which decrements
decrements the
the value
value of
of Similarly,
Similarly,jj ==Jj ++ 10 can also
10 can also be
be
aa variable
variable by 1.
1. written
written as
as jj += 10.
10.

**,
•• , //,
/I, %%
%% operators
operators do
do not
not Other
Other compound
compound assignment
assignment
exist.
exist. operators
operators are
are -=,
-=, *=, /= and
*=,1= and %=.
%=.
+++,
+++, —-- operators
operators do
do not
not exist.
exist.

main()
main() main()
main()
{{ {
int ii=O;
int = 0; * inti
int i== 0;
0;
while (++i <=
while (++i <= 10)
10) while (i++<
( iff < 10)
10)
printf ( "%d", i) ;
printf ("%d", i); printf C%d",
( "%d", i);
I) ;
}} }

In
In the
the statement,
statement, white
while (( ++ ii In
In the
the statement
statement while
while (i++
( i++ <<
<=
<= 1010)) first incrementation
first incrementation 10 ), first
10 ), first the comparison of
the comparison of
of
of iitakes
takes place,
place, then
then the
the com-
com- value
value ofof iiwith
with 10 is performed,
10 is performed,
parison
parison ofof value
value of
of iiwith
with 10
10 and
and then
then thethe incrementation
incrementation of of
is performed.
is performed. value
value ofof iitakes
takes place.
place.

Figure
Figure 3.2
3.2 Incrementation,
InerementatioD, decrementation
deerementation & compound
eompound
assignment operators
operators
Merry go
Merry go Round 85
85

I
Precedence
Precedence of Operators
Operators
Following
Following figure
figure shows
shows the
the precedence
precedence of of all
all the
the operators covered
operators covered
so far. Unary
so far. Unary operators
operators have
have the
the highest
highest precedence,
precedence, whereas
whereas the
the
comma operator has the lowest precedence.
comma operator has the lowest precedence.

Description
Description Operator
Operator Associativity
ABN:iativity

Increment/decrement
Increment/decrement ++
++ -- Right
Right to left
to left
Negation
Negation i! Right
Right to left
left
Unary
Unary minus
minus - Right
Right to left
left
Size
Size in
in byteK
bvtes, sizeof
sizeof Right
Rint to left
to left
Multiplication
Multiplication ** Left
Left to right .
to right
Division
Division / Left
Left to
to right
right
Mod
Mod % % Left
Left to right
to rizht
Addition
Addition ++ Left
Left to
to right
right
Subtraction
Subtraction - Left
Left to
to right
right
Less
Less than
than < < Left
Left to
to right
right
Less than
than oror equal
equal to
to <=
<= Left
Left to
to right
right
Greater
Greater than
than > > Left
Left to
to right
right
Greater
Greater thanthan or
or equal
equal to
to >=
>= Left
Left to
to right
riPt
Equal
Equal to to --
== Left to right
Left to right
Not equal
equal to ,-
i.-
= Left
Left to
to right
right
Logical
LoticalANDAND &&&& Left
Left to
to right
rizht
Logical
Logical OR OR IIII Left
Left to
to right
rizht
Conditional
Conditional ?? :: Right to left
Right to left
Assignment
Assignment == %=+=
0/0= += .= *- /...:.Right
-= *=/= to left
Ri.e;htto left
Comma
Comma Left
Left to
to right
right

Figure
Figure 3.3
3.3 Precedence
Precedence of
of operators
operators
86 Exploring C

break and continue


Use of break continue
We often come across situations where
across situations where we want to jump
jump out of a loop
loop
instantly, without waiting
instantly, without waiting to get. back to the conditional
conditional test. The
keyword break
keyword break allows
allows usus to
to do
do this.
this. When
When break
break is encountered
is encountered
inside aa loop,
inside loop, control automatically passes
control automatically passes to
to the first statement
the first statement after
after
the loop.
the loop.

In some
In some programming
programming situations
situations we
we want
want to
to take
take the
the control
control to
to the
the
beginning of the
beginning of the loop,
loop, bypassing
bypassing the
the statements
statements inside
inside the
the loop
loop which
which
have not yet
have not yet been
been executed.
executed. The
The keyword
keyword continue allows
allows us
us to
to do
do
this. When
this. When continue is encountered inside any C loop,
is encountered inside any C loop, control control
automatically
automatically passes
passes to the beginning
to the beginning ofof the loop.
the loop.

A break
break and continue is usually associated
associated with an if.
if. The following
following
figure
figure shows
shows break
break and
and continue at work.
at work.

main()
main() main()
main_()
{{ {
inti;
int i ;
MIL I , . int i;
for (i
for
{
(i == 11 ;;ii <= < = 1100 ;; iiH

iiff (i( i ==== 55))


break; -----,
break;
+ + ))
.{
for (i
for ( i = 1 ;;ii <=

iiff (( i==
i = = 5 ))
continue
J
< = 1100 ; iiH

.
++)
takes
™ con-
takes
trol
c o n t i n u e ; — ' here
tfctrol
con-
here
else takes else
else I

printf ( "%d\n", i); control printf (("%d\n",


"%d\n", i)in-;
} here }
printf (("Hello");
"Hello" ) ; ---' }}
}}

Figure 3.4a Working


Figure 3.4a Working of
of break
break and
and continue

The working
working of the programs
programs given in Figure 3.4a is straightforward.
straightforward.
But if
But if you
you still
still have
have any doubts, the
any doubts, the following
following figure
figure would
would take
take care
care
them.
of them. .
Merry
Merry go
go Round
Round 87

v
next statement
statement following next statement following
the for loop the for loop

Figure 3.4b Working of break continue


break and continue
88 Exploring C

Exercise

[A] What will be the output of the following programs:


programs:

f(1)
l) mainQ
mainO
{{
charj=1;
char j =1;
while (j <= 255 )
while ( j < = 255)
{
{
printf ( "%<fIn", j) ;
printf ("%d\n",j);
j =j+ 1;
j=j + 1;
} Y
}
(2)
(2) main()
main()
{
{
intj=1;
intj =1;
while ((jj <=
while <= 255)
2 5 5 ) ;;
{{
printf (( ""%c
printf %c%%<fIn.,
d \ n " ,j,j ,j j)) ;;
j++ ;
}}
}}

(3) main()
main()
{{
=
int j = 11 ;;
intj
while ((jj <<=
while = 2255)
55)
printf ( "%<fIn",+++j)
printf ("%d\n", + j ) ;;
}}

(4)
(4) main()
main()
{{
int.a;
int.a;
for
for (( aa == 11 ;; aa <=
<= 32767;
32i67 ;a++)
a++ )
Merry go
Merry go Round 89
89

printf ("%d
( ' % d "",, a)
a);
}
}

(5) main()
main()
{{
irt i;
inti;
for ( ii = 1 ; i++
i++ <=
<= 5 ;; printf(
printf ("%d",
"%d ., ii )) ) ;
}}

(6) main()
mainO
{{
irti=1,j=1
inti = 1, j = 1 ;;
for
for ( ;; jj ;; printf
( printf (("%d%d\n
"%d %d\n",i,i ,j)j ) ))
,
I

jj == i++
i++ <=5;
<=5;
}}

((7)
7) main()
main()
{{
int ii == 1 ;
irt
for {(;; i++
i + +;); )
printf ((·%d
printf " % "d ii)) ;;
}}

((8)
8) main()
main()
{{
int a = 5 ;
irta=5;
do
{{
printf ("%d\n",
( '%~n', a)
a);
a =-1
a=-1; ;
}while(a>O)
} w h i l e ( a > 0 ) ;;
}

(9) main()
main()
{{
int =
inl aa = 3, =
3, bb = 44 ;;
90
90 Exploring
Exploring C
C

bb%=3t4
% = 3 + 4 ;;
aa*=
* = aat+ 5;
5;
printf(
printf( "b == %d aa == %d", b,
b ,a)
a ) ;;
}

(10) main()
{
{
int x = 3;=3;
x*=Xt
x * = x + 4; 4;
printf (( 'x
printf =
%d", x)
x = %d",
B
x ) ;;
}

(11) main()
{{
int xx =:: 3,
int y, Zz ;;
3, y,
zz=y=x;
=y=x;
z *= y = x **x;x |
printf ("x =
( "x = %'d =
%d yY = %d z = %d", x,
X. y, z)
z) ;
}

(12) main()
main()
{{
=
int xx = 3, y, zz ;;
3, y,
zz=y=x;
=y=x;
zz *= y /=I:: xx',;
printf (
printf ("x"x == %d =
%d yY = %d =
%d zz = %d", x, y,
%d", x, y, z)
z) ;
}

(13) main()
main()
{{
= =
int x = 1,1, yY = 55 ;;
t:
y * ==x;x '
printf ("x
printf =
( "x = % %dd yY == %d",
%d", x,
x ,Yy )) ;;
}
Merry
Merry go
go Round
Round 91
91

((14)
1 4 ) mainf)
mairaO
{{
int xx == 3,3, y,y, z;
int Z ;

zz=y=x;
=y=x;
z ==Yy ++== xX ==-- zz;;
z
printf ("x
printf ( "x == %%d =
d yY = %
%d =
d zz = %d",
%d·, x,X. IY,
y , zz )) ;;
}

((15)
15) main()
{{
=
int xx = 55;;
int
Xtt ;
x++;
printf ("x
printf ( "X = = %%d\n",
d \ n " ,x)
x ) ;;
ttX;
++x;
printf ("x
printf ( "X = = %cf\n",x);
%d\n", x) ;
}

((16)
16) main()
main()
{{
int =
int xx = 3,
3, z;
z;
z =
z = x++ ++ 110;
Xtt 0;
printf {"x
printf =
( "X = %d =
%d zz = %d",
%d", x,
x, z)
z ) ;;
}

((17)
17) mainQ
main()
{{
int =
int xx = 3,
3, z;
z;
=
zz = ++x+
ttX + 10;10;
printf ( " X
printf ("x = % = %dd zz == %d",
%d", x,
x , z)
z ) ;;
}

((18)
18) main()
main()
{{
int x = 3, z;
z;
z = x---111
x-111;
printf ("x
( "x = %
%dd zz = %d",
%d", X,x ,z)
z);
92
92 Exploring CC
Exploring

(19) main()
(19) main()
{{
intx
int x ==3,3,zz;;
z
z = x—=
x-- --11 ; ;
printf =
( "x= %%0
printf ("x = %d", xx,, zz)) ;
a zZ= %d",
}

(20) main()
(20) main()
{{
intx=3,
intx = 3 , zz;;
zZ=x++
= x++ +tx++;
x++;
printf ("x
printf ("x ==%%d d zz== % d , xX,, zz)) ;
%d", ,

(21)
(21) miiin()
main()
{{
intx=3,
int x = 3, zz;;
z = x++ +t ++x;
z =X++ ttX;
printf ( "x =
printf ("x = % d zz ==%d",
%d %d·, xx,, zz)) ;
}

(22)
(22) main()
{{
intxx ==3,
int 3, z;
z;
z =
z = x — 1 ;;
x----1
printf ("x
printf ( "x == %
%dd zz == % d " ,X,x , z)
%d", z) ;
}

((23)
23) main()
{{
int =
intxx = 3, z;
z;
zz = xl
x / +t+X:
+x;
printf =
printf ("x = % %dd zz == %d",
%d·, x,
x , z)
z) ;
}
Merry
Merry go
go Round
Round 93
93

((24)
24) main()
main()
{{
inti 3 , j;
int i ==3, j;
=
jj = +Hi+ i ** +Hi+ i **+Hi+ i ;;
printf (( "N%d",
printf % d " ,jj )) ;;
}

((25)
25) main()
main()
{{
int xx == 3,
int 3, yY == 3,
3, zZ == 33 ;;
zz -=
-= --x-- - --y
X " - —y j
;
printf ("x
printf %dd yY == %dz=%d",
( "x == % %d z =%d", x,
x , y,
y ,z)
z ) ;;
}

((26)
26) main()
main()
{{
int 10, yY == x,
int xx == 10, x, zz == xx ;;
yy-=x;
-=x;
=
zz = -x;
-x;
=-
tt = - xx;;
( "y == %
printf ("y
printf %dd zz == %dt
%d t == %d",
% d " ,y,y ,z,z ,t)t ) ;;
}

((27)
27) main()
main()
{{
int x == 10,
int y, Zz ;;
10, y,
zz=y=x;
=y=x;
yy --== x--
x--;;
zz -=
-= --x;
--x;
xx -= --x -- x--
-= --x x - ;;
( Ny=
printf ("y
printf %d zz == %d
= %d %d xx == %d", y, z,z, x)x ) ;;
%d", y,
}

((28)
28) main()
main()
{{
=
int x = 4, y
Y = 3, =
3, Zz ;;
94
94 Exploring
Exploring C
C

=
zz = x--
x - - -y;
-y; .
printf
printf ("x
( "X == %
%dd yY == %
%dd zz == %d",
% d , X,
x ,y,
,
y z)
z ) ;;1

}}

(29)
(29) main()
main()
{[
n t x,
iint y , zz;;
x , y,
xx=y=z=1
= y = z = 1 ;;
iz = ++x ||II ++y && ttZ
++Y&& + + z ;;
printf ("x =
( 'x = % =
%dd yY = % =
%dd zz = %d\n",x,
%d\n°, ~, y,y ,z)
z ) ;;
}}

(30) main()
main()
{{
n tx,
iint x , y,y , z ;:
xx=y=z=1
= y = z = 1 ;;
zZ == ++x && ++y j)II ++Z + + z ;;
printf ((·x =-%d
"x^%dy = % Y = =
% d \ n " X,x ,y,y ,Z)z ) ;;
%dd zz = %d\nft, )

}}

(31) main()
main()
{{
iint x , y,
n tx, y , z;
z;
xx=y=z=1
= y = z = 1 ;;
=
z =++x && ++y &&++z;
ttX &&++y &&++z;
printf ("x = = =
( 'x = %d yY = %d zZ = %d\n", x, y, z ) ;
}}

(32) main()
main()
{{
int x, y, z;
int x, z;
x = y = z = - 1 ;;
x=y=z=-1
z == ++x && ++y ||II ++z++z;
(Ox == %
printf ("x %dd yY == %
%dd zz == %d\n., , x y,
% d \ n " x, , y z)
,z);
}}
Merry
Merry go
go Round
Round 95
95

((33)
33) main{)
main{)
{
{
int x,
int Y, Z;
X, y, z;
x=y=z= ;
x=y=z=-1 - 1 ; .

zz == ++x
ttX \\B ++y && + + z ;
HY&&++Z:
( 'x == %
printf ("x %dd zz == %d\n",x,y,z);
%0d yY == % %d\n", X, Y,z ) :
}

((34)
34) main()
main()
{{
iint y , zz;;
x , Y,
n t X,
xx=y=z=-1
= y = z = - 1 ;;
=
zZ = ++xttX && &&HZ
&& ++y && ++z;;
printf ("x
( 'x == %d yY == %d z == %d\n",
%d\n', x, Y,z)
X, y, z) ;
}

((35)
35) main()
main{)
/{
i

int ii;;
for (( ii == --11 ; ; ii <=
for <= 1100 ;; itt
i++))
{
{
i1(i<5)
if(i<5)
continue;
continue;
else
else
break;
break;
printf ( "Gets printed only once!!" ) ;
printf ("Gets printed only once!!");
}}
}

((36)
36) main()
main()
{{
int x == 10,
intx 10, y;
y;
Y = --x-- ;
y = - - X - - ;

printf ( xx == %dy
%d Y == %d',
% d " ,X,x ,y)y ) ;;
}
96
96 Exploring C
Exploring C

(37)
(37) main()
mainO
{{
i = 2;;
inti=2
int
printf ( "i-- =
V = %d",
% d " i-, i -)) ;
}}

[B]
[8] Attempt
Attempt the following:
the following:

(1)
(1) Here is
Here is an
an ecological
ecological simulation
simulation ofof wolf
wolf and
and rabbit
rabbit popula-
popula-
tions. Rabbits eat
tions. Rabbits eat grass.
grass. Wolves
Wolves eat
eat rabbits.
rabbits. There
There is
is plenty
plenty of
of
grass,
grass, so
so wolves
wolves are
are the
the only
only obstacle
obstacle toto the rabbit population
the rabbit population
increase.
increase. The
The wolf
wolf population increases with
population increases the population
with the population of
of
rabbits. The day-by-day
rabbits. The day-by-day changes
changes in
in the
the rabbit
rabbit population
population Rand
R and
the wolf population
the wolf population W W can
can be
be expressed
expressed by by the
the following
following
formulae:
formulae:

R(tomorrow) = (1
R(tomorrow) (1 +
+ a).R(today)
a).R(today) -- c.R(today).W(today)
c.R(today).W(today)

W(tomorrow) =
W(tomorrow) = (1
(1-- b).W(today)
b).W(today) + c.d.R(today).W(today)
c.d.R(today).W(today)

aa = 0.01
0.01 = fractional
fractional increase
increase in
in rabbit
rabbit population
population without
without
threat from wolves
threat from wolves (( 0.01
0.01 means
means 11 %
% increase)
increase)

bb = 0.005
0.005 = fractional
fractional decrease
decrease in
in wolf
wolf population without
population without
rabbit to
rabbit eat
to eat

cc = 0.00001
0.00001 = likelihood
likelihood that
that aa wolf
wolf will
will encounter
encounter and
and eat
eat aa
rabbit
rabbit

dd = 0.01
0.01 =
= fractional
fractional increase
increase in
in wolf
wolf population
population attributed
attributed to
to
a devoured
devoured rabbit.
rabbit.

Assume that initially there are 10,000 rabbits and 1000 wolves.
Assume thatinitialiy wolves.
Write aa program
Write program to to calculate populations of
calculate populations of rabbits
rabbits and wolves
and wolves
over aa 1000-day
over 1000-day period.
period. Have
Have the
the program
program print
print the popula-
the popula-
tions every 25
tions every 25 days.
days. See
See what
what happens
happens when
when you
you start
start with
with 500
500
wolves instead of 1000. Try
wolves instead Try starting
starting with 2000 wolves too.
Merry go
Merry go Round
Round 97
97

(2)
(2) Super-Duper
Super-Duper Micros
Micros currently
currently sells
sells 100
100 Super-Dupers
Super-Dupers per per
month at
month at aa profit
profit of
of Rs.
Rs. 500/- per Super-Duper.
500/- per Super-Duper. They have aa
They have
fixed operating cost
fixed operating cost of Rs 10,000/-
of Rs 10,000/- that
that does
does not
not depend
depend on the -
on the
volume
volume of of sales.
sales. They
They currently
currently spend
spend RsRs 1000/-
1000/- perper month
month on on
advertising.
advertising. A A marketing
marketing consultant
consultant advised them that
advised them that if they
if they
double
double the amount spent
the amount spent on
on advertising,
advertising, sales will increase
sales will increase by by
20
20 %.
%. Write
Write aa program
program that
that begins
begins with
with the
the company's
company's current
current
status, and successively
status, and successively doubles the amount
doubles the amount spent
spent on
on advertis-
advertis-
ing until the
ing until the net
net profit
profit begins
begins to decline. Have
to decline. Have the
the program
program print
print
the number of Super-Duper sales, the advertising
the number of Super-Duper sales, the advertising budget, andbudget, and
the net profit
the net profit just before the
just before the profit
profit begins
begins toto decline.
decline.

2 2 2
(3) The equation x2 + y2 = i2 represents a circle with centre at
(3) The equation x + y = r represents a circle with centre at
origin and radius r. Write a program that reads r from the
origin and radius r. Write a program that reads r from the
keyboard and prints the number of points with integer coor-
keyboard and prints the number of points with integer coor-
dinates that lie within the circle.
dinates that lie within the circle.
(4)
(4) Write aa program
Write program that,that, for
for all
all positive integers i,
positive integers i, j,j , k, and 1 from
and 1from
11 through
through 1000,
1000, finds
finds and
and prints
prints all
all combinations
combinations ofi,j, of i, j , k,
k, and
and
ILsuch
such that
that ii + jj + k 1 and ii <<jj << kk << I.I.
k = land

(5)
(5) Write aa program
Write program which
which finds
finds four
four digit
digit perfect
perfect squares
squares where
where
the number
the number represented
represented by
by the
the first
first two digits and
two digits and the
the number
number
represented squares.
represented by the last two digits are also perfect squares.

(6) Write a program which finds a four digit number AABB which
is aa perfect
is perfect square.
square. A
A and
and B
B represent different digits.
represent different digits.
98
98 Exploring C
Exploring

Answers
Answers

Answers to [A]
Answers to [A]

(1)
(1) Output
Output

1
1
22
33

127
127
-128
-127
-126

o
0
1

Explanation
Explanation

Strange output at
Strange at first
first glance,
glance, you
you would
would agree.
agree. InIn C,C, aa char
char isis
always 11 byte
always byte long
long and
and hence
hence can
can only
only hold
hold values
values in in the
the range
range
-128 to
-128 to +
+127. In this
127. In this program,
program, till
till value
value ofj
of j is
is less
less than
than oror equal
equal
to 127
to 127 there
there isis no
no problem.
problem. Its Its value
value gets
gets printed
printed through
through
printf().
printff But once j becomes
). Butoncej becomes 127, 127,jj =J
= j + 11 tries
tries to
to make
make itit 128,
128,
which it
which it cannot
cannot become
become (( being
being aa char
char ).). Hence
Hence it it goes
goes to to the
the
otherside and picks up the value -128. This goes
other-side and picks up the value -128. 111isgoes on increasing on increasing
through j =J
throughj = j ++ 11 until
until itit becomes
becomes 127,
127, and
and then
then again
again goes
goes to
to
the negative
the negative side.
side. This
This goes
goes on
on indefinitely,
indefinitely, hencehence the above
the above
output.
output.
Merry
Merry go
goRound
Round 99
99

(2)
(2) Output
Output

No
No output
output

Explanation
Explanation

This
'Thisisisan
an indefinite
indefinite loop
loop and
and contrary
contrary toto common
common expectations
expectations
it doesn't print out the ascii table. The reason is the ; after
it doesn't print out the ascii table. The reason is the; after the
while.
while. This
This semi-colon
semi-colon reduces
reduces thethe loop
loop to...
to ...

while ((j j<<=


while 255 )
= 255)

ItItmeans
means the
the null
null statement';'
statement';' keeps
keeps getting
getting executed
executed repeated-
repeated-
ly.
ly. And
And since
sincejj doesn't
doesn't get
get incremented,
incremented, the
the condition
condition]j <=
<=255
255
remains
remains true
true forever.
forever.

(3)
(3) Output
Output

22
33

256
256

Explanation
Explanation

The prinlf()
printf( ) statement
statement is a littlelittle tricky.
tricky. Would
Would j be incre-
incre-
mented
mented first and then then printed
printed or vice
vice versa?
versa? Since ++ precedes
Since ++ precedes
jj,j's
, j ' s value
value would
would be first incremented,
incremented, and then this new new value
value
would
would be printed
printed out.
out. Therefore
Therefore whenwhen j is 1, the condition
condition is
satisfied
satisfied and the controlcontrol reaches
reaches printf().
prlntf( ). Here
Here firstly
firstly jj be-
be-
comes 2 and then it is printed. Thus the first output is 2, and
comes 2 and then it is printed. Thus the first output is 2, and
not 1. L Similarly,
Similarly, towards
towards the end when] whenj is 255,
255, the condition
condition
in thethe while
while is once
once again
again satisfied
satisfied and and the control reaches
control reaches
100
100 Exploring C
Exploring C

printf( ). Here it becomes


printf(). becomes 256 and is printed
printed out. Now when
when
the control
control reaches j ' s value as 256, the condition
reaches while with j's condition
fails
fails and
and the
the execution
execution is terminated.
is terminated.

(4)
(4) Output
Output

1 22 33.... 3276632701
.... 32766 32767-32768
-32768-32701
-32767....0
0 112 2.. 32767..
.. 3'lJ67 ..

Explanation
Explanation

indefinite for loop.


Here we have an indefinite loop. The output from 1 to
32767 is as expected.
expected. When a is 32767,
32767, its value
value is printed
printed and
a++
a++ attempts to increment"a
attempts to increment a to to 32768.
32768. aa cannot
cannot become
become 32768,
32768,
since
since this
this falls
falls outside
outside the
the integer
integer range.
range. Hence
Hence it it goes
goes to the
to the
negative side of the range and becomes -32768. With
negative side of the range and becomes -32768. With this value this value
of
of aa the
the condition
condition isis tested,
tested, which
which is bound to
is bound to gel
get satisfied
satisfied since
since
-32768
-32768 is is less
less than
than 32767.
32767. AndAnd from
from here
here onwards
onwards aa keeps
keeps
incrementing
incrementing untiluntil it
it becomes
becomes 32767,
32767, and
and then
then once
once again the
again the
same
same process
process isis repeated
repeated allall over
over again.
again. Thus,
Thus, control never
control never
comes
comes out out of
of the
the for loop.
loop. Therefore
Therefore it
it becomes
becomes an an indefinte
indefinte
loop.
loop.

What if we want to print numbers


numbers from 1 to
to 32767
32767 using
using aa for
for
loop? Write
loop? Write it in the following form·
form-

for(a
for ( a = 00;a<32767;a++)
; a < 32767 ; il++ )
printf ("%d",a+1);
printf("%d",a+ 1);

(5)
(5) Output
Output

2 3456
23456

Explanation
Explanation
rI
McrrygoRound 101

Let us
Let us isolate
isolate the
the condition
condition in the for
in the for loop
loop for
for closer
closer examina-
examina-
tion:
tion:

i++ <= 5
iff <=5

In this
In this expression
expression valuevalue ofof ii is
is first
first compared
compared with with 5,
5, and
and then
then
incremented. Thus
incremented. Thus when
when ii isis 1,
1, the
the condition
condition is is satisfied,
satisfied, andand ii
is incremented
is incremented to to 2.
2. Then
Then the the control
control reaches
reaches thethe null
null state-
state-
ment, executes
ment, executes it,it, and
and then
then goes
goes to to printf(),
printf(), where
where ii is printed
is printed
out. Having
out. Having printed
printed outout 2, 2, control
control onceonce again
again reaches
reaches the the
condition, where
condition, where since
since 2 2 is
is less
less than
than 5,5, the
the condition
condition is is satisfied
satisfied
and ii is
and is incremented
incremented to to 3.
3. Once
Once againagain control
control reaches
reaches the the null
null
statement, executes it, reaches printf() and
statement, executes it , reaches printf( ) and prints out 3. Lastprints out 3. Last
time through
time through the the loop
loop when
when ii is is 5,
5, the
the condition
condition is is once again
once again
satisfied, ii is
satisfied, is incremented
incremented to to 6, null
null statement
statement is is executed,
executed, value
value
of i (i.e. 6 ) is printed, and then the condition
of i(I.e. 6 ) is printed, and then the condition fails. On failurefails. On failure
the control
the control reaches
reaches thethe closing
closing bracebrace of of main(
maine )) and and thethe
execution is
execution is terminated.
terminated. Thus,Thus, the the output
output isn't
isn't numbers
numbers from from
11 to
to 5,
5, but
but from
from 22 toto 6.
6.

(6) Output
Output

21
21
31
31
4411
551
1
6611
7700

Explanation
Explanation

In the
In the normal
normal place
place ofof aa condition
condition inin for
for loop,
loop, here
here we have
we have
just aa j.
Just j . This
This means
means the the statements
statements in in the
the loop
loop would
would keep keep
getting executed
getting till j is
executed tillj is non-zero.
non-zero. ToTo begin
begin withj
with j isis non-zero,
non-zero,
hence first
hence first time
time around
around thethe condition
condition inin the
the for
for loop
loop is satisfied,
is satisfied,
and hence
and hence thethe control
control reaches the statementj
reaches the statement j = = i++
i++ <=<= 5.
5. Here
Here
102
102 Exploring
Exploring C

ii is
is first
first tested
tested against
against 5, 5, the
the result
result of of this
this test
test (( 11 or
or 00 )) is
is
assigned to
assigned to j,j , and
and then
then value
value of of ii isis incremented.
incremented. First First time
time
through the
through loop, with
theloop, with ii as as 1,1, the
the condition
condition is is satisfied, hence
satisfied, hence
11 is
is assigned
assigned toj to j and
and ii isis incremented
incremented to to 2.
2. With
With ii as as 22 andj
and j as
as
1, the
1, the control
control then then reaches
reaches the the printf()
printf( ) which
which prints
prints out
out values
values
of ii and
of and j.j . This
This wholewhole operation
operation is is repeated,
repeated, printing
printing in in the
the
process the
process the values
values 31,413 1 , 4 1 andand 5 5 1. With
With ii as
as 55 andj
and j asas 1 when
1 when
the control
the reaches j = i++
control reaches i++ <= 5, 5, the
the condition
condition is is satisfied,
satisfied,
therefore 11 isis assigned
therefore assigned toj to j and
and ii isis incremented
incremented to to 6.
6. With
With these
these
values the
values the control
control reaches
reaches printf(), which prints
printf( ), which prints outout 66 11 and
and
then reaches
then reaches the the condition
condition in in for.
for. Sincej
Since j isis 1,
1, this
this condition
condition is is
satisfied and
satisfied and the control once
the control once again
again reaches]
reaches j = i++ i++ <= 5. 5. Here
Here
the condition
the condition fails, fails, so
so 00 is
is .assigned
assigned toj to j and
and ii is
is incremented
incremented to to
7. These
7. values are
These values are then
then printed
printed through
through printf(),
printf(), and and then the
then the
control reaches
control reaches the the condition
condition in in for
for loop.
loop. Since
Since jj is is 0,
0, the
the
condition fails
condition fails andand the
the loop
loop is is therefore terminated.
therefore terminated.

(7)
(7) Output
Output

22 33... 32767...
... 32767 -32768 -32767
... -32768 -32767... -1 00
... -1

Explanation
Explanation

Since i++
Since i++ is being used
is being used inin the
the forfor loop,
loop, twotwo operations
operations are are being
being
carried out.
carried out. Firstly
Firstly ii is
is tested
tested for for truth
truth or or falsity,
falsity, andand then
then it is
it is
incremented. To
incremented. begin with,
To begin with, as as ii is
is equal
equal to to 1,
1, the
the test
test results
results
into aa truth
into truth and
and then
then ii is
is incremented
incremented to to 2. This 22 is
2. This is then
then printed
printed
through printf().
through printf( ). Next Next time
time whenwhen the the control reaches i++,
control reaches
since ii is
since is 2,
2, the
the test
test once
once again
again results
results into
into truth,
truth, ii is
is incremented
incremented
to
to 3 and printed out. This goes on smoothly till ii becomes
3 and printed out. This goes on smoothly till becomes
32767. When
32767. When ii is is 32767,
32767, it it evaluates
evaluates to to truth
truth and
and ++ ++ tries
tries toto
make it
make it 32768,
32768, which being an
which being an int it cannot
int it cannot become.
become. Therefore
Therefore
the number
the number from from thethe negative
negative side side of of the
the range
range (( -- 32768
32768 )) is is
assigned to
assigned i, which
to i, which is is then printed out.
then printed out. This
This goes
goes on on and
and then
then
sometime later
sometime later ii becomes
becomes -1. - 1 . With
With ii as as -1
-1 the
the test
test results
results into
into aa
truth and
truth and i++i++ makes
makes the the value
value of of ii as
as O.
0. This
This value
value is is printed
printed
Merry go
Merry go Round 103
103

out and once again the control reaches the test in the for loop.
This time, however, is o.
however, the test fails since value of iiis 0. Therefore
Therefore
the loop is terminated
terminated and the execution comes to an end.

(8)
(8) Output
Output

Explanation
Explanation

A do-while
A do-while allows
allows the
the body
body of
of the
the loop
loop to
to get
get executed before
executed before
testing the
testing the condition.
condition. Therefore
Therefore toto begin
begin with,
with, value
value of of a, i.e.
a, i.e.
5, gets printed,
5, gets printed, and
and then
then the
the control
control reaches
reaches the
the statement
statement aa
==·1.
- 1 . Be
Be careful.
careful. This
This isis different
different from
from aa -= 1 . aa =-
-= 1. =- 11 would
would
simply
simply assign
assign -1-1 to
to a, whereas aa -= 11 would
a, whereas would decrement
decrement the the
value
value of of aa by
by 1.
1. In our case,
In our case, -1 is assigned
-1 is assigned to
to aa and
and then
then the
the
control
control reaches
reaches the condition in
the condition in the while. Since
the while. Since -1 -1 is
is not
not
greater
greater than 0, the
than 0, the condition
condition fails
fails and
and the
the loop
loop is
is terminated.
terminated.

(9)
(9) Output
Output

bb =
=44 a=
a =24
24

Explanation
Explanation

Get back to the precedence


precedence table. You would observe that +
enjoys aa higher
enjoys higher priority
priority as
as compared
compared to to %=.
%=. Hence
Hence the addition
the addition
is
is carried out first and the statement therefore reduces to bb %=
carried out first and the statement therefore reduces to % =
7,
7, which evaluates to
which evaluates to 4.
4. This
This 44 is assigned to
is assigned to b.
b. Similarly, the
Similarly, the
next statement first
next statement first performs
performs the
the addition
addition and
and then
then *=, thereby
thereby
resulting in 24.
resulting in 24.

(10) Output
(10) Output

x =21
= 21
104
104 Exploring
Exploring C

Explanation
Explanation

According to
According the precedence
to the table, firstly
precedence table, firstly + will
will be
be performed,
performed,
followed
followed by by *=. Thus,
Thus, first
first 33 + 44 results
I
results into
into 7,
7, and
and on
on
multiplication with 33 results
multiplication with results into
into 21.
21.

(11) Output
(11) Output

xx=3y=9z=27
= 3y = 9z = 27

Explanation
Explanation

zz = y = xx is
is evaluated
evaluated from
from right
right toto left,
left, assigning
assigning firstly
firstly 33 to
to y
and then to
and then to z. The next
z. The next statement
statement is is also
also evaluated
evaluated from
from right
right
to left.
to left. Therefore firstly 33 **33,, i.e.
Therefore firstly i.e. 99 is
is assigned
assigned to
to yy and
and then
then zz
*= yy is performed, zz *= yy evaluates
is performed. evaluates to to 27,
27, which
which isis assigned
assigned to to
z.
z.

(12) Output
(12) Output

xx=3y=1z=3
=3y=1z=3

Explanation
Explanation

= =
zz = yy = xx isis evaluated
evaluated fromfrom right to left assigning
right to-left assigning the
the value_3
value. 3
to the
the variables
variables z andand y. The
The next
next statement
statement is also
also evaluated
evaluated
from right to
from right to left.
left. Firstly
Firstly yy 1=
/= xx is
is evaluated,
evaluated, which
which isis same
same asas
yy = yy 1/ x.
x. Thus,
Thus, 11 isis assigned
assigned toto the
the variable
variable y.y. After this z *=
After this
yy is is evaluated,
evaluated, whichis
which'is same as zz = zz * y.
same as y. This
This assigns
assigns the
the value
value
33 toto the
the variable
variable z. z.

(13) Output
(13) Output

Error message:
Error message: Expression
Expression syntax
syntax in
in function main
function main
Merry go Round
MerrygoRound 105
105

Explanation
Explanation

operator *=, a blank


While using the operator blank between
between •* and
and = is never
never
allowed.
allowed. They must go together as *=. Hence the.error mes-
sage.
sage.

(14) Output
(14) Output

xx=-3y=Oz=O
= - 3 y = 0z = 0

Explanation
Explanation

To begin with, z and yyare are assigned the value of x, X, i.e. 3. Look
statement
at the next statement closely. This expression
expression is evaluated from
from.
right
right to
to left.
left. Firstly
Firstly the
the value
value -z
-z is
is assigned
assigned toto x.
x. Hence
Hence xx gets
aa value -3. Then y += += xX is evaluated. This is same as y == y ++
x,
X, and
and 33 +:,.-3,
- 3 , i.e.
i.e, 0,
0, is
is assigned
assigned to to y.
y. The
The value
value ofof yy is
is then
then
assigned
assigned to to z.
z. Thus,
Thus, zz also
also turns
turns out
out to
to be o.
be 0.

(15)
(15) Output
Output

xx=6
=6
xx=7
=7

Explanation
Explanation

x++
x++ increments
increments the the value
value ofof xx to
to 66 and
and the
the printf(
priBtf( )) promptly
promptly
prints
prints itit out.
out. ++x
++x also
also increments-the
increments· the value value of of xx toto 77which
which isis
then
then printed
printed out
out byby the
the printft).
priDtf(). Note Note that
that ++,
++, as as used
used here,
here,
won't
won't make
make anyany difference
difference whether
whether the the ++
++ occurs
occurs before
before or
or
after
after the
the variable.
variable. However,
However, when when used used inin association
association with with
something
something else else (like
(like in =
in aa = i++
i++ or =
or aa = ++i,
++i, inin which
which case case each
each
statement
statement would
would store
store aa different
different value
value inin aa )),, the
the position
position ofof
++
++ operator
operator doesdoes matter.
matter. Thus,
Thus, the the following
following printf(priBtf( )s
)s are
are
different.
different.
106
·106 Exploring C
Exploring C

prinl1(("%d",
printf "%d", ++x);
+tx) ;
printf (("%d",x++);
"%d", x++ )";

(16) Output
(1') Output

xx=4z=-13
= 4z=»13

Explanation
explanation

Here, since
Here, since the
the incrementation
incrementation operator
operator ++
++ is
is present
present after the
after the
variable x, firstly the value of x is used in evaluation of the
variable
expression and is
expression and is then
then incremented.
incremented. Thus,
Thus, firstly
firstly xx + 1 0 is
+ 10 is
performed which results
performed which results into
into 13,13 is assigned
13, 13 is assigned toto z,
z, then
then xx isis
incremented Thus, finally the values of z and x are 13 and
incremented to 4. Thus,
4.
4.

(17) Output
(17) Output

xx=4z=14
= 4z = 14

Explanation
Explanation

Here, since the incrementation


incrementation operator ++ is present before
the variable x, firstly the value ofx
of x is incremented and is then
used in evaluation of the expression. Thus, firstly ++x ++x is
performed which increments
increments x to 4 and then this 4 is added to
10 to yield 14, which is then assigned to z. Thus, finally tIrethe
values of z and x are 14 and 4.

(18) Output
(18) Output

xx=2z=-108
= 2z = -108

Explanation
Explanation
Merry go Round
Merry go Round 107
107

Look at
Look — 1 1 1 as
at xx---111 as x-- 1 1 1 and
x~ -- 111 and the
the expression
expression immediately
immediately
becomes comprehensible.
becomes comprehensible. Since Since — follows the
- follows the variable
variable x,
X,
firstly 111 is
firstly 111 is subtracted
subtracted from
from xx (( 33 -- 111,
111, i.e
i.e -108
-108 ),
), then
then -108
-108
is assigned to
is assigned to z,
z, and
and finally
finally the
the decrementation
decrementation operator
operator
reduces the
reduces the value
value ofof xx to 2.
to 2.

(19) Output
(19) Output

xx=2z=4
=2z=4

Explanation
Explanation

The expression
expression which assigns the value to z becomes simple
to understand
to understand if if we
we look
look at
at it
it as =
as zz = xx-- - -1. Thus firstly
1 . Thus firstly -1
-1 is
is
subtracted
subtracted from x, which gives 4, then 4 is assigned to z, and
from x, which gives 4. then 4 is assigned to z, and
finally
finally xx is
is decremented
decremented toto 2.
2.

(20)
(20) Output
Output

x=5z=6
x = 5z = 6

Explanation
Explanation

Since ++ occurs after the variable x, its value is firstfirst used to


evaluate the
evaluate the expression,
expression, and
and then
then xx is
is incremented
incremented twice. Thus
twice. Thus
xx +
+ xx would
would result
result into
into 6,
6, and
and the
the result
result would
would be
be assigned
assigned to to
z. After this,
z. After this, the
the first
first x++
x++ would
would increment
increment the the value
value of
of xx to
to 4,
4,
followed by second x++, which would further increment
followed by second x++, which would further increment x to x to
5.
5.

(21) Output
(21) Output

X = 5z = 8
x=5z=8
108
108 Exploring
Exploring C

Explanation
Explanation

This one is a bit tricky,


tricky, follow it carefully. We might be led to
believe that
believe that while
while evaluating
evaluating zz what
what would
would bebe added
added is is 33 and
and
4. But
4. But this is definitely wrong.wrong. This
This is because
because while
while calculat-
calculat-
ing
ing z, Z, the
the very
very first
first operation
operation that
that is
is performed
performed is is ++x, which
++I, which
ncrements the
"ncrements the value
value ofof xx to
to 4.
4. So
So by
by the
the time
time the
the addition
addition (( xx
+
+ xx )) is
is performed,
performed, xx has has already
already become
become 4. 4. Thus
Thus 44 + + 44 would
would
be performed and
be performed and not
not 33 + 4.
4. After
After this
this the
the result
result of
of the
the addition
addition
(( 44 + 44 )) is
is assigned
assigned to to the
the variable
variable z,
z, and
and then
then xx is
is incremented
incremented
to
to 55 ((because
because of of x++
x++ ).).

(22) Output
(22) Output

Error message: Lvalue


Error message: Lvalue required
required in function main .•

Explanation
Explanation

What do we mean
What mean by lvalue'!
lvalue? An lvalue is a variable
variable whose
whose
value change ( can have a new value
value can change value assigned
assigned to it ).
Contrary to this
Contrary rvalue represents
this an rvalue represents a variable
variable whose value
value
cannot change. An
cannot change. An easy way to differentiate
differentiate the two is that an
lvalue occur on the left of assignment
Ivalue can occur assignment operator,
operator, whereas
whereas
an rvalue can occur
an rvalue occur to its right.
right.

x-—1 is
x····l interpreted by the compiler
is interpreted compiler as x--
x --1.1 . And since — -
cannot applied to constants
cannot be applied constants (in —1), it flashes the
(in this case -1),
error message. Had
error message. Had the statement
statement been
been written 1 , it
written as xx-- - -I,
would have worked.
have worked.

(23) Output
(23) Output

xx=4z=1
=4z=1

Explanation
Explanation
Merry go Round
Merry 109
109

++ enjoys
enjoys aa higher
higher priority
priority than
than /.
/. Therefore,
Therefore, firstly
firstly x is
x is
incremented to
incremented to 4. So by
4. So by the
the time
time the
the division
division is
is carried
carried out;
out; xx
has already
has become 4.
already become 4. During
During division
division 4/4
4 / 4 is
is performed
performed andand
the result
the result is assigned to
is assigned z.
to z,

(24) Output
(24) Output

216
216

Explanation
Explanation

iiis
is initialised
initialised toto 33 andthenj
andthen j is is assigned
assigned the
the cube
cube ofo ++i.
fAm ong
Among
the multiplication
the operator * and
multiplication operator and the increment operator
the increment operator ++,++,
the ++ operator
the operator has the higher
has the higher priority.
priority. Hence,
Hence, first
first ii gets
gets
incremented as
incremented as many
many timestimes as
as the
the ++ is
is encountered,
encountered, so so that
that ii
is now
is now 6. 6. After this jj is
After this is evaluated
evaluated asas 6 * 6 * 6, giving
giving the
the output
output
216.
216.

(25) Output
(25) Output

xx=2y=2z=8
=2y=2z=8

Explanation
Explanation

While evaluating
While evaluating z,z, the
the highest
highest priority is enjoyed
priority is enjoyed by by the unary
the unary
minus, which
minus, which attaches
attaches aa minus
minus signsign to
to the
the value
value ofof x,x, making
making
it -3. Note
it -3. Note that
that on
on doing
doing this
this the
the value
value ofof the
the variable
variable x remains
x remains
unchanged. Next
unchanged. Next operation performed is
operation performed ~y which
is -y which decrements
decrements
y to 2.
yto 2. Following
Following this,
this, the
the binary
binary minus
minus isis performed
performed ((-3 -3 -- 2),
2 ),
which evaluates
which evaluates toto -5,
-5, and
and then
then -:
-= results
results into
into 88 (3
( 3 -- -5)
-5), which
Iwhich
is assigned
is assigned to to z.
z. Lastly
Lastly xx is
is decremented
decremented to to 2.
2.

(26) Output
(26) Output

yy=Oz=-10t=-10
= 0z = -l0t = -lu
110
110 Exploring C
Exploring C

Explanation
Explanation

Is Y
Is =
y = xx acceptable
acceptable in in the
the declaration
declaration statement?
statement? Answer
Answer is is yes.
yes.
So long
So long asas xx has
has been defined earlier,
been defined earlier, it can be
it can be assigned
assigned to to yy
while declaring
while declaring y. Same is
y. Same true about
is true about zz = x. The next
x. The next statement
statement
is simple. It performs y - x and the result 0 is
is simple. It performs y - x and the result 0 is assigned to assigned to y.
y. zz
- -x
= -x performs
performs aa unary
unary minus
minus operation
operation on on x,
x, which
which results
results into
into
-10. This
-10. This is
is then
then assigned
assigned to to z.
z. Note
Note that
that by
by using
using unary
unary minus,
minus,
the value
the value stored in xx remains
stored in remains unchanged.
unchanged, tt =- xx is is similar
similar toto the
the
previous statement and hence assigns -10 to t. It
previous statement and hence assigns -10 to t. It highlights thehighlights the
fact that
fact that while
while using
using thethe unary
unary minus
minus operator,
operator, the blank
the blank
between the
between the minus
minus signsign and
and the
the variable
variable namename is is optional.
optional.
Thus,
Thus, tt =-
=- xx is
is same
same asas, tt = -x.
= -x.

(21) Output
(27) Output

y_=0z = 2 x = 6

Explanation
Explanation

In the
In first arithmetic
the first arithmetic statement
statement since since --
—occurs
occursafterafterthe
thevari-
vari-
able x,
able x, firstly
firstly value
value ofof xx is used to
is used to calculate
calculate yy -- x,
x, and
and then
then xx is
is
decremented. Thus
decremented. Thus y y -- xx results
results into
into 0,
0, which
which isis assigned
assigned to y,
to y,
and xx is
and is decremented
decremented to 9. In
to 9. In the
the next
next statement,
statement, firstly
firstly xx is
is
decremented and
decremented and then
then this
this decremented
decremented value value isis used
used to calcu-
to calcu-
late zz -- x.
late x. This
This results
results into
into xx being
being decremented
decremented to and zz -- x
to 88 and .(
being evaluated
being evaluated to to 2,
2, which
which is then assigned
is then assigned to
to z.z.

The next
The next statement
statement deserves
deserves aa careful
careful look.
look. Here,
Here, firstly
firstly xx is
is
decremented (( through
decremented through --x)
~x ) to
to 7, and
and then
then this
this 77 is is used
used toto
calculate the
calculate the value
value ofof x-x.
x - x. This
This evaluates
evaluates toto 77 -- 77,, which
which isis O.
0.
After this x -= -0- is performed, which results in
After this x -=-Ois performed, which results in x being once x being once
again assigned
again assigned aa value
value 7.
7. And
And finally
finally x~
x-- is
is performed,
performed, which which
decrements xx to
decrements to 6.
6.
Merry RO Round
Merry go 111
111

(28) Output
(28) Output

x=3y=3z=1

Explanation
Explanation

While evaluating
While evaluating z,
z, since
since -—operator
operatoroccurs
occursafter
afterthe
thevariable
variable
x, firstly
x, firstly value
value of
of x is used
x is used toto calculate
calculate xx -- y,
y, and
and then
then xx is
is
decremented. Thus
decremented. Thus xx -- yy results
results into
into 1,
1, which
which isis assigned
assigned toto z,
z,
and xx is
and is decremented
decremented to to 3.
3.

(29) Output
(29) Output.

xx=2y=1z=1
= 2y = 1z = 1

Explanation
Explanation

First let
First let us
us bind
bind the
the operators
operators according
according toto the
the precedence
precedence table.
table.
&& hashas higher
higher priority
priority over II. Therefore,
over ||. Therefore, binding
binding the
the operators
operators
we get,
we get,

zZ == HX
++xII|| ((++y &&HZ)
Hy && ++z ;

Firstly xx will
Firstly will be
be incremented
incremented to to 2.
2. This
This is
is aa truth
truth value
value (since
( since
it is
it is non-zero
non-zero ), ), and
and the operator II|| requires
the operator requires onlyonly one
one ofof its
its
conditions to
conditions to be
be true
true for
for the
the entire
entire statement
statement to to be
be true.
true. Thus
Thus
once
once 22 is
is checked
checked forfor truth, and indeed
truth, and indeed itit turns
turns out
out to
to be true,
be true,
the rest
the rest of
of the
the statement
statement would
would be be ignored.
ignored. So So yy and
and zz would
would
both remain
both remain unchanged,
unchanged, i.e.i.e. at
at 1.
1. The
The truth
truth value
value of
of the test, 1,
the test, 1,
is then
is then assigned
assigned toto z.
z.

(30) Output
(30) Output

xx=2y=2z=1
=2y=2z=1
112
112 Exploring C
ExploringC

Explanation
Explanation

Here &&
Here && enjoys
enjoys aa higher
higher priority
priority as
as compared
compared to II. Hence
to ||. the
Hence the
first condition
first condition (( ++x
++x &&
&& ++y++y )) would
would bebe evaluated
evaluated first. If it
first. If it
turns
turns out
out to
to be false only
be false then the
only then the second
second condition
condition (( ++z
++z ))
would
would be evaluated. While
be evaluated. While evaluating
evaluating the first condition
the first condition xx and
and
yyare
are both
both incremented
incremented to to 2.
2. Thus
Thus the
the first condition becomes,
first condition becomes,

(2&&2)
(2&&2)

&& requires
&& requires aa truth
truth value
value to
to its
its left
left and
and right
right for
for the whole
the whole
statement to
statement to evaluate
evaluate toto true.
true. In
In this
this case
case since
since there
there are truth
are truth
values on left
values on left and
and right
right of
of &&
&& thethe statement
statement is,treated
is treated as
as true
true
and
and hence
hence 11 is
is assigned
assigned toto z.
z. Since
Since the first condition
the first condition hashas
evaluated to true
evaluated to true the
the second
second condition
condition isis not
not evaluated
evaluated at all.
at all.

(31) Output
(31) Output

xx=2y=2z=1
=2y=2z=1

Explanation
Explanation

Since ++x,
Since ++x, ++y
++y and
and ++z
++z are
are all
all combined
combined using
using &&
&& operators,
operators,
to check the truth or falsity of the statement x, y and z are first
incremented, resulting in they taking a value 2 each. Thus the
incremented, resulting
condition becomes,
condition becomes,

zz=2&&2&&2
= 2&&2&&2

Since all three conditions


conditions are true, the whole condition is
treated as true.
treated as The truth
true. The truth value
value of
of this
this condition
condition ((i.e
i.e 11)) is
is then
then
assigned to
assigned to the variable z.
the variable z.

(32) Output
(32) Output
Merry go Round
MerrygoRound 113
113

xx=Oy=-1
= 0y = -1z =0
z=O

Explanation
Explanation

Since priority
Since priority ofof && is is higher
higher than
than that
that of II, the
of ||, the first condition
first condition
to be
to be evaluated
evaluated is is (( ++x
++x && ++y).
++y ). If
If this
this condition
condition turns
turns out
out
to be
to be true,
true, then
then aa truth
truth value,
value, 1,
1, is
is assigned
assigned to to z.
z. If
If this
this turns
turns
out to be
out to be false,
false, then
then the
the second
second condition
condition isis evaluated.
evaluated.

To evaluate
To evaluate thethe first
first condition,
condition, x x is
is incremented
incremented fromfrom -1 to o.
-1 to 0.
So thethe condition
condition becomes
becomes (( 00 && && ++y ++y ). ). Since
Since ++x
++x has has
evaluated to
evaluated to 00 and
and ++x
++x andand ++y
++y are
are combined
combined using
using the
the &&
operator, irrespective
operator, irrespective of what is
of what is the
the result
result of
of ++y,
++y, the
the condition'
condition-
is going
is going toto evaluate
evaluate to to false.
false. Therefore,
Therefore, the condition is
the condition aban-
is aban-
doned here itself without incrementing
doned here itself without incrementing y. Since. the first
Since. the first
condition is
condition is evaluated
evaluated to to falsity,
falsity, the
the second
second condition
condition (( ++z )is)is
evaluated now.
evaluated now. On On incrementing
incrementing zz the the condition
condition evaluates
evaluates to to
(( 00 ),
), which
which is is also.false.
also false. Since
Since neither
neither ofof the
the two
two conditions
conditions
are true,
are true, 00 is
is assigned
assigned to to z.
z. So
So in
in the
the final
final output
output x x and
and zz are
are 00
while y remains
while remains -1. -1.

(33)
(33) Output
Output

xx=Oy=Oz=O
=0y=0z=0

Explanation
Explanation

Taking into
Taking into account
account the
the priorities
priorities of
of logical
logical operators,
operators, the the
conditions to
conditions to be
be evaluated
evaluated are
are (( ++x
++x )) and
and (( ++y
++y && && ++z ++z ).).
Since the
Since first and
the first and second conditions have
second conditions have been
been combined
combined
using ||II operator,
using operator, the
the second
second condition
condition would
would be
be evaluated
evaluated onl onlyy
if first
if first turns
turns out to be
out to be false.
fake. And
And the
the first
first one
one indeed turns out
indeed turns out
to be
to be false
false since
since incrementing
incrementing x x by
by 1
1 makes
makes itit 0,
0, which
which is the
is the
falsity value
falsity value inin C.
C. Therefore
Therefore the
the second
second condition
condition is evaluated.
is evaluated.
And the
And the second condition too
second condition too meets
meets thethe same
same fate,
fate, since
since onon
114
114 Exploring C
Exploring C

incrementing
incrementing y it becomes O. 0. Therefore the condition becomes
becomes
( 0 &&
&& z++ ), which turns out to be false. Here, Zz doesn't
doesn't get
a chance to to get incremented, as the condition before && is
already
already O.0. Now
Now since
since both the conditions
both the conditions have
have evaluated
evaluated to
to
falsity, the false
falsity, the false value
value 00 is
is assigned
assigned to z.
to z.

(34) Output
(34) Output

xx == 00y
~.==-1-1z z= =0 0

Explanation
Explanation

For the
For the entire
entire condition
condition to evaluate to
to evaluate to true,
true, ++x, ++y and
++X,++y ++z
and ++z
all
all must
must evaluate
evaluate to to true.
true. So
So to
to test
test the
the condition,
condition, Firstly
firstly ++x
++x isis
performed,
performed, which which results
results into
into aa O.0. Now,
Now, since
since ++x
++x has
has
evaluated
evaluated to to 0,
0, irrespective
irrespective of of the
the results
results of
of ++y and ++z,
++y and the
++z, the
whole
whole condition
condition is is going
going toto evaluate
evaluate to to false. Therefore C
false. Therefore C
doesn't bother to
doesn't bother to evaluate
evaluate ++y
++y andand ++z, and assigns
++Z, and assigns aa falsity
falsity
value, i.e. 0,
value, i.e. 0, to
to the
the variable
variable z.z. Thus
Thus xx has
has become
become 00 duedue to
to
incrementation, z has become 0 due to evaluation
incrementation, z has become 0 due to evaluation of the whole of the whole
condition
condition to to falsity, whereas yy doesn't
falsity, whereas doesn't get
get aa chance
chance toto change
change
at
at all,
all, and
and hence
hence remains
remains at -1.
at -1.

(35) Output
(35) Output

No output
No output

Explanation
Explanation

The fer-loop
forioop begins with an initial value on of i equal to -1.
-1. When
i has,
has a value -1, the condition ( i < 5 ) is satisfied hence the
continue statement gets
continue statement gets executed. This sends
executed. This sends the control to
the control to i++
i++
in the
.in the for
for statement.
statement. OnOn incrementing
incrementing. iito
to 0,
0, the
the condition
condition inin
the for loop
the for loop is
is tested
tested which evaluates to
which evaluates to true,
true, and
and hence once
hence once
again
again the control reaches
the control reaches inside
inside the
the loop.
loop. Once
Once inside, again
inside, again
r Merry
Merry go Round 115
115

the iFs
if's condition is satisned
satisfied and tontinue
continue takes the control to
i++. This is repeated till value of i remains less than 5. The
moment ii equals
moment equals 5,
5, the condition ii < 55 fails,
the condition fails, hence
hence the control
the control
reaches
reaches the
the else
else block and executes
block and executes the
the break
break statement.
statement, break
break
takes the control
takes the control outside
outside the
the for
for loop.
loop. Here,
Here, since
since there
there are
are no
no
statements,
statements, thethe execution
execution is terminated. The
is terminated. The printf(
printf()) inside
inside
the loop doesn't
the loop doesn't get
get aa chance to get
chance to get executed,
executed, hence
hence there
there is
is no
no
output
output inin this program.
this program.

(36) Output
(36) Output

Error message:
message: Lvalue
Lvalue required in function main

Explanation
Explanation

Lvalue is a variable
variable which can be assigned a new value in the
program. Here, —x,
program. --x, if evaluated, would result into 9, which
would be
would be assigned
assigned to
to y.
y. But
But the
the problem
problem comes
comes after this, when
after this, when
9— is to
9-- is tobe
be evaluated.
evaluated. This
This can't
can't be
be done
done because
because 99 is
isaa constant
constant
and
and inin that
that sense
sense cannot
cannot be
be changed.
changed. Therefore,
Therefore, in
in place
place of
of 99
the compiler expects
the compiler expects something
something which
which can change; in
can change; in general
general
an lvalue.
lvalue. Hence the error message.
message. .

(37) Output
(37) Output

i-- = 22
i~

Explanation
Explanation

Anything
Anything other than a format specification when enclosed in
the format string
the format string of
of printf()
printfO is is printed
printed as
as it
it is.
is. Therfore
Therfore i--
i— ==
is transferred to the screen as it is. Then %d prints the current
is'transferred
value of
value of i,
i, i.e.
i.e. 22 and
and the operation then
the operation then proceeds
proceeds to to decrement
decrement
iitoto 1.
1. Since
Since --—occurs
occursafter
afteri iininprintf(
printf(), firstlythe
), firstly thevalue
valueofofii
is printed and then decremented.
decremented.
116
116 Exploring
Exploring C

Solutions to [B]
[8]

(1) Program
Program

main())
,fnain(
{{
float a == 0.01,
float 0.005, c == 0.00001,
0.01, bb == 0.005, 0.00001, dd == 00.01
. 0 1 ;;
int r1 == 10000,
ii'll r1 10000, w1w1 == 2000, r2, w2
2000, r2, w 2 ;;
irt
int i:i:

for ( ii = 1 ;; i <<== 11000


0 0 0 ; iiH)
++)
{{
r2 = ( 11 + aa)) **rr11 -- cc** rr11 **ww11 ;;
w2 = ( 1 - b ) * w 1 +c*d*r1
w2=(1-b)*w1 + c * d * M **w1; w1;

(if{i%25==0)
f(i%25==0)
printf ("\nAfter w2) ;
( "\nAfter %d days R = %d W = %d", i, r2, w2)

r1 =
r1 = rr2;
2;
w1
w1 ==w2;
w2;
}}
}}

Sampu run
Sampte run

=
After 25 days R = 7958 W = 1800
1800 =
After 50 days R == 6654 W = 1602
1602
=
After 75 days R = 5832 W = 1427
1427 =
After 100 =
100 days R = 5337 W = 1206
1206
After 125
125 days R = 5070 W = 1116
1116 =

Explanation
Explanation
Merry go Round
MerrygoRound 117
117

r l and wI
Here r1and w l represent today's
today's populations of rabbits and
wolves respectively,
wolves respectively, whereas
whereas r2 r2 and
and w2w2 represent their
represent their
torn morrow's populations.
tommorrow's populations. Beginning with 10000 and 2000 as
rabbits' wolves' populations,
rabbits' and wolves' populations, through the for f o r loop their
tomorrow's populations
tomorrow's are calculated
populations are calculated using
using the
the formulae.
formulae. TheThe
populations
populations calculated
calculated are
are printed
printed after
after aa gap
gap ofof 25 days.
25 days.
Whether
Whether 25 25 days
days are
an: over
over is
is checked
checked through the iiff statement
through the statement
within the ffor
within the o r loop.
loop. The
The same program can
same program can be
be run
run with
with dif-
dif-
ferent initial values
ferent initial values of r l and w
of r1and wI.l .

(2)
(2) Program
Program

main()
main( )
{
{
a~ = 1000
float opercost = 10000, pps = 500, adv 1000;;
float curprof,
float curprof, newprof
newprof;;
int sale = 100
100;;

sale * pps ) - ( opercost + adv)


curprof = ((sale*pps)-(opercost adv);

(1)
while (1
{{
adv*=2;
adv*=2;
( sale** 120
sale = (sale 1 2 0/100)
/100);

a l e **ppps
newprof = ((ssale p s )) --(opercost adv);
( opercost + adv)

if ((newprof
newprof << curprof)
curprof)
break;

curprof = newprof
newprof;;
}}

printf ("Sale
( ·Sale = %d\n", sale)
sale);;
printf (("Advertising
·Advertising expenses = %1\n",adv)
%f\n", a d v ) ;
printf (("• Profit = %f, curprof);;
%f, curprof)
118
118 Exploring C
Exploring C

}}

Sample run
Sample run

=
Sale = 296
Advertising
Advertising expenses
expenses =
= 64000
64000
Prom = 81500
Profit = 81500

Explanation
Explanation

To begin
To begin with,
with, the
the current
current profit
profit is
is calculated
calculated using
using the current
the current
sale, and current
sale, and current advertising expenses. Then
advertising expenses. within an
Then within in-
an in-
definite while
definite while loop,
loop, the
the advertisement expenses are
advertisement expenses are doubled
doubled
with aa corresponding
with corresponding riserise (( 20
20 %% )) in
in the
the sales
sales figure.
figure. On
On the
the
basis of
basis of these new sales
these new sales figures
figures and
and advertising
advertising expenses, new
expenses, new
profit is
profit is calculated.
calculated. This
This value
value is is stored
stored inin the variable
the variable
newprof.
newprof. TheThe moment
moment the the newprof
newprof figure
figure goes
goes below
below the
the last
last
newprof figure, the
newprof figure, the control
control breaks
breaks out
out of
of the loop and
the loop prints
and prints
the sale, advertising
the sale, advertising expenses
expenses and and the
the profit
profit figures.
figures.

(3)
(3) Program
Program

main()
main()
{{
float rr;;
int x, y, points == 0, ii;;

printf ("\nEnter
( "'nEnter the radius of the circle
circle");
•) ;
scant ("%f',
scanf ( " % f , &r)
&r);

for ( x == 00 ;; xX <= <= rr;; x++


x++))
{{
for
f o r (( yy == 11 ;;Yy <= < = rr ;; yy++
+ + ))
{
{
ifif (( ((xx **xx ++ yy **yy)) <=
<= (r( r** r)
r ) ))
Merry go
Merry go Round
Round 119
119

points++;
points++ ;
}}
}}

points ** 4 ++ 1 ;
points = points
points
printf( "No. of points
printf( points inside
inside the circle
circle = %d", points);;
%d·, points)
}}

Sample run
Sample run

Enter the radius


radius of
of the
the circle
circle 44
of points
No. 'of points inside
inside the
the circle
circle = 49=
Explanation
Explanation

Assume that
Assume that the
the centre
centre ofof the
the circle
circle is at origin
is at origin (( 0,00, 0 ).). Now,
Now,
if aa point
if point lies
lies inside
inside the circle, its
the circle, its distance
distance fromfrom the the centre
centre ofof
the circle
the circle must
must be be less
less than
than the
the radius
radius of of the
the circle.
circle. If If xx and
and yy
are the
are the coordinates
coordinates of the point,
of the point, then
then for
for this
this point
point to to lie inside
lie inside-
the circle,
the circle, itit must
must satisfy
satisfy the
the condition
condition givengiven inin the
the if if statement
statement
in the
in the program
program above.
above. If If this
this condition
condition is is satisfied,
satisfied, then then the
the
variable points
variable points is incremented, which
is incremented, which keeps track of
keeps track the num-
of the num-
ber of
ber of such
such points
points encountered.
encountered. The The two
two for
for loops
loops change
change thethe
xx and
and yy coordinates
coordinates of of points
points from
from 00 toto rand
r and 11 toto rr respectivel
respectively. y.
This would
This would countcount the
the points
points lying
lying inin the
the first
first quadrant
quadrant of the
of the
circle, and
circle, and those
those on
on the
the positive
positive Y Y axis.
axis. This
This figure
figure is is multiplied
multiplied
by 44 to
by take care
to take care of
of the
the points
points lying
lying inside
inside the-circle
thccircle in in the
the other
other
three quadrants
three quadrants and and remaining
remaining axes. Finally, as
axes. Finally, as the coordinate
the coordinate
(( 0,0, 00 )) never
never got
got included,
included, we we addadd 11 toto points
points andand obtain
obtain the
the
total number
total number of of points
points with integer coordinates.
with integer coordinates.

(4)
(4) Program
Program

main()
main( )
{{
120
120 Exploring
Exploring C

int i, j, k,
k, I;I;

for (1
(I = 1 ; l1<=
< = 1000;
1000:1++) 1++)
{{
for =
for (( kk = 11 ;;kk << lI ;; kk++
+ + ))
{
{
• for(j=1 ;j<k;j++)
. {for ( j = 1 ; j < k; j++)
{ for ( i = 1 ; i < j ; iff )
for
{ ( i = 1 ; i < j ; i++)
{ if ( ( i+ j + k) == I )
i f ( ( iprintf(
+ j + k"\n%d =
) = = l )+ %d + %d %d", i, j, k, I) ;
} printf ("\n%d + %d + %d = %d", i, j, k, I ) ;
} }
} }
} }
} }
}
Sample run
Sample run

1+2 + 3 = 6
1+2+3::=6
1+2+4=7
1+2+4=7
11+3+4=8
+3+4=8
1+2+5=8
1+2+5=8
2+3+4=9
2+3+4=9
1+3+5=9
1+3+5=9
t •• t' •• '••• 0 " .0'

Explanation
Explanation

S i n c ei,! j,j , k,
Since k, and 1 all are
and 1all are to
to vary
vary from
from 11toto1000,
1000,should
shouldwewenot
not
write each
write each ffor o r loop
loop to vary from
to vary from 1 1 to 1000?
10001 This
This is not
is not
necessary, since there
necessary/since there is
is no
no point
point inin increasing
increasing the
the value of kk
value of
beyond that
beyond that of 1, or
of I, or value ofjj beyond
value of beyond that of k.
that of k. This
This is
is because
because
Merry
Merry go
80 Round
Round 121
121

condition (( ii <<jj << kk << 1I ) would get violated.


then the condition violated The fforor
loops
loops thus have been written such that the condition is met at at
all times. Within the innermost loop, if the the other condition (i (i
==
++jj ++ kk = = 1I ) is satisfied, the values of i,i,j,
j , kk and
and II get printed,
printed,
otherwise
otherwise the control loops around to try the condition for the the
next
next set
set of
of values.
values.

((5)
5) Program
Program

#include
'include "math.h"
mainQ
main( )
{
{
int i, a, num, d1,
d1, d2, d3, d4, nleft,
d3, <J4, nleft, nright,
nright, x, Y;
X, y;

for ( ii = 1000;
1000 ; ii<=9999;i++)
<= 9999 ; iff )
{
{
aa=sqrt(i);
= sqrt(i);

iif(i==a*a)
f(i==a*a)
{{
num=i;
num = i;
d4 = n u m % 110;
d4=num% 0;
num == num
num /10;
num/10;
d3== num
d3 num% 10;
% 10;
num = num /10;
num = num/10;
d2 == num
d2 % 10;
num%10;
num == num
num /10;
num/10;
d1 =num%10;
d1 =num%10;

nleft = d1*
d1 * 10 + d2d2;;
nright = <J3*10
d3 *10 + d4;d4;
x = sqrt ((nleft);
nleft) ;
y = sqrt( nright);;
sqrt ( nright)

if (nleft
( nleft == x ** xx &&
&& nright
nright ==
== yy **yy)
)
printf ("Desired
( "Desired number
number = %d\n",
%o\n", i ) ;
122
122 Exploring
Exploring C
C

)}
}}
}}

Sample
Sample, run

DssireJ
D03imj number == 1600
Desired
Desir8·j number == 1681
Desired
D8~irej number == 2500
Desired
Desird.j number == 3600
Desired number == 4900
Desired number == 6400
Desired number == 8100

Explanation
Etpfanation

Inside the for loop, first


first we get the square root of ii and test
whether iiis
is a perfect
perfect square
square oror not.
not. Ifit
If itisisaaperfect
perfectsquare,
square,then
then
we segregate the four digits of this number into variables variables dl,
d2,
dl, dJl and d4.
dJ and d4. Next
Next we
we construct
construct twotwo numbers
numbers "efland
nleft andBright
might
from
from the
the first
first two
two and
and thethe last
last two
two digits
digits of of the
the four
four digit
digit
number. Having done this, we test whether these two numbers numbers
are
arc perfect
perfect squares
squares or not. If they
or not. they turn
turn out
out to be perfect
to be perfect squares
squares
then
then we
we have
have met
met the
the number
number satisfying
satisfying our our requirements.
requirements.
Hence
Hence wewe print
print it out. Itis
it out. It is necessary
necessary to toinclude
includethe thefile
file "math.h"
"math.h"
for
for the
the sqrt( ) function
function to work.
to work.

(6)
(6) Program
Program

include
#include •math.h'
"math:h"
main()
main()
{{
int a, i, d1, d2, d3, d4, nurn ;
i n t a j , d1,d2,d3, d4, num,
for (i = 1100 ; i <= 9988 ; i++ )
for ( i = 1100 ; i < = 9 9 8 8 ; i + + )
Merry go
Merry go Round 123
123

{{
num=i;
num = i ;
d4 = num % % 10;
10;
num = num/10;
num/10;
d3== num% 10;
d3 10;
num = num/10;
num/10;
62
d2 = num
num %% 10;
10;
num num/10;
num = num/10;
d1 = nnum%
dl u m % 10;
10;

ifif(d1
(d1 ==== dd22 &&&& dd3
3 ===
= dd4
4 &&&
& dd1
1 !=
!=d3)
d3 )
{{
a=sqrt(i);
a = sqrt(i);
== aa** a)
if ( ij;:= a)
printf ( ·Desirednumber
printf ("Desired = %~n·, i ) ;
number = %d\n",
}}
}}
}}

Sample run
Sample run

Desired number = 7744


Desirednumber 7744

Explanation
Explanation

The smallest
The smallest 44 digit
digit number
number of of the
the form
form MBBAABB is is 1100,
1100,
whereas the
whereas the biggest
biggest 4
4 digit
digit number
number of of this
this form
form is is 9988.
9988. SoSo the
the
number desired
number desired by us lies
by us lies in
in the
the range
range 11001100 toto 9988. Hence
9988. Hence
these values
these values havehave been
been used
used asas the
the initial
initial and
and final
final values
values in in
the for
the for loop.
loop. Within
Within the
the loop, firstly the
loop, firstly the digits-of
digitsof ii are
are separated
separated
out into
out into dl,
d l , dl,
d2, d3
d3 and
and d4. If these
d4. If these digits
digits ar..e
are of
of the
the form
form MBB,
AABB,
then it
then it is
is tested
tested whether
whether ii is
is aa perfect
perfect square
square oror not.
not. If
If so, the
so, the
value of i is printed out, otherwise the control
value of i is printed out, otherwise the control loops back andloops back and
begins all
begins all over
over again,
again, this
this time
time forfor the
the next
next four
four digit number.
digit number.

l
4
A Multi-point
Multi-point Switch
N
N
control
ow
OW let's
the
let's switch over to switch.
the choice
choice we
selecting
we have
selecting between
control structure
have to
between two
structure called
switch. In serious C programming,
to make
make is
is more
more complicated
two alternatives.
called switch
alternatives. C
switch that
that allows
allows us
programming,
complicated than
C provides
us to
than merely
merely
provides aa special
to handle
handle such
special
such cases
cases
effectively.
effectively. The
The following
following figure
figure demonstrates
demonstrates its
its usage.
usage.

switch
swnch t(choice)
choice)
( s t a r t
) {{
case
case 1 ::
stat. 1 ;;
Yes break;
break;
3 stat. 1
case 2:
case 2:
stat. 2 ;;
break;
break;
Yes J case 3:
case 3:
% stat. 2 |—3 stat. 3;
3;
break;
break;
}
Yes
j stat. 3 | - 3

( s t
°P )

Figure 4.1 Operation switch


Operation of switch
A Multi-point Switch
Multi-pointSwitch 127
127

you would
As you would now
now agree,
agree, switch
switch is is impressive
impressive in
in style
style and
and elegant
elegant
in presentation. If you have even a flicker of doubt then try writing
in presentation. If you have even a flicker of doubt then try writing
the above
the above program
program using
using if
if -- else
else and we are
and we are sure at the
sure at the end
end you
you
would more
would than agree.
more than agree.

A few useful
A few useful tips
tips about
about the
the usage
usage of
of switch:
switch:

(a)
(a) The cases need
The cases need not
not necessarily be arranged
necessarily be arranged in
in ascending order,
ascending order,
1, 2,
1, 2, 33 and
and default.
default.

(b)
(b) Even
Even ifif there
there are
are multiple
multiple statements
statements to
to be
be executed
executed in each
in each
case, there
case, there is
is no
no need
need to to enclose
enclose them
them within
within aa pair
pair of braces
of braces
(( unlike
unlike if
if and
and else
else ).).

(c)
(c) The default
The default case
case is
is optional.
optional. If it is absent,
Ifitis absent, and
and no
no case matches
case matches
with the value
with the value of
of the
the expression,
expression, thenthen the
the program
program simply falls
simply falls
through
through the entire switch
the entire and continues
switch and continues with
with the next instruc-
the next instruc-
tion
tion (if any ) that
( if any) that follows
follows the
the control structure.
control structure.

(d)
(d) The limitation
The limitation of
of switch
switch is
is that
that the
the logical
logical operators
operators r.annot be
cannot be
used in cases.
used in cases. Thus,
Thus, aa case
case like,
like,

case ii <=
case 20:
<= 20:

is unacceptable.
is unacceptable. All
All that
that we
we can
can have
have after
after the
the case
case is
is an
an int
int or
or
aa char.
char. Even
Even aa float
float is
is not
not allowed.
allowed.

(e)
(e) In
In principle,
principle, aa switch
switch may
may occur
occur within
within another,
another, but
but in practice
in practice
it is
it is rarely
rarely done.
done.

goto

This keyword
This keyword is used when
is used when wewe want
want to to transfer
transfer the
the control
control to
to some
some
Point in the
point in the program
program which
which is
is not
not in
in the
the normal,
normal, step
step by
by step
step sequence
sequence
of the
°f the program.
program. ItIt takes
takes control
control from
from one
one place
place to
to another uncondi-
another uncondi-
128
128 Exploring C
Exploring

tionally, so
tionally, so aa different
different path
path for
for the
the execution
execution of
of the
the program
program is
is set up.
set up.
The following
The following program
program illustrates
illustrates the
the use
use of
of goto.
goto.

Useofofgato
I*Use
/* goto*/
*/
mainQ)
main(
{{
printf (("Hope
"Hope is hoping
hOping against hope...• );
hope...');
goto hope;
gotohope ;
printf (("even seems hopeless.'
"even if it seems hopeless.');
);

hope:
hope:
exit(O);
exH(O);
}}

On running this
On tunning this program, what would
program, what would show
show up
up is:
is:

Hope is hoping
hoping against
against hope...
hope ...

The second
The second part
part of
of the
the message
message will
will not
not get
get printed,
printed, asas due
due to
to the
the
goto, control
goto, control skips
skips to
to the
the label
label hope
hope and
and execution
execution is is terminated
terminated due
to the
to exit(O) present
the exit(O) present here.
here. Had
Had there
there been
been any
any executable statements
executable statements
after hope, those
after hope, those would
would have got executed.
have got executed.

Though goto
Though goto seems
seems to
to be
be handing
handing over
over to
to us
us aa magic
magic wand
wand for placing
control where
control where wewe please,
please, we
we would
would do do well
well to
to employ combinations
employ comomauons
of if, for, while and switch instead. This is because
ofif, for, while and switth instead. This is because goto makesgoto makes the
program less
program less readable
readable and hard to
and hard to debug.
debug. Besides,
Besides, once
once the controlj
the control'
is given
is given toto goto,
goto, there's
there's nono telling
telling how
how the
the program
program would behave
would hpt",v,t'!:_
as is
as illustrated in
is illustrated in the
the exercises
exercises that
that follow.
follow.
A
A Multi-point
Multi-point Switch
Switch 129
129

Exercise

[A]
[A] What will be the output of
of the following
following programs:

(1) main()
main()
{{
int i;
inti;
printf ("Enter
printf ( "Enter any 8IPf number");
number
I ) ;

scanf ((""%d",
scanf % d \ &&i) i ) ;;
switch (i)
switch ( i )
{{
case 1 :
easel:
printf ( "Do" ) ;
printf ("Do");
case
case 2 :
2:
printf ( "Re" ) ;
printf ("Re");
case 3 :
case 3 :
printf ( "Me" ) ;
printf ("Me"),
case defauR :
case default:
printf ('Fa So La Ti Do") ;
printf(*FaSol_aTiDo");
1}
}}

(2)
(2) main()
main()
{{
int ii ==3;
int 3;
swnch
switch (i)(i)
{
{
case 1 :
easel:
printf ( 'au revoir!' ) ;
printf ("au revoir!");
case 2 :
case 2 :
printf (("adieu!");
printf 'adieu" ) ;
break
break;
;
case 3 :
case 3 :
continue;
continue;
defauR:
default:
130
130 Exploring
Exploring C
C

printf ("plain
( "plain simple
simple goodbye!");
goodl7fe'" ) ;
}}
}}

(3) main()
main()
{{
char s =e a:
chars 3;
switch (s)
swnch (s)
{
{
case '1':
case T :
printf( "Seagherkins\n" ) ;
printf( "Seagherkins\n");
case '2':
case '2':
printf( "Baboons\n" ) ;
printf( "Baboons\n");
defauh:
default:
printf( "Bucaneers\n" ) ;
printf( "Bucaneers\n");
}
}
printf( "Gallows fodder" ) ;
printf("Gallowsfodder");
}}

(4) main()
main()
{{
int kk == -2,
int -2, jj == 44;;
swHch ( k 1= j 1 k )
switch ( k / = j / k )
{
{
defauh:
default:
printf ( "AII are same!\n" ) ;
printf ("All are same!\n");
case 0:
case 0:
printf ( "Happy birthday\n" ) ;
printf ("Happy birthday\n");
case 1 :
case 1:
printf ( "A punch on the mouth\n" ) ;
printf ("A punch on the mouth\n") ;
case 2:
case 2:
printf ( "A kick in the back\n') ;
printf ("A kick in the back\n");
}
}- .
}}

(5) main()
main()
AAMulti-point Switch
Multi-pointSwitch 131
131

{{
intj,
int j, xx== 00;;
for ((j j ==00; ;j j<=
for <=55; ;j++)
j++ )
{
{
sw~ch(j -1 )
switch
{ (j-1)
{ case 0 :
caseO:
case -1 :
case X+=
-1: 1;
xbreak
+ = 1 ;;
casebreak;
1:
ecase2:
asel:
case
case 23 ::
case x+=2;
3:
xbreak
+ = 2 ;;
break;
default :
default:
x+=3;
} x+=3;
}printf ( "%d", x) ;
} printf C % d " , x ) ;
}
}
}

(6)
(6) main()
{{
int i;
inti;
for ( i= 2 ; i<= 10 ; iH )
for ( i = 2 ; i <= 1 0 ; i++)
(
{
sw~ch(i)
switch
{ (i)
{ case 2 :
caseprintf
2 : ( "0" ) ;
printf ( " 0;" ) ;
continue
continue;
case 3 :
casebreak
3: ;
casebreak;
4:
case
case 54 ::
caseprintf
5 : ( "H" ) ;
printf ( " H " ) ;
132
132 Exploring
Exploring C
C

break;
break ;
default:
defauR:
printf
printf (( "'"
T )) ;;
}}
}}
}}

(7)
(7) main()
main()
{{
'E' ;
char ch == 'E';
charch
sw~ch (ch)
switch ( c h )
{{
ccase
a s e (( cchh >>== 6655 &&&& cchh <<== 990)
0 ) ::
printf ("Capital
printf ( "CapitalLetter")
Letter");;
break ;
break;
case (ch(ch >= >= 9797 &&&&ch ch <=<= 122)
1 2 2 ) ::
printf ("Small
printf ( "Smail case Letter") ;
catI Letter");
break
break; ;
ccase
a s e ( chc h >=
> = 4488 &&&& cchh <<== 557)
7 ) ::
printf (("Digit");
printf "Digit') ;
break
break; ;
defauR:
default:
printf ("Any
printf ( Any other
I other character*);
character" ) ;
}}
}}

(8)
(8) main()
main()
{
{
int i:
i;
for (( ii=
for = 11 ;; ii<= 5 ;; i++
<= 5 i++))
{
{
if (i * i>= 121)
if(i*i>=121)
gotothere;
goto there;
else
else
printf ("%d ", i) ;
printf("%d",i);
}}
there:
there:
A Multi-point Switch
Multi-pointSwitch 133
133

printf ("\nNo
( "\nNo more murphy's laws·
laws");
);
}}

(9)
(9) main()
main()
{
{
int i,i, jj ;;
int
for
f o r (j
( j == 11 ;;jj <=
< = 110;
0 ; jjff+ + ))
{
{
for ( i = 1 ; i <= 10 ; iff )
for ( i = 1 ; i < = 1 0 ; i + + )
{
{ if(j<10)
i f ( j <gotoout;
10)
} goto out;
}printt ( "Murphy's first law\n· ) ;
printf ("Murphy's first law\n");
printf (·Ifthe price of the PC is a dream...\n·) ;
printf ("If the price of the PC is a dream...\n");
printf ( "then the service would be a nightmare" ) ;
printf ( t h e n the service would be a nightmare");
}
}
out:
out:
printf ( ·Dream about
printf ("Dream about aa nightmare· );
nightmare");
}

(10)
(10) main()
main()
{{
int i, j, kk;;
for ( j = 11 ;;j <
<==44 ;; jj++
++)
{{
if(j*j==16)
if(j*j==16)
goto
goto secretplace
secretplace;;
}}
for ( i= 1 ; i <= 5 ; i++ )
for ( i = 1 ; i <= 5 ; i++)
{
{
k=i*i;
k = i*i;
j=k+2;
j=k+2;
secretplace::
secretplace
printf ("Murphy's
( ·Murphy's second law\n")
law\n");;
printf ("Good
(·Good computers are always
comJXJ!ersare priced...\n");
always priced...\n·) ;
714
134 Exploring C
Exploring

printf ("just
( 'just beyond your budget\n"
budget\n");
);
}}
}}

(11)
(11) include
'include "stdio.h"
"stdio.h"
i main()
main()
I
'!
{{
illt i;
inti;
I

II char
charj; j;

I
printf ( "Enter any
printf ("Enter number ..." ) ;
artf number...");
scanf ("%d",
scant ( "%d', &i)
& i ) ;;

~ switch (i)
sw~ch (i)
{{
ecase
a s e l1 ::
printf ("\nEnter
printf ( "\nEnter any alphabet ...") ;
artf alphabet...");
mush ( stdin)
fflush(stdin); ;
scanf (("%c",&j);
scant "%C", &j) ;

switch (j)
switch (j)
{{
case 'a' :
case'a':
printf ("\nlf
printf ( "\nlf you
you love
love something...");
something ...• ) ;
gotoout
goto out;;
case'b'
case'b': :
printf ("\nSet
printf ( "\nSet it~free...");
free ...• ) ;
break ;
break;
}}
break;
break;
case 22 ::
case
printf ("\nlf
printf ( "\nlf itit returns,
returns, its
its yours....");
yours ....• ) ;
}}
out:
out: .
printf ("\nElse it was never meant to be.");;
printf ( "\nElse it was never meant to be.')
}}

(12)
(12) main()
main()
A Multi-pointSwitch
A Multi-point Switch 135135

{
int i, k = 1 ;
int i, k = 1 ;
here:
here:
if(k>2)
if(k>2)
goto out;
goto out;
there:
there:
for ( i = 1 ; i <= 5 ; iH )
for ( i = 1 ; i <= 5 ; i++)
printf ( "%d", i ) ;
printf ("%d", i ) ;
k++ ;
k++ ;
goto there;
goto there;
out: ;
} out:;
}
(13) main()
(13) main()
{
{ int i = 1 ;
intswitch
i = 1 (i)
;
switch
{ ( i )
{ case 1 :
case 1goto : label;
goto label;
label:
caselabel:
2:
case printf
2: ( "He looks like a Saint .... ) ;
printf
break; ("He looks like a Saint...");
} break;
}printf ( "\nA Saint Bernard!" ) ;
printf ("\nA Saint Bernard!");
}
[BJ Attempt the following:
[B] Attempt the following:
(1) If a number 972 is entered through the keyboard, your program
(1) If a number 972 is entered through the keyboard, your program
should print "Nine
should print "Nine Seven
Seven Two".
Two". Write
Write the
the program
program such
such that
that
it does this for any positive integer.
it does this for any positive integer.
136
136 Exploring
Exploring C
C

(2)
(2) A positive integer is entered through the keyboard. Alongwith
itit the base of
of the numbering system in in which you want to
convert this number is entered. ,Write a program to display the
number
number entered,
entered, the base, and
the-base, and the
the converted
converted number.
number.

For
For example, if
'ifthe input is 64
64 2 then the output should be 64
2 1000000. Similarly, if the input is 64 16,16, then the output
should be 64
64 16 40.
1640.
A Multi-point
MUlti-poult Switch
Switch 137

Answers
Answers

Answers to [A]
Answers to [A]

(1)
(1) Output
Output

Error message: Expression


Errormessage: Expression syntax in function main

Explanation
Explanation

In aa switch,
In switch, the the default
default case
case must
must be specified simply
be specified simply as
as
ddefault,
e f a u l t , and not case default.
default. Hence the error.

(2)
(2) Output
Output

Error message:
message: Misplaced
Misplaced continue in function
function main

Explanation
Explanation

Observe case
Observe 3 . Our
case 3. Our program
program says,
says, if Case 33 is
if case is satisfied
satisfied then
then
loop back to
loop back the switch.
to the switch. And there lies
And there lies the continue
error, continue
the error.
cannot take the
cannot take the control
control back
back to switch. Unlike
to switch. break, continue
Unlike break, continue
can work
can work only
only with
with loops, never with
loops, never switch.
with switch.

(3)
(3) Output
Output

Bucaneers
Gallows fodder

Explanation
Explanation

To begin
To with, 33 is
begin with, is stored
stored inin the
the variable
variable s. In switch,
s. In switch, this
this 3 is
3 is
tested against ''1'1 ' and
and ''2'.
2 ' . Remember that 1 and and T
'1' are
are dif-
138
138 Exploring C
Exploring C

ferent. Whenever
Whenever we use' use ' 11',' , it is replaced by ascii value of 1
i.e. 49. Similarly '2'
' 2 ' is replaced by 50. Naturally,
Naturally, value of s
doesn't match with 49 or 50. Hence the control reaches the
doesn't
default clause of switch
default and prints 'Bucaneers'.
switch and·prints' Bucaneers'. Followed by
this the
this control reaches
the control reaches outside
outside switch, switch, where
where the second
the second
printf()) gets
printf( executed.
gets executed.

(4)
(4) Output
Output

mouth
A punch on the mouth
A kick
kick in the
the bar.k
back

Explanation
Explanation

Is an
Is an expression
expression allowed
allowed inin switch?
switch? Yes, provided the
Yes, provided the expres-
expres-
sion
sion involves only ints
involves only or chars.
ints or chars. Let
Let us
us see
see how
how k/=
k /= jj //k
k gets
gets
evaluated.
evaluated./ / has
has aa higher
higher priority
priority as
as compared
compared to·/=
to /= hence
hence is
is
evaluated
evaluated first. Thus the
first. Thus the expression
expression would
would become,
become,

k/=(4/-2)
k /= (4/-2)

Here, 44// --22 would


Here, would give
give -2.
-2. Thus
Thus the
the expression
expression reduces
reduces to:
to:

k/=-2
k/= -2

which evaluates
which to 1.
evaluates to 1.

Hence case
Hence case 11 in
in the
the switch
switch is satisfied and
is satisfied and the
the message
message 'A
punch
punch onon the mouth' is
the mouth' is printed.
printed. Since
Since there
there is
is no
no break
break in
in case
case
1 after the
the printf(),
printf(), the control
control just
just falls through till the end of
switch executes all statements
switch and executes statements that come in its path. In our
example printf
example printf ( "And
"And a kick
kick in the back"
back" ) falls in its path
and hence gets
and hence gets executed.
executed.

Note that in
Note that in the
the switch the very
switch the very first
first case
case is
is the
the default
default case.
case.
This is perfectly acceptable.
acceptable.
A Multi-point
Multi-point Switch
Switch 139
139

(5)
(5) Output
Output

x= 1
x=l
xx=2
=2
x=4
x=4
x=6
x=6
x=8
x=8
x == 11
11

Explanation
Explanation

The following
The following figure
figure shows
shows which
which case
case isis selected
selected and the
and the
corresponding value
corresponding value of
of xx outputted
outputted for
for jj varying
varying from
from 00 to
to 5.
5.
Note that
Note the absence
that the absence ofof break
break causes
causes the
the control
control toto simply
simply
fall through
fall through the
the subsequent
subsequent cases,
cases, until
until aa break
break or
or the
the end
end of
of
switch is encount-ered.
switch encountered. .

...
jj j l
j-l case satisfied
case sa~fied Value
Value of
of x outputted
x outputted

0
0 -1
-1 case -1
ease -1 11
11 0
0 case 00
case 22
22 11 case 11
case 44
33 22 case 22
ease 66
44 33 case 33
ease 88
55 44 default
default 11
11

Figure 4.2
Figure 4.2

(6) Output
Output

OHHII!!!
OHH!I!!!
140
140 Exploring C
Exploring C

Explanation
Explanation

The following figure lists out the values printed for each case.
ease.

....
ii case satisfied
case satisfied output
output

22 case 2 0
0
33 case 3 No value is
No value printed
is printed
44 case 44
case H
H
5S case 5
caseS H
H
66 default
default !!
77 default
default !!
88 default
default !!
9
9' default
default !!
10
10 default
default ! !

Figure 4.3
Figure 4.3

(7) Output
Output

Error message:
Error Constant expression
message: Constant expression required
required in main
in main

Explanation
Explanation

switch has
switch has not
not been
been made
made intelligent
intelligent enough
enough toto handle rela-
handle rela-
tional operators
tional while testing
operators while testing cases.
cases. After
After aa case
case there
there must
must
always be
always be aa constant
constant (( either
either integer
integer or
or character
character ),
), hence
hence the
the
error message.
error message.

(8)
(8) Output
Output

112345
2345
A Multi-point
Multi-point Switch
Switch 141
141

No more murphy's
murphy's laws

Explanation
Explanation

For no
For value of
no value of ii is
is the
the condition
condition (i (i •* ii >=
>= 121)
121) satisfied.
satisfied. Hence
Hence
on testing
on testing the
the condition,
condition, everyevery time
time the
the control
control reaches
reaches the
the else
else
block and
block and prints
prints the.
the current
current value
value of of i.i. Thus
Thus when
when the loop is
the loop is
getting executed,
getting executed, the the goto
goto statement doesn't get
statement doesn't get aa chance
chance to to
get executed,
get executed, andand hencehence the
the control
control doesn't
doesn't reach
reach the
the lable
lable
there.
there. However,
However, once once the
the control
control reaches
reaches outside
outside the loop after
the loop after
normal termination
normal termination of of the
the for,
for, it
it reaches
reaches there
there and
and hence
hence the
the
printf() prints the message about murphy's
printf() prints the message about murphy's laws. laws.

(9)
(9) Output
Output

Dream about a nightmare


nightmare

Explanation
Explanation

Can we
Can we abruptly
abruptly break out of
break out of the
the loop
loop using
using goto?
goto? Yes.
Yes. In fact
In fact
goto can
goto can take
take the
the control
control anywhere
anywhere in in the
the program.
program. Here,
Here, first
first
time through
time through the
the loop
loop itself
itself the
the condition
condition is is satisfied,
satisfied, and
and goto
goto
takes the
takes control directly
the control directly to
to the
the label
label eut,
out, where
where thethe printf(
printf())
gets executed.
gets executed.

(10) Output
(10) Output

Murphy's second law


Murphy's
computers are always priced...
Good computers
just beyond your budget

Explanation
Explanation
142
142 Exploring
Exploring C

Look at
Look at the
the first
first for
for loop.
loop. The
The momentj
moment j * jj equalsequals 16,
16, the
the goto
goto
statement is executed, which takes the control to secretplace
statement is executed, which takes the control to secretplace
inside the
inside second for
the second for loop.
loop. This
This is
is perfectly acceptable, goto
perfectly acceptable. goto
can virtually
can virtually take
take the
the control
control anywhere
anywhere -- even even deep
deep inside
inside aa for
for
loop. Having
loop. Having reached
reached the the secretplace,
secretplace, Murphy's
Murphy's second second law law
is printed
is printed outout and
and then
then thethe control
control reaches
reaches the the closing
closing brace
brace of of
the for
the for loop.
loop. AsAs aa result,
result, control
control jumps
jumps to to the
the beginning
beginning of loop
ofloop
i.e. to
i.e. to i++, which
which increments
increments ii and and then the condition
then the condition ii <= 55 is is
tested. Whether
tested. Whether the the condition
condition is is satisfied
satisfied or or not
not depends
depends uponupon
the garbage value
the garbage value that
that waswas picked
picked up
up for
for i.i. Why
Why garbage
garbage value?
value?
Because we
Because we entered
entered the the loop directly at
loop directly at secretplace
secretplace as as aa result
result
of which
of which ii = 11 couldn't
couldn't get get executed.
executed. Hence
Hence aa garbage value
garbage value
of ii is
of is assumed.
assumed. Thus Thus after
after printing
printing Murphy's
Murphy's law law once,
once, howhow
many more times it would get printed entirely
many more times it would get printed entirely depends upon depends upon
the garbage-value
the garbage-value that that has
has been
been picked
picked upup for for i.
i.

(11) Output
(11) Output

Enter any number ...11 <ENTER>


<ENTER>
Enter any alphabet ...aa
'if you love
'If something...
love·something ...
Else it was never meant to be.
be.

Explanation
Explanation

We can
We can useuse nested
nested switches.
switches. On On entering
entering number
number 11 andand al-
al-
phabet a,
phabet a, the
the case 'a' of
case 'a' of switch
switch (j (j )) is
is executed.
executed. The
The goto takes
goto takes
control out,
control to the
out, to the last
last printf(
printf(), and hence
), and hence the
the output.
output. Had
Had we
we
entered number 2, control would have reached
entered number 2, control would have reached case 2 of switch case 2 of switch
( i )),, printing
(i printing "If"If it
it returns
returns ...
...". Following this,
". Following this, the
the line
line "Else
"Else it
it
was ...
was ... "" would
would getget printed
printed this
this time
time also,
also, as
as out
out happens
happens to to
occur in
occur the normal
in the normal course
course of
of execution
execution of of the program.
the program.

Puzzled about
Puzzled about the weighty looking
the weighty looking ## include
include and
and mush(
fflush( ))
statements? The
statements? file "stdio.h"
The file "stdio.h" is
is required
required for
for the
the function
function
fflush( )) to
mush( to work.
work. This
This function
function empties
empties the
the keyboard
keyboard buffer
buffer
r A Multi-point
Multi-point Switch
Switch 143

before the
before the alphabet
alphabet entered
entered byby us
us is
is scanned.
scanned. The
The reason
reason forfor
this is
this is that
that when
when scanf()
scanf() isis used
used for
for reading
reading-anan int, it
it collects
collects
everything till
everything till the
the the
the enter
enter key
key is
is hit
hit as
as the
the value
value ofof the
the int,
and leaves
and leaves the
the enter key itself
enter key itself unread.
unread. When
When aa char
char is to be
is to be
scanned next,
scanned next, the
the scanf()
scanf( ) accepts
accepts the
the enter
enter key
key as
as the character
the character
entered, which
entered, which certainly
certainly won't
won't do
do if we were
if we were to
to exercise
exercise ourour
choice in
choice in the
the switch()'.
switch()~ The fflush() ensures
The mush() ensures that
that the
the Enter key
Enter key
pending in
pending in the keyboard buffer
the keyboard buffer is
is flushed
flushed out
out before
before thethe al-
al-
phabet entered
phabet entered by by us
us is
is scanned.
scanned.

(12) Output
(12) Output

12345123451234512345
12345123451234512345 .....

Explanation
Explanation

Here's an
Here's an example
example of of how
how thethe goto statement
statement can can capture more
ca pture more
control than
control than we would like
we would like it
it to.
to. Though
Though we we have
have not
not said
said goto
here,
here, it it is
is executed
executed anyway,
anyway, sincesince it it lies
lies in
in the
the normal execu-
normal execu-
tion path.
tion path. To To begin with kk iiss 1,
begin with 1, i.e.
i.e. less
less than
than 2. 2. Hence
Hence control
control
skips the
skips the if if and
and reaches
reaches thethe next
next statement
statement in in line,
line, which
which is the
is the
label there.
label there. In In the
the for
for loop,
loop, 1,2,3,4
1,2,3,4 andand 5 get printed,
5 get printed, and then
and then
kk is
is incremented
incremented to to 2.
2. The
The following
following goto goto statement
statement takes
takes thethe
control 'back
control back up up toto there,
there, and and once
once again
again the the for
for loop
loop is is
executed. Next,
executed. Next, kisk is incremented
incremented to to 3,
3, again
again control
control isis taken
taken toto
there
there and and so so on.
on. Thus,
Thus, the for loop
the for loop is is executed indefinitely,
executed indefinitely,
irrespective of
irrespective of the
the fact
fact that
that kk is
is no
no longer
longer lessless than
than 2.
2. The
The ifif
condition can
condition can exercise
exercise no no control
control nownow thatthat the
the goto
goto has
has taken
taken
over.
over.

(13) Output
(13) Output

He looks
He looks like
like aa Saint
Saint...
...
A Saint
A Saint Bernard!
Bernard!

l
144 Exploring C

Explanation
Explanation

Since ii is 11,, case 1 is executed, which takes control to label.


label.
Once the control is here, contrary to what one might expect,
Ishere,
case 2 gets executed, as is clear from from the output. Legally
speaking, case 2 should have got executed only for value of ii
speaking,
equal to 22.. But goto
goto overrules this, and whatever follows goto,
goto,
is taken as the law. You'll
You'Il agree that goto
goto would rather be used
sparingly,
sparingly, as it it seems to have a mind of its own!

Solutions to [B]

(1)
(1) Program
Program

main()
main( )
{{
unsigned int
unsigned int num,
nurn, num2,
num2, no_dig
no_dig == 0,
0, p-;
p:
int i;
int i;

printf ("\nEnter
( "\nEnter any
any positive
posnive integer");
integer" ) ;
scanf ("%d",
( "%d", &num);
&nurn ) ;

num2
nurn2 == num;
num;

do
{{
no_digH;
no_dig++;
nurn2 == nurn2/10;
num2 num2/10;
}} while
while (num2
( nurn2 !=
!= 0)
0 ) ;;

for (; no_dig
no_dig>> 00;; no_dig-,
nO_dig--,nurn num %= %= p)
{{
p == 11 ;;
., P
for ((ii == no_dig
no_dig -- 11; ; i >> 00;; i--
i- )
Pp=p*10;
= P*10;
A Multi-point
Multi-point Switch
Switch 145

switch ( nurn /I pp))


swttch (num
{{
case 00 ::
case
printl (( "·ZERO
printf Z E R O"")) ;;
break;
break;
case
case 11 ::
printf (( ""ONE"
printf O N E " )) ;;
break;
break;
case 22 ::
case
printf ( "1WO • ) ;
printf("TWO");
break;
break;
case
case 33::
printf (( ""THREE
printf T H R E E •" )) ;;
break;
break;
case
case 4:4:
printf (( ""FOUR"
printf F O U R " ));;
break;
break;
caseS:
case 5 :
printf ((""FIVE
printf FIVE"); II ) ;

break;
break;
case 66::
case
printf ((""SIX
printf S I X "• )); ;
break;
break ;
case7:
case 7:
printf ( ·SEVEN
printf ("SEVEN"); II ) ;

break;
break;
case 88::
case
printf ("EIGHT");
printf ( "EIGHT II ) ;

break;
break;
case99: :
case
printf ("NINE");
printf ("NINE n) ;
break;
break;
}}
- }
}
}
}
146
146 Exploring C
Exploring C

Sample run
Sample run

Enter any positive integer 972


NINE SEVEN
NINE TWO
SEVEN lWO

Explanation
Explanation

The number
The number isis accepted
accepted from
from the
the keyboard
keyboard andand stored
stored in num.
in Dum.
Using
Using aa do-while,
do-while, the the number
number of of digits
digits in
in the
the number
number are are
counted,
counted, which
which isis stored
stored in no_dig. In
in no_dig. In the
the for loop, each
for loop, each digit
digit
of
of the
the number
number is is separated
separated by by dividing
dividing by by an appropriate
an appropriate
multiple
multiple of
of 10
10 and
and assigning
assigning the
the remainder
remainder to to num
Dum itself. Then
itself. Then
depending on
depending on what
what the
the number
number is,is, the
the switch
switeh causes
causes the same
the same
to be printed
to be printed in
in words.
words.

(2)
(2) Program
Program

main())
main(
{ •
num, nurn2,
unsigned int nurn, num2, no_dig = 0,
0, p, base;
base;
inti;
int i;

printf ("\nEnter
( "\nEnter any positive integer & base
base");
•) ;
scant ("%d %d", &num, &base);;
&nurn, &base)
printf ( ""\n%d
\ n % d%d
% d'.n nurn,
u m , base)
base);;

nurn2== nurn;
num2 num;

do
{{
no_dig++ ;
no_dig++;
•, nurn2
num2 = nurn2!
num2 / base;
base;
} while ((num2
nurn2 != 0)
0);

for (; nodig
no_dig>> 00;; no_dig--,
nodig--, num p)
nurn %= p)
A Multi-point
Multi-point Switch
Switch 147
147

{{
p == 1i ;;
for ( ii = no_dig
for no_dig - 11; ; i > 0
0 ;; i--i-))
p=p*base;
p = p*base;

( base ==
ifif (base = = 16
1 6 ))
printf (("%X",
printf n u mI /pp)) ;
"%X", nurn
else
else
printf (("%d",
printf n u mI /pp)) ;;
"%d", nurn
}}
}}

Sample run
Sample run

Enter any
Enter any positive
positive integer
integer and
and base
base 64 2
64 21000000
6421000000

Explanation
Explanation

The program
The program uses uses the the concept
concept of of successive
successive divisions
divisions of the
of the
number by
number by the
the base
base of of the
the numbering
numbering system
system in in which
which it it is to
is to
be outputted. Assume that we want to convert 64 to its binary
be outputted. Assume that we want to convert 64 to its binary
equivalent. Therefore,
equivalent. Therefore, when when 64 64 is
is entered,
entered, first
first the
the number
number of of
digits that
digits that the binary equivalent
the binary equivalent of of 64 would have
64 would have are deter-
are deter-
mined
mined using
using the
the do-while.
do-while. 64 64 can
can be
be divided
divided by by 2 2 aa maximum
maximum
of 77 times,
of times, till
till aa 00 is
is obtained.
obtained. Thus,
Thus, Do_dig
no_dig in in this
this case
case turns
turns
out to
out to be
be 7.
7. The
The first time through
first time the inner
through the for loop,
inner for loop, ii isis 6.
6.
Once outside
Once outside thethe for
for loop,
loop, pp would
would bebe 64,
64, and
and num
Dum getsgets divided
divided
by 64,
by 64, and
and hence
hence 1 isprinted
1 is printed out.
out. Now
Now thethe control
control reaches
reaches Dum num
%= p,
%= where Dum
p, where num is is set
set to
to 00 since
since both
both num
Dum and and p are 64.
pare 64.
Next time
Next time through
through the the loop
loop pp turns
turns out
out toto be
be 32,
32, and
and Dum
num // p, p,
i.e. 00 gets
i.e. gets printed.
printed. This This process
process continues
continues till
till all
all the
the digits
digits ofof
the binary equivalent
thebinary equivalent of of 64
64 have
have been printed.
been printed.
148
148 Exploring
Exploring C

Note that if the base of the numbering system is 16, then the
format specification %X is used to print hexadecimal digits.
digits.
5
Functioning
Functioning

with Functions
with Functions
A
C program,
program, except
except for the
the simplest
simplest one,
one, cannot
cannot handle
handle all

A
provide
the tasks

provide the
tasks by itself.
entities
the mechanism
itself. Instead,
entities - 'functions'
mechanism for
Instead, it requests

for producing
producing programs
programs that
other program-like
requests other
'functions' - to get its tasks
tasks done.
program-like
Functions
done. Functions
that are
are easy
easy to
to write,
write,
read,
read, understand,
understand, debug,
debug, modify
modify and
and maintain.
maintain.

A
A function
function is
is aa self-contained
self-contained block
block of
of code
code that
that performs
performs aa coherent
coherent
task
task of
of some
some kind.
kind. Every
Every CC program
program is is aa collection
collection of
of these functions.
these functions.
Following
Following figure
figure shows
shows functions
functions in
in action.
action.

main()
main{) ,
{ message{)
{ I
message();; brings
brings the
the
printf
printf ("Study hard!");
( "Study hard !" ) ; control here
control here
} «

returns the
'returns the
message()
message() *+-. ---------' control
control back
back
{{
printf ("Don't
printf ( "Don't let
let sleep
sleep be
be the
the weak
weaklink .." ) ;
link..");
}
}
Notes
Notes

-- A
A function
function gets
gets called
called if
if the
the function
function name
name is
is followed
followed byby aa semicolon.
semicolon.
-- A
A function
function gets
gets defined
defined ifif the
the function
function name
name isis not
not followed
followed by by aa semi-
semi-
colon.
colun.
7
igure 5.1
Figure 5.1 Calling
Calling and
and defining functions
defining functions
r
1
Functioning Functions
Functio,ning with Functions 151

Let's now
Let's assimilate aa few
now assimilate few facts
facts about
about functions
functions and
and lay
lay them
them out
out
neat and
neat and clear.
clear.

(a)
(a) Functions can
Functions can be
be either
either library
library functions
functions or
or user-defined func-
user-defined func-
tions. For example,
tions. For example, printf(),
printf( ), scanf()
seanf( ) are
are library functions
library functions
whereas message( )) is
whereas message( is aa user-defined
user-defined function.
function.

Library functions
Library functions come
come alongwith
alongwith the
the compiler
compiler and
and are
are present
present
on the
on the disk.
disk. The
The procedure
procedure of
of calling
calling both types of
both types of functions
functions
is exactly
is exactly same.
same.

(b)
(b) There can
There can be
be any
any number
number of
of functions
functions in
in aa program
program and any
and any
function can
function can call
call any
any other
other function
function any
any number
number of times.
of times.
However, program execution
However, program execution always
always begins
begins with
with maine
main().
).

(c)
(c) The order
The order in
in which
which the
the functions
functions get
get called
called and
and the
the order
order in
in
which they are
which they are defined
defined in
in aa program
program need not necessarily
need not necessarily be
be
same.
same.

(d) .' The


(d) The use
use of
of user-defined
user-defined functions
functions allows
allows aa large
large program
program toto be
be
broken down
broken down into
into aa number
number of of smaller
smaller self-contained
self-contained com-com-
ponents, each
ponents, each of of which
which has has aa definite
definite purpose.
purpose. There
There areare
several advantages
several advantages to to this
this breaking
breaking upup of
of program
program into func-
into func-
tions. For
tions. For one,
one, writing
writing functions
functions avoids
avoids rewriting
rewriting thethe same
same
code over
code over and
and over. For another,
over. For another, breaking
breaking down
down ofof logic
logic into
into
separate functions
separate functions makes
makes thethe entire
entire process
process ofof program writing
program writing
and debugging
and debugging easier.
easier.

Communication between Functions


Communication between Functions

Not only
Not only can
can one
one function
function call
call another,
another, if
if needed
needed we
we can
can pcss
pr.ss values
values
to and
to and fro
fro between
between functions.
functions. Foll
Following figure shows
owing figure shows this
this mechanism
mechanism
of passing
of passing and
and returning
returning values
values between functions.
between functions.
152
152 Exploring
Exploring C
C

main()
main()
{
int
int a,
a, b, c, sum;
sum ;
printf ("Enter
printf ( "Enter any
any three
three numbers");
numbers • ) ;
scant ("%d%d%d",&a,&b,
scanf ("%d %d %d", &a, &b, &&c)
c ) ;;

r sum
sum == calsum
calsum (a, b,c);
~Lb-=,C_)_;
l—i—i ----"
I . printf
printf ("Sum
( ·Sum = = %d", sum);;
%d", sum) values of
values of a,
a, b,
b, cc get
get
this
this }} , passed
passed to
to x,
x, y, zz
value
value is .rh
.—| —, -. ,
returned
returned calsum
calsum (x, (X, y, zz))
and
and col-col- iint x y z :
n t x y z ;
lected
.inlected {r '"
1

in sum •ints;
„.
x
sum int s; t

s=x+y+z;
l
L_l____
J I
~tu~n+{~
return ( s+) ;z ;
J);
Figure
Figure 5.2
5.2 Passing
Passing values
values between functions.
between functions.

Note
Note the
the following
following points carefully.
points carefully.

(a)
(a) There
There is
is no
no restricti
restrictionon on
on the
the number
number ofof return
return statements
statements that
that
may
may be
be present
present inin aa function.
function. Also,
Also, the
the return
return statement
statement need
need
not
not always
always bebe present
present at at the
the end
end of
of the
the called function.
called function.

(b)
(b) Any
Any C C function
function by by default
default returns
returns an an int value.' More specifi-
value: More specifi-
cally,
cally, whenever
whenever aa call call is
is made
made to to aa function,
function, the compiler
the compiler
assumes
assumes thatthat this
this function
function would
would return
return aa value
value of
of the
the type
type int.
If
If we
we desire
desire that
that aa function
function should
should return
return aa non-integer
non-integer value,
value,
then it is necessary to explicitly mention so in the calling
then it is necessary to explicitly mention so in the calling
function
function as as well
well asas called
called function.
function. This
This is
is shown
shown in in the
the
following figure.
following figure.
Functioning
Functioning with
withFunctions
Functions 153
153

main()
main() main()
main() main()
main()
{ { {
int
int a,
a, b,b,c,
c, p;
P; float
float a,a, b, c, p;
b,c, P; float
float a,a, b,
b,c;
C;
float
float prod();
prod() ; void pradO ;
votdprod();
aa=b=c=5;
=b=c=5; aa== bb=c=
= c = 1.5;
1.5;
pP1rod
= p r o d(a,
( a ,b,
b ,c);
c); pp=prod(a,b,c);
= prod(a,b,c); aa=
= bb=c=
= c = 1.5;1.5;
printf
pri C('p p ==% d " , p)
%d', p ) ;; printf
printf ("p
('p == % f , pp).;
%r, ); pprod
r o d(( a,
a , bb,c);
,c);
}
} }
} }

prod(x,y,z)
P':od (x, y, z) float
float prod
prod ((x,y,
x , y , zz)) void
void prod
prod (x,y,z)
(x, y, z)
IntX,y,
int x, y, z;
z; float
float xX,, y,
y , z ;; .float X, y, z ;
float x,y,z;
{{ { .{
intp;
intp; float
float p; float
bp; p;
pP=X*l*z;
=x*y*z; pP=X*l*z;
=x*y*z; pP:,x*f
= x *zy; * z ; .
return ( pp);) ;
return return ( pp);) ;
return pprinlf
r i n t (f ( p' p==%r,
% f , pp),
);
} }} }

Notes
Notes Notes
Notes Notes
Notes

-- An int value
value is
is being
being -- A
A float
float value
value is
is being
being -- No value is
No value isbeing
being
returned
returned by
by function
function returned
returned by by function
function returned
returned byby function
fuoctioo
prod().
prodO· prod().
pradO. prod().
prodO·
-- No special provision isis -- For
special provision Forreturning
returning a htfloat -- To
To ensure that DO
ensure that no
to
to be made for
be made for return-
return- value
value the
the declaration
declaration value
value is
is returned, void
returned. void
ing
ing an
an int
int value.
value. in
in main()
maio( ) asas well as
well as declaration
declaratioo isis made
made inin
while
while defining
defining the
the main(
main()) and
and while
wbile
function
function isis necessary.
necessary. defining
defining the
the function.
function.

Figure
Figure 5.3 Returning
Returning int,
int, float
Ooat and void
void

Pointers
POinters

Functions
Functions can be called
called either
either by value
value or by reference.
reference. We
We have
have so
far used
used a call by value.
value. To be able
able to understand
understand a call by reference
reference
it is necessary
necessary toto first understand
understand the concept
concept of pointers.
pointers. Pointers
Pointers is
°ne
one concept
concept which
which beginners
beginners find hard
hard to digest.
digest. But once
once pointers
pointers
e mastered
a r
are mastered there
there are many
many tricks
tricks that one
one can
can perform.
perform. Let's
Lees meet
meet
the concept
concept head
head on.on. Look
Look at the
the following
following program.
program. It says
says it all.
all.

main()
main()
154
154 Exploring
Exploring C
C

{
int i == 30;
int 30;
int*j,**k;
int *j, **I< ;
j = &i;
&i; /*1* store
store address
address of
of ii in
in jj */
k = &j; storeaddress
1* store
&j ; I* addressofofj jininkk*/*/
printf ( HAddress of i == %d
pri"" ("Address %d %d%d %d\n",
%d\n", &i, j,j, *k)
* k ) ;;
printf
printf ("Address
( •Address of j = %d%d %d\n",
%d\n", &j, k ) ;;
&j, k)
printf ( "Address of k = %d\n",
printf ("Address %d\n", &k) & k ) ;;
printf
primf ("Value
(·Value of i = %d
%d %d
%d %d %d %d",%d', i,i, *(&i), *j, **k);
*j, **k);
}

And
And here
here is
is the
the output...
output...

Address of i == 6484 6484 6484


Address of j =9006
= 9006 9006
Address of k = 9888
Value
Value of ii == 30
30 30
30 30
30 30

Consider
Consider the declaration,
the declaration,

int i = 30;
30;

This
This declaration
declaration reserves
reserves space
space inin memory,
memory, associates
associates the
the name
name iiwith
with
it
it and
and stores
stores the
the value
value 30
30 in
in it. The following
it. The following figure gives the
figure gives the snapshot
snapshot
of
of this reserved space.
this reserved space.

j kk
I 30 1
30-] 6484 9006
6484 9006
9006 9888
integer variable pointer
pointer to
to an
an pointer
pointer to
to an
an
integer
integer variable
variable integer
integer pointer
pointer

Figure
Figure 5.4 Pointers
5.4 Pointers
Functioning withFunctions
Functioning with Functions 155
155

We see
We see that
that the
the compiler
compiler has has selected
selected location
location number
number (( address)
address )
6484 as
6484 as the
the place
place toto store
store the
the value
value 30.
30. The
The location
location 6484
6484 we
we took
took
only for example, the compilermay choose any otherlocation aswell.
onl y for exam pie, the com pilermay choose any otherlocation as well.
The important
The important point
point is,
is, j's
i's address
address inin memory
memory is is aa number.
number.

Next, the
Next, address of
the address of ii is
is stored
stored inj
in j through
through the the statementj =
statement j = &i. &i. Since
Since
jj contains
contains the the address
address of of ii(( an
an integer
integer variable
variable ), ), jj is
is called
called an integer
an integer
pointer. Similarl
pointer. Similarly, y, the address ofj
the address ofj isis stored
stored in in kk through
through the the statement
statement
=
kk = &j.
&j. Since
Since kk contains
contains the the address
address of of jj (( an
an integer
integer pointer
pointer ),), kk is
is
called aa pointer
called pointer to to an
an integer
integer pointer.
pointer. Here
Here & & is
is 'address
'address of'of operator.
operator.
Since j and
Sincej and k k contain
contain addresses
addresses their
their declaration
declaration is is different
different from
from that
that
of i.
of i. In
In the
the declaration
declaration of of jj and
and k,k, ** is
is being
being used.used. This
This isis aa pointer
pointer
operator called
operator called 'value
'value at at address'.
address'. Thus
Thus the the declaration
declaration int int *j means
*j means
the value
the value at at address
address contained
contained in in jj is
is an
an int.
into OrOr inin other
other words
words jj is is an
an
integer
integer pointer. Similarly, the declaration int **k means the value at
pointei. Similarly, the declaration int **k means the value at
address contained
address contained in in *k*k isis an
an int.
into Once
Once. this
this concept
concept is is clear,
clear, rest
rest of
of
the program
the program is is aa breeze.
breeze. Figure
Figure 5.4 5.4 would
would help help youyou check
check the output
the output
as you step through the
as you step through the program. program.

Pointers throw
Pointers throw open
open the
the gates of programmers'
gates of programmers' imagination.
imagination. Can Can you
you
imagine aa pointer
imagine pointer toto aa pointer's
pointer's pointer?
pointer? A A three
three star phenomenon.
star phenomenon.
Or how
Or how about
about aa pointer
pointer toto aa pointer's
pointer's pointer's
pointer's pointer?
pointer? There
There isis no
no
limit on
limit on how
how farfar can
can we
we stretch
stretch this
this definition.
definition. Possibly,
Possibly, till
till the
the point
point
we can
we comprehend it.
can comprehend it. And
And that
that point
point of
of comprehension
comprehension is-usually
is-usually aa
pointer
pointer to a pointer. Beyond this one rarely requires to extend
to a pointer. Beyond this one rarely requires to extend the
the
definition of
definition of aa pointer.
pointer.

Back to Function
Back Function calls

Having had aa tryst


HaVing had tryst with
with the
the pointers
pointers now
now let
let us
us get
get back
back toto where
where we
we
had left off - the function calls. Functions can be called in two ways:
h~d left off - the function calls. Functions can be called in two ways:
eIther by
either by passing
passing values
values ofof arguments
arguments or or by
by passing
passing addresses
addresses ofof
arguments. The former
~rguments. The former is is called
called aa 'Call
'Call by
by Value'
Value' and
and thelatter
the latter aa
Call by Reference'.. These
Call b.yReference' These calls
calls are
are illustrated
illustrated in-the
in the following
following figure.
figure.
156 Exploring C

/* Callby
1* Call byvalue
value*/*/ /* Call
/* byreference
Callby reference*/*/
main()
main() main()
main()
{ { . .

* inta=
j n t a = 110,
0 , bb=20;
= 20; * inta=10,b=20;
inta=10,b = 2 0 ;

s~ia,b);
wapv(a,b); I swapr(&a,&b);
swapr ( &a, &b) ;
pnntf( ( aa=%db=%d\n,iltb);
printf i
= % d b = % d W , a, b ) ; printf ("aa = %d
printf( ,
% dbb =%d\n",
= % d \ n ,a,a ,b)
,
b ) ;;,
} }
swapv(x,y)
swapv (x, y) swapr(x,y)
swapr (x, y)
jntx,y;
intx,y; int*x,*y;
int*x, ~;
{ {{
irrtt;
intt; intt;
int t ;
t=x;
t=x; tt =*x;
=*x;
x=y;
x=y; *x = * y ;
*x=*y;
y=t;
y=t; ~=t;
*y=t;
^ printf ("x = %d Y == %d\n",
printf('x=%dy , x y)
% d \ n X, , y ) ;;
, printf
printf (("*x
"*x =
= %d *y == %d\n",*x,
%d*y %d\n", *x, *y)
* y ) ;;
} - }
}
Output Output

xx=20y=
= 2 0 y = 110
0 . *x = 2 0 * y = 1100
*x=20*y=
aa== 110b=20
0 b = 20 aa=20b=10
= 20b=10
Notes
Notes Notes
Notes

-- Changes
Changes made andyyinin
madeininxxand -- Changes
Changes made
madeininswapr()
swapr()using
using
swapv( ) are
swapv() are not
not reflected
reflected back
back xx and
and yy are
are reflected
reflected back
back in
in aa
in aa and
in and b.
b. and b.
andb.

Figure 5.5 Call by value and call by reference


reference

Recursion
Recursion

When some statement


statement in a function calls the same function it is in,
we say that recursion
recursion has occurred.
occurred. Such a function is called a
recursive function. Taking
recursive Taking the example
example of calculating
calculating the factorial of
a number,
number, let us see the working
working of a recursive
recursive function.
function.
Functioning with Functions
Functioning with Functions 157

main()
{{
int a, fact;
fact;

printf ("Enter
( "Enter any number"
number");
);
scant (("%d",&a);
scanf "%d", &a) ;

fact = rec ( a ) ;
fact=rec(a);
printf ("Factorial
( "Factorial value = %d", fact);;
%d", fact)
}}
rrec
e c (x)
(x)
intx;
int x;
{{
int f;f;

if (x
( x ==
== 1 )
return ( 1 ) ;;
else
f=x*rec(x-1) ;
f = x * rec ( x - 1 ) ;
return (f) ;
} return ( f ) ;
}
Assume that
Assume that the number entered
the number entered is
is 3.
3. Using
Using Figure
Figure 5.6,
5.6, we
we try
try to
to
visualise what
visualise what exactly
exactly happens
happens when
when thethe recursive
recursive function rec())
function rete
gets called.
gets called.

Go through
Go through the the figure
figure carefully.
carefully. The
The first time when
first time when rec(rec()) is
is called
called
from main(),
from main(), xx collects
collects 3.
3. From
From here,
here, since
since xx is
is not
not equal
equal to to 1,
1, the
the ifif
block is skipped and rec() is called again with argument
block is skipped and rec() is called again with argument ( x-I ), i.e. (x - 1 ) , i.e.
2. This
2. This isis aa recursive
recursive call.
call. Since
Since xx is
is still
still not
not equal
equal to to 1,
1, rec()
rec() isis called
called
yet another
yet another time,
time, with
with argument
argument (( 22 -- 11-).
) . This time as
This time as xx is
is 1,
1, control
control
goes back
goes back to to the
the previous
previous rec(
rec( )) with the value
with the value 1, 1, and
and ff is
is evaluated
evaluated
as 2. Similarly, each rec() evaluates its f from the
as 2. Similarly, each rec( ) evaluates its f from the returned value, returned value,

l and finally
and
better
finally 66 is
better by
is returned
by following
executing the
returned to
following the the arrows
program
main(). The
to main().
arrows in
there do
The sequence
in Figure
Figure 5.6.
not
sequence would
Let it
5.6. Let
exist so
execu.ing the program there do no. exist so many copies of the
would be
it be
be clear
many
be grasped
clear that
copies
grasped
while
that while
of the
158 Exploring C

function rec().
rec(). These
These have been shown in the figure just to help you
keep track of how the control flows during
during successive
successive recursive
recursive calls.
calls.

frommain()
from main()
!
rec ( x )
rec(x) rec(x)
rec(~) rec ( x )
rec(~)
intx;
intx; intx;
intx; intx;
intx;
{{ {{ {{
intf;
irttf; intf;
intf; intf ;
intf;

iwf (x

else
else
( x ==== 11))
return ( 11))

ff=x*rec(x-1);
= x*rec(x-1);
ff(x==n
w ( x == 1 )

else
else
return GY
return (( 11 )) ;;
-f=x*rec(x-1);
Wff(x==1)
(x == 1 )
— return
else
else
return (( 11 )) ;;

f=x*rec(x-1);

} return
}
(f);-
retum (:); II }
f = x*rec(x^-1);
return (f) ;
I
return ( f ) ; }
f = x*rec(x-1);
return (f) ;
return ( f ) ;

to main()
to main()

Figure 5.6
Figure 5.6 Recursion
Recursion at work
at work

Whatever a recursive
recursive program can do, a for, while,
while, or do-while
do-while can
do just
just as well.
well. So don't
don't feel daunted
daunted if you don't
don't feel at home with
with
recursion, as we can easily get by without it.
recursion, as we can easily get by without it.
Functioning with
Functioning Functions
withFunctions 159
159

Exercise
Exercise

[A] What will be


What will be the
the output
output of
of the
the following programs:
following programs:

(1)
(1) main() .
main().
{{
=
int i = 45;
45;
float
float c;
c;
c=check(i);
c = check ( i ) ;
=
printf (("c
'c = %f,
% f , c)
c) ;
}}
check
check ((ch)
ch)
int ch;
int ch;
{{
ch
ch >= 45 ? return
>= 45? (3.14):: return
return (3.14) return (6.28)
(6.28);;
}}

(2)
(2) main()
{{
int
int area;
area;
float radius == 2.0;
float radius 2.0;
area == areacircle
areacircle ((radius);
radius) ;
printf (("area
"area == %f, %f, area)
area) ;
}}
areacircle ( r )
areacircle
float rr;;
float
{{
a;
float a;
3 . 1 4* *rr**rr ;
a == 3.14
"a = %1\n·,a)
printf (("a %An", a ) ;;
return ((a)a) ;
}}
160
160 ExploringCC
Exploring

(3)
(3) main()
main()
{ {
int cc;;
int
printf ("c
printf ( "C before
beforecall
call ==%d\n",
%d\n",cc)) ;;
c = message()
c = message(); ;
printf I( "c
printf after call
"C after call == %d\n",
%<1\n",cc )) ;;
}}
message()
messageQ
{
{
printf ( "Live and let live\n" ) ;
printf ("Live and let live\n");
}}

(4)
(4) main()
{{
co
C()
{{
cO
c()
{{
printf ( "C is a C...\n") ;
printf("CisaC...\n");
}
}
printf
printf (("..isac...\n");
"..is a c...\n") ;
}}
printf ("..is
printf ( "..is a sea
sea afterall!");
afteralll") ;
}}

(5) main()
{{
int ii == 33, k,
int (
k, I;
I;
kk == add
add (( +++i + i )) ;;
l=add(iH);
I = add (i++);
printf ("i( "i = %dk
%d k = %d I ==%d",
%d", i;i;k,k I), l ); ;
}}
add(ii)
add(ii)
int ii;
int ii; •<
{
{
++ii;
Hii;
Functioning
Functioning with
with Functions
Functions 161

return (ii);
return (ii)
}}

((6)
6) main()
{{
int ii== 135,
int 135, aa == 135,
135, k;k;
kk == function
function (!++i,
( !tti, !att
! a + +)) ;;
printf ("i = %d a = %d kk == %<f,
printf ("i = %d a = %d %d", i,i, a,
a, k)
k ) ;;
}}
function
function (j, (i, bb))
intj,b;
inti, b;
{{
int c;
intc;
cc=i
= j + b; b;
return ( c ) ;;
return (c)
}}

. (7)
(7) main()
{{
int kk ==35,
int 35, z;
z;
k = func1 (k
k = fund ( k = func1 =
func1 ((kk = fund =
func1 (k)
( k ) )) )) ;;
printf ("k = %d", k)
printf ("k = % d " , k ) ;;
}}
func1 (k)
fund (k)
intk;
int k;
{{
k++;
ktt ;
return
return ((k)
k ) ;;
}}

(8)
(8) main()
main()
{{
int kk == 35,
int 35, zz;;
z=func(k);
z = func ( k ) ;
printf("z
printf =
(·z = %%d",
d " ,z)
z ) ;;
}
162 Exploring C

tunc (m)
func (m)
intm;
int m;
{{
++m;
return
return (( m
m = fund
func1 (( ++m
+ + m)))) ;;
}}
func1
fund (m) (m)
intm;
int m ;
{{
m++;
m++;
return
return (( m)
m ) ;;
}}

(9)
(9) main()
main()
{{
void
void message(
message(); );
int c;
intc;
printf
printf (("c
"c before call == %d\n",
before call %d\n", c) c ) ;;
cc == message(
message(); );
printf ( "c after call == %d",
printf ("c after call % d " ,c)c ) ;;
}}
void
void message(
message())
{
{
printf ( "Only he will survive who is C-fit" ) ;
printf ("Only he will survive who is C-fit")
}}

(10)
(10) main()
main()
{{
int pP == 2233 ,, ff =
int = 24
2 4 ;;
packman
packman (p, f ) ;;
( p, f)
printf
printf ("p
("p == %df %d f == %d",
%d", p,p ,f)f ) ;;
}}
packrnan ((q,
packrrjan q, hh))
int q, h;
int q, h;
{{
qq=q+a;
=q+a;
h=h+h;
Functioning
Functioning with
with Functions
Functions 163
163

return
return ((q);
q);
return
return ((h)
h ) ;;
}}

((11) main()
1 1 ) main()
{{
int ii ==.3,
int 3, jj;;
jj ==add
add ((+++i++
+ i + + ));;
printf ("i
printf ( Hi==% %d d jj ==%d\n",
%d\n', i,i ,j)j ) ;;
}}
aadd
d d ((ii)
ii)
int ii;
int ii;
{
{
ii++ ;
ii++;
printf ( "ii == %d\n",
printf ("ii %d\n", iii)i ) ;;
}}

((12)
1 2 ) main()
{{
int i == 10,
inti 10,jj == 20,
20, kk;;
k = addsub (i,i, j)
k = addsub ( j ) ;;
printf ("k
printf ( "k == %d",
%d", k) k ) ;;
}}
addsub (c,
addsub ( c, dd ))
int c, d;
int c, d ;
{
{
int x, y;
int x, y ;
x=c-d;
x = c - d;
y=ctd;
y=c+d;
return ( x, y) ;
return (x, y ) ;
}
}

((13)
13) main()
{{
inti
int i = 10,j
10, j = 202 0, k ;
display ( i)i ) ;
164
164 Exploring
Exploring C

sshow(i,j)
h o w ( i , j ) ;;
}}
display ((c,
display c, d)d)
int c, d;
int c, d ;
{
{
printf
printf ("%d
("%d%d %d"," ,c,c ,d)d ) ;;
}}
show (c)
shaN (c)
int c;
int c ;
{{
printf
printf (( ""%d",
% d " ,c)c ) ;;
}}

((14)
14) main()
main()
{{
charaa = 65,
char =
65 ch 'c' ;
ch = 'C';
p
=
printit ( a, ch)
printit ( a , c h ) ;
}}
printit (( aa,, ch
printit ch))
{
{
=
printf ("a %d ch %c·, a, ch) ; =
printf ("a = %dch = % c " , a , c h ) ;
}}

((15)
15) main()
main()
{{
float aa =
float = 3.14
3.14;;
inti =
int i = 99; 99;
pprir i(i,( Ua)) ;;
printit
printit (a, ( a, iJ
i ) ;;
}}
pri
p r i (( ii,, aa))
{
{
printf ( Hi= %d a = %1\n", i, a) ;
printf ("i = %d a = %f\n", i , a ) ;
=
printf ( "a = %1 i %d\n\n", a, i) ;
printf ("a = %f i = %d\n\n", a , i ) ;
}}
printit (( aa,, i)
printit i)
float
float a; a;
Functioning with Functions
FunctioningwithFunctions 165
165

{
printf
printf ("a
( 'a = %f i = %d\n",
%d\n", a, i)i ) ;
printf
printf ("i
( "i = %d a = %f\n\n",
%f\n\n", i,i ,a)a ) ;
}}

((16)
16) main()
main()
{{
int kk =~ 35,
int 35, z;
z;
=
zz = check
check (( k)
k ) ;;
printf ("z
printf (·z == %d",
%d·, z)z ) ;;
}}
cheek (m)
cheek(m)
{
{
int m;
intm;
if [m» 40)
if ( m > 4 0 )
return ( !m++ ) ;
return ( ! m + + ) ;
else
else
return ( !++m) ;
return (!++m) ;
}}

((17)
17) main()
main()
{{
intk
int k = 35, * z , "Y
3 5 , *2, * y ;;
zz = &k;
&k; I* supposeaddress
1* suppose addressofofkkisis1008
1008*/*/
yy ==z;z ;
"Y++ ;
*z++ = *y++;
ktt
k++; ;
( "k = %d z = %d yY = %d", k,
printf ("k k, z, Y)
y ) ;;
}

a(18)
8) main()
main()
{
{
int aa == 100,
int *b, "c, ***d
100, *b,**c, * * * d ;;
b=&a;
b = &a;
cc == &b;
&b;
d = &c;
d= &c;
166
166 Exploring C
Exploring C

printf ("%d
printf ( "%d %d
%d %d
%d %d", a, *b,
%d", a, *b, **c,
**c, ***d)
* * * d ) ;;
}}

((19)
19) main()
main()
{{
= 4;
int z =4;
printf ("%d",
printf printf ("%d
( "%d", printf ("%d %d", z, z)
z )) ;
}}

((20)
20) main()
main()
{{
int ii == -5,
int -5, jj == -2
- 2 ;;
junk ( i,
junk (i, & j ) ; &j) ;
printf ("i
printf ( "i == %d
%djj == %d',
% d " ,i,i ,j j)) ;;
}
}
junk
junk (i, (i, j)j )
int i, *j;
int i, * j ;
{{
ii == i*i;
i*i;
*j =*j**j;
}

((21)
21) main()
main()
{{
float aa == 7.999999;
float 7.999999;
float *b, *c
float *b, * c ;;
b=&a;
b = &a;
cc== b;
b;
printf ( "%d %d
printf ("%d %d %d\n",
%d\n", &a,
&a, b,
b, c)
c ) ;;
printf ("%d
printf ( "%d %d %d %d\n", *(&a), *b, *c)
%d\n", a, *(&a), *c) ;
}}

((22)
22) main()
main()
{{
int *c;
int *c;
cc == check
check ({ 110, 2 0 ) ;;
0 ,20)
Functioning
Functioning with
withFunctions
Functions 167
167

printf ( "e==%d",
printf ("c %d", cc)) ; ;
}
}
check (i,
check (i,j j))
int i,
int i, j ;j ;
{{
int* *p,
int p , * *q;
q;
p=&i;
p = &i;
. • qq==&j; &j;
i i>=
>=45 45 ??return
return ((pp)) : :return
return (( qq )); ;
}
}

main()
(23) main()
(23)
{ {
float *jamboree();
float *jamboree() ;
float pp ==23.5,
float 23.5, **qq ;;
q =&p;
q = &p;
printf ("q
printf ( "q before call == %d\n",
before call %d\n", qq)) ; ;
q = jamboree (&p)
q = jamboree ( & p ) ; ;
printf ("q
printf ( "q after call == %d\n",
after call %d\n", qq)) ;;
}}
float *jamboree
float *jamboree (( rr))
float *r;
float *r ;
{
{
rr=r+1;
= r+ 1 ;
return (( rr)) ;;
return
}

(24)
(24) main()
main()
{{
int i ;
inti;
printf ("In
printf ( 'ln the
the year
year of lord\n");
lord\n" ) ;
for ( ii = 11 ; i <<== 110
0 ;;i itt
+ + ))
main();
main() ;
}

(25)
(25) main()
main()
168
168 Exploring
Exploring C
C

{{
inti;
int i ;
=
for (t( i = 11 ; i <<== 110;
0 ; ii++
++)
main() ;
main();
printf ("In
( "In the year of lord\n");
lord\n" ) ;
}

(26)
(26) main()
main()
{{
ifif (printf ( -c for
( printf ("C for yourself how itn works\n"
yourself how ))
works\n"))
main()
main(); ;
}}

(27) main()
main()
{{
message() ;
message();
printf ("..selling
( "..selling cocaine jn
in Xolombo");
Xolombo' ) ;
}}
message( )
message()
{
{
printf ( "making a fast buck..\n" ) ,
printf ("making a fast buck. An"),
main() ;
main();
}
}

(28) main()
main()
{{
int i == 11 ;;
iiff (( !!ii ))
printf ("Recursive
printf ( "Recursive calls
calls are
are real
real pain!");
pain!" ) ;
else
else
{
{
i =0;
i = 0;
printf ( "Recursive calls are challenging\n" ) ;
printf ("Recursive calls are challenging\n");
main() ;
main();
}}
}}
Functioning with Functions
Functioning with Functions 169
169

[B]
[8] Attempt
Attempt the following:
following:

(1)
(1) Consider aa currency
Consider currency system
system in
in which
which there
there are
are notes
notes of
of seven
seven
denominations, namely,
denominations, namely,

Re.1,1, Rs. 2, Rs. 5, Rs.


Re. 10, Rs. 50, Rs.
Rs.10, 100
Rs.100

If aa sum
If sum of
of Rs. N is
Rs. N is entered through the
entered through the keyboard,
keyboard, write
write aa
program to compute
compute the smallest number of notes that will
combine to give Rs. N.

(2) There are three pegs labelled A, Band


B and C. Four disks are placed
on peg A.
A The bottom-most
bottom-most disk is largest, and disks go on
decreasing in size
decreasing in size with the topmost
with the topmost disk
disk being
being smallest.
smallest. The
The
objective of the
objective of the game
game is
is to
to move
move the
the disks
disks from
from peg
peg A
A to
to peg
peg
C,
C, using peg B
using peg B as
as an
an auxiliary
auxiliary peg.
peg. The
The rules
rules of
of the
the game are
game are
as follows:
as follows:

(a)
(a) Only one
Only one disk
disk may
may be
be moved
moved at
at aa time,
time, and it must
and it be
must be
the top
the top disk
disk on
on one
one of
of the pegs.
the pegs.
(b) A larger disk should never be placed on the top of a
smaller disk.
smaller disk.

Write aa program
Write program toto print
print out
out the
the sequence
sequence in
in which
which the
the disks
disks
should
should bebe moved
moved such
such that
that all
all disks
disks on
on peg
peg A
A are
are finally
finally
transferred to peg
transferred to peg C.
C.

(3)
(3) Write aa program
Write program to
to obtain
obtain the
the sum
sum of
of the
the first ten terms
first ten terms of
of the
the
following series
following series using recursion.
using recursion.

i. I £ I
X
3! 5!
+
7! 9!
+
•"•

(4) Two dates are entered through the keyboard in dd,mm,yy


-Two
format. Write a program to find out the difference in these two
dates in terms
dates in terms of
of number
number of
of days.
days.
170
170 Exploring C
Exploring C

Answers
Answers to [A]
Answers to [A]
,
(1)
(1) Output
Output

c =3.000000
= 3.000000

Explanation
Explanation

When the
When the function
function check(
check( )) is
is called
called 4545 gets
gets collected
collected in the
in the
variable ch.
variable ch. In
In check(
check( )) the
the condition
condition ch ch >= 4545 is satisfied
is satisfied
hence 3.14gets
hence returned. Does
3.14 gets returned. Does it it really?
really? No,
No, because by default
because by default
any function
any function isis capable
capable of
of returning
returning onlyonly an
an int.
into Hence 3.14
Hence 3.14
gets truncated
gets truncated to to 3
3 while
while returning
returning the value.
the value.

What if
What if we
we really
really want
want to
to return
return 3.14.
3.14. Just
Just make
make the declaration
the declaration
float check()
Ooat check() inin main(),
main(), asas well
well as
as while
while defining
defining the
the function.
function.

(2)
(2) Output
Output

12.560000
a = 12.560000
area == 12.000000
12.000000

Explanation
Explanation

On calling
On calling the
the function
function areacircle()
areacircle() value
value of of a
a (3.14
(3.14 * 2.0
2.0 *
2.0 ) gets
2.0) gets calculated,
calculated, which
which is is printed
printed out out as
as 12.560000.
12.560000. ButBut
when this
when this value
value isis returned
returned toto main()
main() it it is
is truncated
truncated toto 12 and
12 and
then returned.
then returned. This
This happens
happens because
because the the function
function areacirle(
areacirle())
is not
is not capable
capable of
of returning
returning aa Ooatvalue.
float value. This This 1212 when
when assigned
assigned
to the variable area gets promoted to 12.000000,
to the variable area gets promoted to 12.000000, since area since area
has been
has been declared
declared as float. Moral
as Ooat. Moral is is -- just
just by by declaring
declaring area
area as
as
Functioning
Functioning with
with Functions
Functions 171
171

float
Doat won't
won't ensure
ensure that
that aa float
float value
value would
would be
be returned
returned from
from
the function.
the function.

(3)
(3) Output
Output

c before call = 34
Live and let live
c after call = 457

Explanation
Explanation

Since cc has
Since has not
not been
been initialised
initialised inin main()
main() itit contains
contains aa garbage
garbage
value.
value. When
When we we ran
ran the
the program
program thisthis garbage
garbage value
value was
was 34.
34.
When
When youyou execute
execute the
the program
program thisthis might
might asas well
well turn
tum out
out to
to
be
be something
something else.
else. After
After this
this message()
message( ) getsgets. called,
called, which
which
ouputs
ouputs the
the message
message on on the
the screen. And having
screen. And having printed
printed the
the
message
message thethe control
control returns
returns back
back toto main(
maine )) alongwith
alongwith some
some
garbage
garbage integer
integer value
value which
which gets
gets collected
dollected inin cc and
and is
is then
then
printed
printed out.
out.

Thus
Thus itit is
is important
important to to remember
remember thatthat whether
whether wewe want
want or or
whether we don't, any time a function is called and the control
whether we don't, any time a function is called and the control
comes
comes back
back from
from thethe function,
function, aa value
value always
always gets
gets returned.
returned.
This
This value
value could
could bebe the
the value
value that
that you
you are
are specifically
specifically returning
returning
using
using the
the return
return statement,
statement, or or some
some garbage
garbage integer
integer value
value if
if aa
specific
specific value
value isis not
not being returned.
being returned.

(4)
(4) Output
Output

Error
Error message:
message: Statement
Statement missing;
missing; in
in function main
function main

Explanation
Explanation

The
The compiler
compiler reports
reports an
an error saying there
error saying there is
is aa missing
missing semi
colon. But
colon. But where
where is
is it
it missing?
missing? After C(). But
After C(). But suppose
suppose we
we only
only
172
172 Exploring
Ewloring C

want to
want define the
to define the function
function C(C( ),), logically
logically we shouldn't be
we shouldn't be
required to
required to give
give aa semi-colon
semi-colon after
after C(
C().). That's
That's thethe point. At
point. At
the most
the most youyou can
can call
call aa function
function fromfrom within
within the the body
body of
of
another function.
another function. You
You are
are not
not allowed
allowed to define another
to define another func-
func-
tion within
tion within thethe body
body ofof another
another function.
function. And And that
that isis what
what the
the
above program
above program is is attempting
attempting to to do.
do. ItIt is
is trying
trying toto define
define C()
C()
and c(
and c( )) in
in main(
main( ),), which
which isis not
not acceptable,
acceptable, hence
hence the error
the error
message.
message.

(5)
(5) Output
Output

= 5k = 5l = 5
i;=5k=51=5

Explanation
Explanation

Whenever the
Whenever the ++.
++' operator
operator precedes
precedes the the variable,
variable, first the
first the
variable's value
variable's value is incremented and
is incremented and then
then used.
used. AsAs against
against this,
this,
whenever the
whenever the ++++ operator
operator succeeds
succeeds the the variable,
variable, its its value
value isis
first used
first used and
and then
then incremented.
incremented. According
According to to this
this rule
rule the
the first
first
call add
call add (( ++i)
++i ) would
would first first increment
increment ii to to 44 and
and then
then pass its
pass its
value to
value to function
function add( add( ). ). In add( )) 44 is
In add( is collected
collected in in ii,
ii, incre-
incre-
mented to
mented to 5,
5, returned
returned to to main(
main()) and and finally
finally stored
stored inin k. Hence
Hence
k's value
k's value isis printed
printed as as 5.
5. In
In the
the next
next call,
call, add
add (i++
(i++ ),), the
the current
current
value of
value of ii (( i,e.
i.e. 44 )) is
is first
first sent
sent toto add(
add( )) and
and then
then i's
i's value
value isis
incremented to
incremented to 5.
5. InIn add(
add( )) ii ii is
is incremented
incremented to to 5,
5, which
which is is
returned and
returned collected in
and collected in 1.
I.

(6)
(6) Output
Output

= 1 3 6 a = 136k = 0
ii=136a=136k=O

Explanation
Explanation

Observe the
Observe the function call in
function call in main(
main( ).
). Since
Since ++++ precedes
precedes ii its
its
value is
value is incremented
incremented toto 136,
136, and
and then
then the
the! ! operator
operator negates
negates itit
Functioning
Functioning with
with Functions
Functions 173

to
to give
give 0.O. This
This 00 is
is however
however not not stored
stored inin ii but
but is
is passed
passed toto
function(). As against this while evaluating the expression
function( ). As against this while evaluating the expression
!a++, since
since ++ follows
follows a, firstly
firstly a isis negated
negated to to 0,
0, this
this 00 is
is
passed
passed to to function()
function( ) andand a isis incremented
incremented to to 136.
136. Thus
Thus what
what
get
get passed
passed to to function()
function() areare 00 and
and 0,
0, which
which areare collected
collected ininjj
and
and b,b, added
added to to give
give another
another 00 andand finally
finally returned
returned to to main(),
main( ),
where
where itit is
is collected
collected inin kk and
and then
then printed
printed out.
out.

(7) Output
Output

kk =38
= 38

Explanation
Explanation

While
While evaluating
evaluating k k in
in main()
main() three
three calls
calls toto function funcl()
function func1()
are
are being
being made.
made. These
These calls
calls are
are evaluated
evaluated inside
inside out.
out. That
That is,
is,
the
the innermost
innermost call call is
is made
made first,
first, followed
followed by by the
the next
next outer
outer call
call
and
and so
so on.
on. SoSo when
when first
first time
time the
the call
call is
is made
made with
with value
value of
ofkk
as
as 35,
35, it
it is
is incremented
incremented in in funcl()
func1() to to 36
36 and
and returned
returned back
backtoto
main().
main( ). ThisThis 3636 is
is then
then collected
collected in in main()
main( ) in in k.
k. This
This new
new
value
value of
of k k (i.e.
( i.e. 36
36 )) becomes
becomes the the argument
argument for for the
the next
next call
call to
to
funcl(
func1( ), ), which
which proceeds
proceeds exactly
exactly in in the
the same
same manner
manner asas the
the
previous
previous call.
call. One
One more
more such
such calf
calt and
and thethe value
value ofof kk would
would
finally
finally become
become 38. 3R

(8) Output
Output

2z = 38
=38

Explanation
Explanation

When
When func()
func( ) is
is called
called from main( ), 35
from maine 35 gets
gets collected
collected in in the
the
variable
variable m. In
In func()
func() this
this value
value is
is incremented
incremented to to 3366 1s.nd
nd then
then
the
the return
return statement
statement isis executed.
executed. But
But the
the return
return cannot
cannot be be
immediately
immediately executed, since within
executed, since within the
the arguments
arguments of return
of return
174
174 Exploring
Exploring C

named
there is another function call, this time to the function named
funcl().
funcl( ). While sending a call to funcl()
funcl( ) first
first the value of m
is incremented to 37, and then this 37 is passed on to fnncl().
funcl().
In funcl(),
fnncl(), m is further incremented
incremented to 38 and it is returned to
func(),
fnnc( ), where it gets collected once again in variable m. And
now this 38 gets returned to main(),
maine ), where it is collected in z
and then printed out.

(9)
(9) Output
Output

Error message: Not an allowed type in function


function main

Explanation
Explanation

The error
error meassage
meassage comes
comes because
because we we are
are going
going back
back on
on our
promise.
promise. First
First we
we are
are telling
telling the
the compiler
compiler that
that message()
message() will
not
not return
return any
any value.
value. This
This isis being
being achieved
achieved through
through the
the dec-
dec-
laration void message(). And then we are trying to collect in
laration void message(). And then we are trying to collect
the
the variable
variable c, c, the
the value
value returned
returned by by message().
message( ). Conclusion
Conclusion --
better
better stick
stick to
to your
your word!
word!

(10) Output
(10) Output

= 2 3 f = 24
pp=23f= 24

Explanation
Explanation

AA call
call to
to packman()
packman() fromfrom main()
main() sends
sends 23
23 and
and24 24 to
to variables
variables
qq and
and h.h. In
In packmanQ
packmanO qq and and hh are
are doubled
doubled andand then
then the
the return
return
( q ) is executed, which sends the control back to main( ))
( q ) is executed, which sends the control back to maine
alongwith
alongwith the the value
value ofof q.
q. But
But since
since this
this value
value is is not
not collected
collected
in
in any
any variable
variable inin main()
main() ititjust
just gets
gets ignored.
ignored. AsAs aa result
result pp and
and
fr stand
stand unchanged
unchanged at at 23
23 and
and 2424 respectively.
respectively. NoteNote that
that the
the
statement return ( h ) never gets executed, since the previous
statement return ( h ) never gets executed, since the previous
return
return statement
statement will
will not
not allow
allow the
the control
control toto reach
reach there.
there.
Functioning with Functions
Functioning with Functions 175
175

(11) Output
(11) Output

Error message: Lvalue


Errormessage: Lvalue required
required in
in function
function main
main

Explanation
Explanation

'Lvalue' means
'Lvalue' means aa variable
variable whose
whose value
value cancan change.
change. OrOr inin other
other
words, aa variable
words, variable which
which cancan occur
occur on on the
the left
left hand
hand side
side of the
of the
assignment operator.
assignment operator. Now
Now look
look at at the
the expression
expression ++i++. Here Here
firstly ii would
firstly would be be incremented
incremented to to 44 (due
( due to to the
the ++++ operator
operator
before i)
before i ) and
and the
the expression
expression would
would become
become 4++. 4++. AsAs aa result
result 44
would be
would passed to
be passed to add(
add( )) and
and thenthen would
would attempt
attempt to get
to get
incremented owing
incremented owing to to the
the operator
operator that that occurs
occurs after
after i.
i. But
But 44
cannot
cannot be be incremented
incremented because
because it it is
is not
not aa variable.
variable. Possibly
Possibly if if
you consider
you consider thethe expression
expression i++i++ as as ii = ii +
+ 11 then
then you
you would
would be be
able to
able to appreciate
appreciate thethe mistake
mistake in the program
in the program better.
better. An
An attempt
attempt
would be
would be made
made toto evaluate
evaluate 4++
4++ as as 4 =
4 =4 4++ 1. And since
1. And since 44 is
is not
not
aa variable
variable itit cannot
cannot occur
occur on
on left
left hand
hand sideside of
of =.
=. In
In other
other words,
words,
on left
on left hand
hand side
side of
of assignment
assignment operator
operator aa variable
variable ((lvalue
lvalue ))
should occur.
should occur.

(12) Output
(12) Output

kk =30
= 30

Explanation
Explanation

Values of
Values of ii and
and j (( 10
10 and
and 2020 )) are
are passed
passed to to addsub()
addsub( ) and and
collected in variables
collected in variables e and c and d.d:In function addsubf
In function addsubr), ), xx
evaluates to
evaluates -10, whereas
to -10, whereas yy e~aluates
evaluates to to 30.
30. Then
Then the
the return
return
statement attempts
statement attempts to to return
return the
the values
values of of xx and
and y. Whenever
y. Whenever
we attempt to
We attempt to return
return more
more than
than one
one value
value through
through thethe return
return
statement, the
statement, the last
last value
value gets
gets returned.
returned. Thus,
Thus, inin this
this case the
case the
value of y, i.e. 30 gets returned. Had the return statement
value of y, i.e. 30 gets returned. Had the return statement been been
return
return (y,( y, xx )) then
then value
value of
of xx would
would have
have been
been returned.
returned.
176
176 Exploring
Exploring C

(13) Output
(13) Output

1045710

Explanation
Explanation

When display(
When display() ) is
is called
called one
one argument
argument is passed to
is passed to it,
it, whereas
whereas
while defining
while defining display(
display( ) two two arguments
arguments are are used.
used. Would
Would it it
result into
result into an
an error?
error? No,
No, since
since the
the compiler
compiler accepts
accepts aa mismatch
mismatch
in the
in the number
number of of arguments
arguments being passed and
being passed and collected.
collected. IfIf this
this
is so,
is so, which
which of the two
of the two variables
variables would
would collect the value
collect the value being
being
passed to
passed to display(
display( )? )? ec colfects
collects the
the value
value being
being passed,
passed, hence
hence
the printf
the priotr()( ) prints
prints out
out the
the value
value of
of cc as
as 10,
10, whereas
whereas d d is printed
is printed
as garbage
as value.
garbage value.

What if
What if wewe pass
pass two
two arguments
arguments andand collect
collect them
them in one
in one
variable? This
variable? This is
is what
what is
is being
being done
done in
in the
the call
call to
to function
function
show( ).
show( ). Here
Here the
the first
first value
value gets
gets collected
collected in
in the
the variable c,
variable c,
whereas the
whereas the second
second value
value gets
gets ignored.
ignored. The
The value
value collected
collected in
in
c, i.e.
c, i.e. 10
10 then
then gets printed.
gets printed.

(14) Output
(14) Output.

aa=65ch=C
= 65ch = C

Explanation
Explanation

First glance
First glance at
at the
the function
function printit()
priotit() would
would lead
lead you
you to believe
to believe
that the
that the compiler
compiler should
should have
have flashed
flashed anan error
error message since
message since
the
the variables a and ch have not been defined in printit( ). But
variables a and ch have not been defined in printit(). But
then the
then the Turbo
Turbo C C compiler
compiler isis aa fatherly
fatherly old
old chap
chap who
who knows
knows
the pulls
the f5ulls and
and pressures
pressures aa C C programmer
programmer has has toto bear
bear and
and
therefore makes
therefore makes such
such concessions.
concessions. While
While (Jellning
defining thethe functi
function
on
if the
if the type of formal
type of arguments (( aa and
formal arguments and ch
ch in
in this
this case)
case ) is
is not
not
mentioned
mentioned thenthen they
they are
are treated
treated as
as integer
integer arguments.
arguments. ThusThus aa
Functioning with Functions
Functioning with Functions 177
177

and ch are
and are treated, as integers,
treated as integers, and
and hence
hence printed
printed out
out without
without
any hitch by the printf().
any hitch by the printf( ).

(15) Output
(15) Output

=
i = 99
99 8=
a = 0.000000
0.000000
=
a8 = 0.000000 =
0.000000 ii = 99
99
a =3.14
8 = 3.14ii == 99
99
=
i = 998::3.14
9 9 a = 3.14

Explanation
Explanation

When pri(
When pri( )) is
is called
called the
the values
values passed
passed toto it
it are
are collected
collected inin the
the
variables ii and
variables However, the
and a. However, type of
the type of these
these variables
variables have
have not
not
been declared.
been declared. Therefore,
Therefore, they
they are
are assumed
assumed to to be
be ints.
iBts. The first
The first
printf( ) in
printr() in pri(
pri()) prints
prints out
out the
the value
value of
of ii correctly,
correctly, but value
but value
of aa gets
of gets messed
messed up up because
because we we are
are trying
trying to to print
print an integer
an integer
value collected in a using the specification
'value collected in a using the specification %1. The second%f. The second
printf() messes
printf() messes up up both the values
both the values since
since the first specification
the first specification
itself in
itself in this
this printf(
printf()) is wrong. Remember
is wrong. Remember that that once
once the output
the output
of one
of one variable
variable goes
goes awry
awry the
the printf(
printf( )) messes
messes up up the
the output
output
of the rest of the variables
of the rest of the variables too. too.

When printit()
When printit( ) is called aa has
is called has been
been declared
declared as
as Ooat
float whereas
whereas
ii has
has not
not been
been declared,
declared, hence
hence is
is assumed
assumed to
to be
be an
an into
int. There-
There-
fore both
fore both the
the printr(
printf( )s
)s output
output the
the values
values as
as expected.
expected.

(16) Output
(16) Output

Error message:
Error Redeclaration of
message: Redeclaration of'm' in function
'm' in function check
check

Explanation
Explanation

Observe the
Observe the check()
check( ) function
function carefully.
carefully. The
The variable
variable mused
m used
in check( ) has
in has not
not been defined before
been defined the opening
before the brace.
opening brace.
178
178 Exploring C
Exploring C

Therefore
Therefore itit is
is assumed
assumed toto be
be an
an integer
integer variable. And then
variable. And then after
after
the opening brace we once again declare m, thereby causing
the opening brace we once again declare m, thereby causing
the
the redefinition
redefinition of of the
the variable
variable m.
m. Hence
Hence the
the error message.
error message.

17) Output
Output

= =
3 6 zz = 1010
k = 36 =
1010yY = 1010

Explanation
Explanation

In
In main()
maine ) thethe address
address of of kk is
is stored
stored inin zz and
and the
the same
same address
address
is
is then
then assigned
assigned to to y.
y. Since
Since yy andand zz contain
contain addresses
addresses of of an
an
integer
integer (( 35
35 ), ), they
they have
have been
been quite
quite appropriately
appropriately declared
declared as as
integer
integer pointers.
pointers. The The next
next statement
statement is is the
the most important
most important
statement
statement in in this
this program.
program. What What is is done
done here is, the
here-is, the zz and
and y
pointers
pointers are
are incremented
incremented to to point
point toto the
the next
next integer
integer location
locatiq'n
(( which
which would
would be be 1010,
1010, assuming
assuming that that zz and
and y y contain
contain 10Q810d8
before
before incrementation
incrementation). ). But But before
before thethe incrementation
incrementation what what isls
done
done is
is assignment.
assignment. This This isis beacuse
beacuse ++ ++ isis occurring
occurring after
after the
the
variable'
variable names
names yy and and z. z. During
During assignment,
assignment, value value at at the
the
address
address contained
contained in in zz is
is replaced
replaced by by value
value at at the
the address
address
contained
contained in in yy (i.e.
( i.e. 35
35 ).
). After
After that
tha t the value
the val of kkis
ue of incremented
is increm ented
to
to 36
36 and
and then
then printed
printed out.
out. i
(18) Output
(18) Output

100100100100
100100100100

Explanation
Explanation

bb contains
contains thethe address
address of
of an
an integer
integer a,
a, hence
hence bb is
is an
an integer
integer
pointer. cc contains
pointer, contains the
the address
address of
of an
an integer
integer pointer, hence ccisis
pointer, hence
aa pointer
pointer toto an
an integer
integer pointer.
pointer. Similarly,
Similarly, since
since dd contains
contains the
the
address
addrelw?fof a,pointer
a.pointer toto an
an integer
integer pointer,
pointer, dd can
can bebe called
called a11
Functioning with Functions
Functioning with Functions 179
179


pointer to
pointer to aa pointer
pointer to
to an
an integer pointer. Foxed?
integer pointer. Foxed? Look
Look at
at the
the
following figure
following figure to
to sort
sort it out.
it out.

a
abc b c d

0ElB8
100

4002
4002
4002

5006
5006
| 5006

7008
7008

9002

Figure 5.7

In printf(),
In printf(), aa would
would print
print out
out the
the value
value 100
100 which
which is straight-
is straight-
forward. *b would print the value at the address contained
forward. *b would print the value at the address contained in in
b.
b. Since
Since the address contained
the address contained in in bis
b is 4002,
4002, and
and the
the value
value at at
this address
this address is
is 100,
100, once
once again
again 100
100 would
would get printed. ***c
get printed. * c can
can
be
be explained similarly, ec would
explained similarly. would give *c means
5006, *c
give 5006, means value
value atat
address contained in c, i.e. value at address 5006,
address contained in c, i.e. value at address 5006, i.e. 4002.i.e. 4002.
Thus **c
Thus c gives
gives 4002, therefore ***c
4002, therefore * c would
would give
give value
value at
at address
address
4002, i.e. 100.
4002, i.e. 100.1I hope
hope you
you would
would bebe able
able to
to extend the similar
extend the similar
logic to understand the output of ***d, which would
logic to understand the output of ***d, which would also be also be
100.
100.

(19) Output
(19) Output

4443
43

Explanation
Explanation

Can aa printf(
Can printf( )) occur
occur within
within another
another printf(
printf( )?)? Yes,
Yes, by by all
all
means. Here the
means. Here the inner printf()) is
inner printf( is executed
executed first,
first, and
and it prints
it prints
out
out aa 4,
4, aa space
space and
and another
another 4.4. Thus
Thus itit totally
totally prints
prints out
out 33
characters. Whenever the
characters. Whenever printf() function
the printf() function is
is called
called it returns
it returns
the number of
the number of characters
characters it
it has
has successfully
successfully managed
managed to print.'
to print.'
In this program
In this program thethe inner
inner printf(
printf()) has
has printed
printed out
out 33 characters*,
characters,
180
180 Exploring C
Exploring C

therefore it sends back 3 to the calling function, which is


promptly printed
promptly printed out
out by
by the
the outer
outer printf().
printf( ). Moral
Moral of
of the story
the story
is whenever aa function
is whenever function is
is called, be it
called, be it aa user-defined
user-defined or
or aa
standard
standard library
library function,
function, it
it always
always returns
returns aa value.
value.

(20) Output
(20) Output

ii=-5j=4
= -5j = 4

Explanation
Explanation

Refer to
Refer the following
to the following figure
figure first.
first.

mainO's i,
main()'s i,jj mainO's i,
mainO's i,jj
i jJ jJ

,0 0 after
after
00
4008 4008
4008
multiplications
multiplications

4008 25 4008

junkO's i,j
junkO's i,j junkQ's i,j
junkO's i,j

Figure 5.8
Figure 5.8

One doubt immediately


immediately comes to the mind - can we use same
variable names in
variable names in different
different functions?
functions? Yes,
Yes, by
by all
all means,
means,
without
without absolutely
absolutely any conflict. Thus,
any conflict. Thus, the
the two
two sets
sets of
of ii and
and jj
are
are two
two totally
totally different
different sets
sets of
of variables.
variables. While
While calling the
calling the
function junk( ) the
functionjunk() value of
the value of ii and
and the
the address
address 'bfj
of j are
are passed
passed
r
Functioning with Functions
FunctioningwithFunctions 181
181

to it.
to it. Naturally,
Naturally, in
in junk(
junk( )) ii is
is declared
declared as
as an
an ordinary
ordinary int,
int,
whereas jj is
whereas is declared
declared as
as aa pointer
pointer to
to an int.
an into

Even though
Even though the the value
value of
of ii isis changed
changed toto 25
25 inin junk(
junk( ), this
), this
change will
change will not
not be
be reflected
reflected backback in main().
in maine As against
). As against this,
this,
since j ' ss address
since j' address is being passed
is being passed toto junk(
junk( ), ), any
any change
change inin
junk() gets reflected
junk( ) gets reflected back
back in in maine
main(). Hence *j
). Hence *j ** *j,
*j, which
which
evaluates to
evaluates to 4
4 is
is reflected
reflected back
back inin main(
maine ).). Figure
Figure 5.8 would
5.8 would
make the
make the whole
whole logic
logic aa little
little more
more palatable.
palatable.

(21) Output
(21) Output

420042004200
4200 4200 4200
024576-316415
024576 -316415

Explanation
Explanation

bb contains
contains the
the address
address of of variable
variable a. Since
Since a is is aa float,
float, bb must
must
be aa float
be float pointer.
pointer. The
The same
same address
address is is then
then assigned
assigned to to c.
c.
Therefore cc has
Therefore also been
has also been declared
declared asas"aa Ooat
float pointer.
pointer. The first
The first
printf()) prints
printf( prints the
the address
address of of aa in
in three
three different
different ways.
ways. NoNo
problem there.
problem there. What
What is is surprising
surprising is
is the
the output
output of of the
the second
second
printf().
printf( ). Through
Through thisthis printf() we are
printf( ) we are attempting
attempting to to print
print
7.999999 by
7.999999 by applying
appl ying pointer
pointer operators
operators on on a,
a, b and c.
band c. a,
a, *(&a),
*(&a),
*b, *c
*b, *c all
all yield
yield 7.999999
7.999999 but but when
when they
they are
are printed
printed using
using %d,
%d,
printf() ) blows
printf( blows itit up
up as
as the
the output
output above
above would
would justify.
justify.

So always
always remember
remember to to use %f to
use %f print floating
to print floating point vaiues.
point values.
Don't rely
Don't rely onon printf(
printf() ) to
to truncate
truncate aa Ooat
float value
value to
to an
an integer
integer
while printing
while printing by by using
using aa %d.
%d. Vice
Vice versa
versa also
also its
its true.
true. The
The
following statements
following would not
statements would not print 7.000000. Don't
print 7.000000. Don't bebe
surprised if
surprised if you
you get
get some
some odd value. In
odd value. that sense
In that sense %d
%d andand %f
%f
. are
are aa little
little unreliable.
unreliable.

int ii =
int = 7;
7;
printf
printf (("%f",
"%1", i)i ) ;;
182
182 Exploring C
Exploring C

(22) Output
(22) Output

Error message:
message: Non portable pointer assignment in main

Explanation
Explanation

The reason for the error is simple. The integers being passed
to check() are
to check() are collected
collected in
in iiandj,
and j , and
and then
then their
their addresses
addresses areare
assigned
assigned toto pp and
and q.
q. Then
Then inin the
the next
next statement
statement the conditional
the conditional
operators test the
operators test the value
value of
of ii against
against 45,45, and
and return
return either the
either the
address stored in
address stored in pp or
or the
the address
address stored
stored inin q.
q. It
It appears
appears that
that
this
this address would be
address would be collected
collected inin cc in
in main(),
main(), andand then would
then would
be
be printed out. And
printed out. And there
there lies
lies the
the error.
error. The
The function
function check(
check())
is not capable
is not capable of of returning
returning an an integer
integer pointer.
pointer. All
All that
that it
it can
can
return is an
return is an ordinary
ordinary integer.
integer. Thus
Thus just
just declaring
declaring cc as
as an integer
an integer
pointer
pointer is is not
not sufficient.
sufficient. We W~ must
must makemake the following
the following
modifications
modifications in in the program to
the program to make
make it it work properly.
work properly.

main())
main(
ff
int*c;
int *c;
int *check()
int *check();;
cc == check
check ((10,20);
10, 20) ;
printf ("c
printf = %d",
( "c = %d",ch
c] i
}}
int *check ((i,i, jj))
int *check
int i,j j ;;
int i,
{{

}}

(23) Output
(23) Output

q before call == 5498


before call 5498
after cal
q after callI == 5502
5502
Functioning with Functions
Functioning with Functions 183
183

Explanation
Explanation

In maine
main( ), q has been declared as a float float pointer. It means q
is a variable
variable capableof
capable of holding the address of a float. Through
q
q = &p&p the
the address
address ofof p,
p, aa float,
float, is
is stored
stored in
in qq and
and then
then printed
printed
out through the
out through the printf(
printf(). This is
). This is the
the value
value ofof qq before
before jam-
jam-
boree()
boree( ) is is called.
called. When
When jamboree()
jamboree( ) is is called
called the
the address
address ofof
p is sent
p is sent to
to it
it and
and is
is collected
collected in in r. At
At this
this juncture
juncture r contains
contains
5498 ( when we
5498 (when we ran
ran the
the program
program it it was
was 5498;
5498; when
when you
you execute
execute
the program this
the program this may
may turn
tum out
out to
to be
be some
some other
other address). When
address ). When
rr is
is incremented
incremented it it would
would become
become 5502.
5502. WhyWhy aa step
step ofof 4?
4?
Because r is a float pointer and on incrementing it
Because r is a float pointer and on incrementing it by 1it would by 1 it would
point
point to the next
to the next float which would
float which would be be present
present 44 bytes
bytes hence,
hence,
since every float
since every is 44 bytes
float is bytes long.
long. The
The return statement then
return statement then
returns this address
returns this address 5502
5502 back
back toto main(
main(). ).

Since a float
float pointer is being returned, a declaration float float
*jamboree() is
*jamboree() is necessary in main(),
necessary in main(), which
which tells
tells the compiler
the compiler
that down
that the line
down the line there
there exists
exists aa function
function called
called jamboree(
jamboree(), ),
which
which will
will return
return aa Doat
float pointer.
pointer.

(24) Output
(24) Output

In the year of lord


In the year of lord
!n the
In the year of lord
In the
the year of lord

Explanation
Explanation

When the control enters main(


main( ) it meets the printt;
print!' ) and
promptly prints
promptly prints the
the message.
message. Then
Then comes
comes the
the for
for loop. First
loop. First
time through
time through the
the for
for loop
loop the
the function main()) is
function maine called again.
is called again.
184
184 Exploring
Exploring C
C

This
This isis nothing
nothing butbut recursion
recursion -- aa function
function calling
calling itself.
itself. SoSo
control
control once
once again
again reaches
reaches thethe printf(),
printf( ), and
and hence
hence thethe second
second
message.
message. Once
Once again
again the
the control
control reaches
reaches the
the for loop
loop and
and with
with
ii equal
equal toto 11 once
once again
again main()
main( ) gets
gets called.
called. This
This results
results into
into
another
another message
message printed
printed onon the
the screen followed by
screen followed by another
another call
call
to
to main(
main( )) for
for value
value ofof iiequal
equal toto 1.
1. This
This goes
goes on
on and
and onon until
until
either
either you
you abort
abort the execution by
the execution by pressing ctrl C
pressing Ctrl Cor or Ctrl
ctrl scroll-
scroll-
lock or when the internal stack overflows.
lock or when the internal stack overflows.

(25) Output
Output

No
No output
output

Explanation
Explanation

First
First time
time the
the control
control reaches
reaches thethe for loop
loop main()
main( ) gets called.
once
once again. The control
again. The control again
again reaches
reaches the
the for loop
loop and
and for
for value
value;
of
of ii equal
equal to
to 1,
1, main()
main( ) is
is called
called yet
yet another
another time,
time, so
so on
on and
and so
so [
forth.
forth. This
This continues
continues until
until the
the stack
stack becomes
becomes fullfull or
or until
until the,
the
user
user aborts
aborts the
the program
program through
through Ctrl scroll-lock.
ctrl scroll-lock.

(26) Output
Output

C for yourself
yourself how it~works
works
C
C for yourself how it works
works
C
C for yourself
yourself how ttit works
works
yourself
C for yourself how n
it works
works

Explanation
Explanation

On
On execution,
execution, printf() always
always returns
returns the
the number
number ofof characters,
C1HUU .......,.~

it has
has printed
printed succesfully.
succesfully. In
In our
our case
case this
this value
value will
will be
be 27.
Since
Since the value returned is a non-zero value the if evaluates to-
the value returned is a non-zero value the if evaluates
Functioning with Functions
Functioning with Functions 185
185

true, hence
true, hence main(
main( )) gets
gets called.
called. Next
Next time
time around
around exactly
exactly the
the
same thing
same thing happens. This goes
happens. This goes on
on and
and onon till
till either
either the user
the user
interrupts through
interrupts Ctrl scroll-lock
through ctrl scroll-lock or
or aa stack
stack overflow occurs.
overflow occurs.

(27) Output
(27) Output x

making a fast
making fast buck
making a fast
.making fast buck
making a fast
making fast buck

Explanation
Explanation

From main(
From main( )) firstly
firstly the
the function
function messagef
message( )) gets
gets called.
called. InIn
message( )) 'making
message( 'making a a fast
fast buck'
buck' gets
gets printed
printed and
and once again
once again
main()) gets
main( gets called,
called, through
through which
which once
once again
again message
message () gets
( ) gets
called. This
called. This goes
goes onon and
and on.
on. Thus,
Thus, the
the control
control never
never reaches
reaches
the
the printf(
printf( )) statement
statement in in main(
main( ),
), and
and therefore
therefore ''..selling
..selling
cocaine in
cocaine Xolombo' doesn't
in Xolombo' appear in
doesn't appear in the output.
the output.

(28) Output
(28) Output

Recursive calls
Recursive challenging
calls are challenging
Recursive calls
Recursive calls are challenging
challenging
Recursive calls are challenging
Recursive challenging

Explanation
Explanation

Since ii is
Since 1, !i
is 1, !i results
results into
into aa 0.
0; Therefore
Therefore thethe if
if fails
fails and
and ihe
1l1~
control reaches
control reaches thethe else
else block,
block, where
where ii is assigned aa value
is assigned value 0,
0,
the printf()
the printf() isis executed,
executed, and once again
and once again main()
main() is is called. What
called. What
is important
is important is is when
when main(
main()) isis called
called now,
now, the
the variable
variable ii is
is
186
186 Exploring C
Exploring C

reset to
reset to 1. Thus, !i
1. Thus, !i would
would bebe 0,
0, and again the
and again the control
control would
would
reach the
reach the else
else block
block and
and the same process
the same process would
would bebe repeated
repeated
all over
all over again.
again- NoNo provision
provision has
has been
been made
made to break
break out
out of
of these
these
horrowing circles,
horrowing circles, hence
hence this
this goes
goes onon indefinitely.
indefinitely. The only
The only
way to
way to break
break out
out of
of the
the loop
loop is
is to
to press
press ctrl
Ctrl scroll-lock.
scroll-lock. II hope
hope
you too
you too^agree
agree that
that 'Recursive
'Recursive calls
calls are challenging'!
are challenging'!

Solutions to [8]
Solutions to [B]

(1) Program
(1) . Program

main()
main( )
{{
int sum, notes = 00 ;

printf (("\nEnter
"\nEnter the sum of rupees");
rupees" ) ; •.
scanf (("%d",
scant &sum);
"%d", &sum );

denom (&sum,
( &sum, &notes, 100);
100);
denom ((&sum,
&sum, &notes, 50)
50);
denom ((&sum,
&sum, &notes, 10);
&notes, 10)
denom (&sum,
(&sum, &notes, 5)
5 ) ;;
denom ((&sum,
denom &sum, &notes, 2)
2 ) ;;
notes += sumsum;;
H\nSmailest number of notes = %d",
printf (("\nSmallest notes);;
%d H,notes)
}}
denom (( s, s , n,
n , Cc ))
int *s, *n,
int *s, *n, c ;;
C
{{
*n
* n ++== (( ((*s)
* s )Ie)
/ c ) ;;
*s %=
*s%=c; c;
}

Sample run
Sample run

Enter the sum of rupees 159


Functioningwith
Functioning withFunctions
Functions 187
187

Smallestnumber
Smallest numberofofnotes
notes= 5 5 =
Explanation
Explanation

TheThefunction denom() )isispassed


function denom( passed thetheaddress
address ofofthe
thevariables
variables
sum and notes,
sum and notes, and one of the 7 denominations of notes. First
and one of the 7 denominations of notes. First
time
timewhen
when thethefunction
function isiscalled,
called, the
thesum
sumofofrupees
rupeesisisdivided
divided
by 100 to find out the maximum number of 100 rupee notes.
by 100 to find out the maximum number of 100 rupee notes.
The remainder is then assigned to the address of sum. Next
The remainder is then assigned to the address of sum. Next
around, the value at sum
time around, the value at sum is used to find the number of 50
time is used to find the number of 50
rupee
rupee notes,
notes, and
andsosoon,
on,till sumisisreduced
tillsum reduced toto1.1.Corresponding
Corresponding
to a 1 rupee note, sum itself is added to notes, yielding the
to a 1 rupee note, sum itself is added to notes, yielding thetotal
total
number of notes
number of notes required.required.

(2)
(2) Program
Program

main( )
main()
{
{
int n = 4;
int n = 4;
move ((n,
move n , ' A'A',
' , ''B',
S V 'C')
C');;
}
}
move ( n, sp, ap, ep)
move(n, sp, ap, ep)
int n;
int n ;
char sp, ap, ep ;
char sp, ap, e p ;
{
{
if (n
if(n«1)
==
1)
printf (~\nMove from %c to %c ., sp, ep) ;
printf (*\n Move from %c to %c", sp, e p ) ;
else
else
{
{ move ( n - 1, sp, ep, ap) ;
m o v e ((1,
move n - 1sp,
, sp, ep, a; p ) ;
", ep)
m o v e ( 1 , s p ,
move (n - 1, ap, sp, " , e p ) ;ep) ;
} m o v e ( n - 1 , ap, sp, e p ) ;
} }
188
188 Exploring
Exploring C

Sample run
Sample run

Move from
Move from A to B
Move from
Move from A to C
Move from
from B to C
from A to B
Move from
from C to A
Move from
from C to B
Move from
Move from
Move from A
A to
to B
B
Move from
Move from A to C
A to C
Move from
Move from B
B to
to CC
Move
Move from B to
from B to A
A
Move
Move from C to AA
from C to
Move from
Move from B
B to
to CC
Move from A to B
Move from A to B
Move
Move from
from A
A to
to CC
Move from B to C
Move from B to C

Explanation
Explanation

This problem
This problem is the famous
is the famous Towers
Towers of of Hanoi
Hanoi problem,
problem, wherein
wherein
three pegs are
three pegs are to
to be
be employed
employed for for transferring
transferring thethe disks
disks with
with
the given
the criteria. Here's
given criteria. Here's how
how wewe gogo about
about it.it. We
We have three
have three
pegs: the starting
pegs: the starting peg,
peg, sp,
sp, the
the auxiliary
auxiliary pegpeg ap,
ap, and
and the
the ending
ending
peg,
peg, ep, where the
ep, where disks must
the disks must finally
finally be.
be. First, using the
First, using ending
the ending
peg
peg as an auxiliary
as an auxiliary oror supporting
supporting peg,peg, we
we transfer
transfer all
all but the
but the
last disk to
last disk ap. Next
to ap. Next the
the last disk is
last disk is moved
moved fromfrom spsp to
to ep.
ep. Now,
Now,
using
using spsp as the supporting
as the supporting peg,
peg, all
all tile
the disks
disks are
are moved
moved from
from
ap
ap to
to ep.
ep.

The three pegs are denoted by 'A','A', 'B'


' B ' and ''C'.
C . The recursive
function move()
function moveO is is called
called with
with different
different combinations
combinations ofof these
these
pegs as starting,
pegs as starting, auxiliary
auxiliary and
and ending
ending pegs.
pegs. Going
Going through the
through the
following figure would
following figure would bebe the
the best
best way
way to to sort
sort out
out how
how the
the
control
control flows
flows through
through the program.
the program.
Functioning with
Functioning with Functions
Functions 189
189

/ move(l,A,C,B) A.. B
y move(l,A,C,B) A-B
moveC2,A,B,q A"C A...C
move(2,A,B,C) A-C A-C
'" move(l,B,A,q B C
\ move(13AC) B C
/
move(3,A,C,B) A -B
A....B A-B

~ / move(l,C,B,A)
move(l.C,B,A) C-A
/
move(2,C,A,B) C....B C....B
move(2,C,AB> C-B C-B
"" move(l,A,C,B)
move(l,A,C,B)
x A...B
A-B

move(4,AB,Q
move(4,A,B,q-- A:+ C AA"'C
-C

y/ move(I,B,A,q
move(l,B,AQ B-C

/
move(3,B,A,q
move(2,B,C,A)
move(2,B,C,A)

.
\

BB-+C
-C
'" . Ba-.A
-A
move(l,C,B,A)
move(l,C,B,A)
BB..
- AA

C-A

B....C
B-C

~ / move(I,A,C,B) A+B
ymove(l,AQB) A-B
move(2,AB,C)
move(2,A,B,q A- C
A-C A+C
A-C

- ~\ move(l,B,AC)
n1ove(l,B,A,Q B....C
B-C

Figure
Figure5.9
5.9

(3)
(3) Program
Program

main()
main( )
{ {
190
190 Exploring
Exploring C
C

float x;
x;
float sum_series();
sum_series() ;

printf ("\nEnter
( "\nEnter value of x "') ) ;;
scanf ( " % f , &x);
scant ("%f', &x); .

printf ("Sum
( ·Sum of first 10
10 terms == %f,
%f', sum_series ( x ) ) ;;
}

float sum_series ( x ))
float x;
x;
{{
static int i, sign == 11;
;
float p,p,f; f;
static float sum;
sum ;
inti,j, k;k;
int

ifif(i<10)
( i < 10)
{{
ji=1+2*i;
= 1+2*i;

Pp=f=1
= f = i ;;

for ( kk =:: 1 ;; k <= ji;


; k++
k++))
{{
pp*=x;
*=x;
f * = kk;;
f*=
}}

sum += ( (( pP //1)
f ) * sign)
sign);;
i++;
itt ;
sign *= -1
-1;
sum series (x)
sum_series (x);
}}
return (( ssum
return u m)) ;;
}
Functioning with Functions
Functioning with Functions 191
191

Sample run
Sample run

Enter value of x 1.57


Sum of first 10 terms is = 1.000000
1.000000

Explanation
Explanation

The variable
variable j is set up so that it stores values 1, 1,3,5,7,9
3, 5, 7, 9 etc.
one after
one after the
the other,
other, corresponding
corresponding to to the
the degree
degree' ofof xx in
in the
the
series. Using aa for
series. Using for loop,
loop, pp is
is assigned
assigned thethe value
value of of xx raised
raised to
to
jj,, and
and fis
f is made
made to
to store
store the
the factorial
factorial value
value ofj.
of j . The
The series
series starts
starts
with
with aa positive
positive x,x, so
so sign
sign is
is initialised
initialised toto 1,
1, and
and then
then made
made toto
toggle
toggle for
for the
the consecutive
consecutive terms
terms ofof the series.
the series.

To start
To start with,
with, sum
sum is is declared
declared as as static
static float,
float, ensuring
ensuring thatthat it
it
stores aa zero.
stores zero. The
The first time x,
first time x, i.e.
i.e. 1.57
1.57 gets
gets stored into sum,
stored into sum, asas
for ii equal
for equal to
to zero
zero (i( i has
has been
been declared
declared static
static ),
), pp evaluates
evaluates to to
1.57 itself and
1.57 itself and ff to to 1.1. Now
Now ii is incremented to
is incremented to 1, and
1, and
sum_series()
sum_series() is is called
called recursively;
recursively. Since
Since sum
sum and
and ii both
both have
have
aa static
static storage
storage class,
class, their
their values,
values, 1.57
1.57 and
and 11 respectively
respectively are are
retained
retained in the second
in the second call.
call. This
This call
call adds
adds on
on to
to sum
sum thethe value
value
of
of the second term
the second term of of the
the series.
series. Following
Following thisthis ii is
is again
again
incremented
incremented and and once
once again
again sum_series()
sum_series() is is called,
called, and
and so on,
so on,
till all the 10 terms are evaluated, and then control
till all the 10 terms are evaluated, and then control returns to returns to
main(),
main( ), wherein
wherein thethe value
value ofof the
the series
series is printed out.
is printed out.

(4)
(4) Program
Program

main()
main( )
{{
int d1, m
m1,
l , y1, d2, m2, y2, days, dm ;

days = 1 ;
days=1;
dm = 0 ;
dm=O;
192
192 ExploringCC
Exploring

printf("Input
printf ( "Inputfirst
firstdate
date(dd.mm.yy)");
(dd,mm,yy) .) ;
scant ("%d
scant ('%d %d%d%d",%d', &d1,
&d1, &m1,
&m1, &&yl
y 1 )); ;

printf("Input
printf ( "Inputsecond
second date
date (dd,mm,yy)");
(dd,mm,yy) • ) ;
scant ("%d
scant ( "%d%d%d%d",
%d",&d2,
&d2,&m2,
&m2, &&y2)
y2); ;

dm==daysinmonth
dm daysinmonth ( m
( ml ,1,yy1
1 ) ); ;

while ((1
while 1))
{
{
days = days + 1 ;
days = days + 1 ;
=
d1 d1 + 1 ;
d1 = d1 + 1 ;

if( dl >>dm)
iff,d1 dm)
{ {
ml =
m1 =m1mt ++11; ;
=
d1 1 ;
d1=1;

if(m1 >>12)
if(m1 12)
{
{
m1 = 1 ;
ml = 1 ;
y1 = y1 + 1 ;
yi=yi + i;
}
}
dm == daysinmonth
dm daysinmonth ((mml 1,
, yy11 ) ;;
}
}

if(d1
if ( dl ===
= dd2
2 &&&
& mml1 == m2 && yl ==y2)
== m2&&y1 == y2)
break;
break ;
}
}

printf ("\n\nDifference
printf ("\n\nDifference in Dates == %d",
in Dates %d·, days);
days) ;
}
}

daysinmonth (m,
daysinmonth ( m, y)
y)
int m, y;
int m, y ;
{
{
Functioning with Functions
Functioning with Functions 193

int dm;
int dm;

ifif ( m == 111|
m == 31|m m====51151|
II mm====311 m == 71171|
m == m ==m811 81|==m10==II 101|
== m 12==
m == m ) 12)
dm == 31 ;
31;

ifif (( m
m == 41|mm=====61161|m ==
== 411 == 91|
m =911 ==) 11)
m ==m11
dm =30;
=30;

if(m==2)
if (m == 2)
{{
dm,:
dm = 28; 28;
ifif (( (( yy %
% 400 ==0)0) II||((Yy%%100
400 == f= 0&&&&
1001=0 Y% 4 ==
y% 0) 0))
4 == )
dm =29;
dm = 29;
}}
return ( dm
return d m)) ;;
}

Sample run
Sample run

Input first
Input first date
date ((dd, mm, yy)
dd, mm, yy) 01 01
011993
1993
Input second
Input second date
date (dd,
( dd, mm, yy) 31
mm, yy) 31121993
12 1993

Difference in
Difference in Dates = 365
Dates = days
365days

Explanation
Explanation

Firstly the
Firstly the two
two dates
dates are
are received
received in in dd,mm,yy
dd,mm,yy format.
format. Then
Then
the function
the function daysinmonth()
daysinmonth( is called
) is called to
to find
find out
out number
number of of
days in
days in the month ml
the month m l ofyearyl.
of year y l . Nextly,
Nextly, through
through thethe indefinite
indefinite
while
while loop
loop the variable days
the variable days isis continuously
continuously incremented.
incremented. It It
counts the
counts the number
number of of days. If d
days. If dll exceeds
exceeds the days in
the days in a month,
a month,
then we
then we go go to
to the
the next
next month
month byby incrementing
incrementing ml, m l , and
and if
if ml
ml
exceeds 12
exceeds 12 then
then we
we gogo to
to the
the next year's first
next year's first month. This
month. This
counting
counting goesgoes on
on tili
till we
we reach
reach the
the second
second date.
date. This
This happens
happens
when d
when dll equals
equals d2,
d2, mmll equals
equals m2
m2 and yl equals
and yl equals y2.
y2. When
When this
this
194
194 Exploring C
Exploring C

happens the
happens the control comes out
control comes out of
of the
the loop
loop by
by executing
executing break
break
and prints out
and prints out the
the difference
difference in
in dates stored in
dates stored in the
the variable
variable
days.
days.
6
Datatypes

The Building blocks


Building blocks
or
II
or an
nn all

of
all the
int and
int
the earlier

unsigned char,
earlier chapters
chapters we
float. These
and Ooat.
of several
These primary
types. For
several types.
an unsigned char, an
we used

For example,
an int
used the

example, aa char
int could
could be
the primary
primary data

char could
be aa short
could be
short int
int or
data types
datatypes themselves
primary datatypes
types char,
themselves could
be aa signed
char,
could be
signed char
or aa long
be
char
int, or
long int, or aa
real could
real could bebe aa Ooat,
float, aa double
double oror aa long
long double.
double. While
While storing
storing chars
chars
and ints,
and the highest
ints, the highest bit is always
bit is always usedused for
for storing
storing thethe sign
sign of the
of the
number.
number. What What if if we
we know
know that
that the
the value
value stored
stored inin an
an integer
integer or or aa
character variable
character variable is is never
never going
going toto be
be negative
negative (( for
for example
example the the age
age
of aa person
of person )1 )? In
In such
such cases
cases there
there isis no
no point
point in
in wasting
wasting thethe sign
sign bit.
bit.
This wastage
This wastage can can bebe avoided
avoided byby declaring
declaring thethe integer
integer oror the character
the character
variable in
variable in question
question as as unsigned.
unsigned. By By doing
doing this
this the
the range
range of the
of the
variable is
variable is almost
almost doubled,
doubled, since
since the
the sign bit is
sign blt no longer
is no longer used
used forfor
storing
storing thethe sign.
sign. The
The fact that the
fact that the ranges
ranges ofof different
different datatypes
datatypes are are
different means that
different means that the
the memory
memory occupied
occupied by by each
each would
would alsoalso be
be
different.
different. Figure
Figure 6.1 6.1 shows the ranges,
shows the ranges, bytes
bytes occupied
occupied and and the
the format
format
specifications
specifications used used for each datatype
for each datatype whenwhen they
they are
are used
used in printf()
in printf()
and scanf()) statements.
and scanf( statements.

While defining the various variables, variables, C allows the abbreviation of a


short
short intint to
to int,
int, and
and of
of long
long int
int to
to long.
long. Thus
Thus aa declaration
declaration short int
short int
jj is
is same
same as
as int
intj.j . Similarly
Similarly aa long
long intint k
k is
is same
same as
as long
long k. Sometimes
k.Sometimes
we
we come
come across
across situations
situations where
where the the constant
constant is
is small enough to
small enough to be
be
an int,
an int, but
but still
still we
we want
want to
to give
give itit as
as much
much storage
storage as
as aa long.
long. In such
In such
cases
cases we add the
we add the suffix
suffix 'L'
'L' or
or T'J' at
at the
the end
end of
of the number.
the number.
Datatypes-The
Datatypes- The Building
Building blocks
blocks 197

Datatype
Datatype Range
Range Bytes Format
Bytes Fonnat

signed
signed char
char -128 to +127
-128 to +127 11 %c
o/oe
unsigned
unsigned char
char 0Oto255
to 255 11 %c
o/oe
short
short signed
signed int
int -32768
-32768 toto+32767
+32767 22 %d
%d
short unsigned int
short unsigned int o0 to 65535
to 65535 22 %u
%u
long
long signed
signed int
int -2147483648
-2147483648 toto +2147483647
+2147483647 44 %ld
%ld
long
long unsigned
unsigned intint 0o to 4294967295
to 4294967295 44 %lu
%lu
float
float -3.4e38to+3.4e38
-3.4e38 to +3.4e38 44 %f
%f
double
double -1.7e308to+1.7e308
-1.7e308to +1.7e308 88 %lf
%If
long
long double
double -1.7e4932to+1.7e4932
-1.7e4932 to +1.7e4932 10
10 %Lf
%Lf

Figure
Figure 6.1
6.1 Datatypes
Datatypes in
in C
C

Storage
Storage Classes
Classes in
in C
C

Done
Done with
with constants,
constants, we we move
move on on toto C
C variables.
variables. Variables
Variables areare
nothing
nothing but
but aa fixed
fixed number
number ofof locations
locations reserved
reserved under
under aa specific
specific
name.
name. The
The mode
mode in in which
which aa variable
variable isis assigned
assigned memory
memory space
space isis
determined
determined byby its
its storage
storage class.
class. The
The computer
computer allows
allows access
access to
to two
two
types
types of
of locations:
locations:

(a)
(a) Memory
Memory
(b)
(b) CPU registers
CPU registers

Besides
Besides the
the location
location of
of the
the stored
stored variable,
variable, aa storage
storage class
class determines:
determines:

(a)
(a) What
What is is the
the default
default initial
initial value,
value, i.e.
i.e. the
the value
value assumed when
assumed when
aa variable
variable has
has not
not been
been initialised
initialised
(b) What
What isis the
the scope
scope ofof the
the variable,
variable, i.e.
i.e. in
in which
which functions
functions the
the
value
value ofof the
the variable
variable is available
is available
(c)
(c) What
What isis the
the scope
scope of
of the variable
the variable
198
198 Exploring
Exploring C

(d) What is the life of the variable


variable

A C variable
variable can have any of the following storage classes:
classes:

(a) Automatic storage class


Automatic
(b)
(b) Register storage class
Register storage class
(c)
(c) Static storage class
Static storage class
(d)
(d) External storage
External storage class
class

The features
The features of
of all
all the
the storage
storage classes
classes have
have been
been given
given in
in the
the follow-
follow-
ing figure.
figure.

Storage
Storage Location
I..ocation Default initial
Default initial Scope
Scope Life
Life
class
class value
value

Automatic
Automatic Memory
Memory Unpredictable
U~redictable or Local
or Local Till control
Till control isis
garbage
ga value
age value to
to within that
within that
block
block block
block
Register
Register CPU
CPU garbage value
garbage value Local
Local Till control isis
Till control
Registers
Registers to
to within that
within that
block
block block
block
Static
Static Memory
Memory Zero
Zero Local
Local Persists
Persists
to
to between
between
block
block various
various
function calls
function calls

Figure 6.2 Types


Figure 6.2 Types of
of storage
storage classes
classes

In the
In declaration of
the declaration of storage
storage class
class for
for aa variable,
variable, we mention the
we mention the
keyword for
keyword for that
that particular
particular class.
class. For
For instance,
instance, for assigning auto-
for assigning auto-
matic,
matic, register,
register, static
static and
and external
external storage
storage classes
classes to
to variables
variables a,
a, b,
b,
cc and
and dd respectively
respectively we
we should
should say:
say:

auto float
auto float aa ;;
register int bb;;
static irit cc ;
static
Datatypes-The
Datatypes ...The Building
Building blocks
blocks 199
199

extern
extem double d ;;

Tips on storage
storage classes

Here are a few


few things that you must keep in mind about
about storage
classes.
classes, .

By
By default, automatic
automatic storage class is assumed forfor variables
declared within a function, and an external storage class for
those declared outside. This is why we could afford
afford to drop the
mention of storage classes in the variables used as yet.

static
static storage class should be used only only when a program
requires the value of a variable to persist between different
function calls, like in recursive calls.

As there are only


only 14 CPU registers present, of which even less
may be at our disposal due to the microprocessor itself using
some, we must use them sparingly. Since the computer acces-
ses them faster than it accesses memory, their best utility
utility would
be
be as loop counters which have to be used a number of times.
However, if no registers are free
free at the time, auto
auto storage class
is assumed by the compiler and execution is carried on.

CPU registers are 2 bytes long. So their maximum range is


equal to that of an int. floats
Ooats cannot be stored in register
register
storage. Even if we say register,
register, float x or the like, auto
auto is
assumed
assumed for x.
for x.

extern
extern storage class should be used for only those variables
for:only
which are being used by almost all the functions
functions in ,the
the pro-
gram. By doing so you are spared the botherence of passing
and collecting
collecting them as function arguments. At the same time,
declaring all
declaring all the
the variables
variables as
as extents
externs is not advisable,
is not since
advisable, since
200
200 Exploring C
Exploring C

program, .
they would remain active throughout the life of the program,
wasting a lot of memory unnecessarily.
unnecessarily.

When you
When you don't
don't have any of
have any of the express needs
the express mentioned
needs mentioned
above, use auto
above, use auto storage
storage class.
class. These variables are
These variables are lost once
lost once
they are used
they ar~ used in
in aa function,
function, which
which isis perfectly
perfectly fine,
fine, as
as we no
we no
longer
longer need them.
need them.

In case
In case of
of aa conflict
conflict between
between aa global
global (( extern
extern) ) and
and aa local
local
variable of the same name, it is always the local variable that
is given
is given the
the higher priority.
higher priority.
Datatypes- TheBBaiding,
Datatypes-The ·,ildingblocks
bloclcs 201
201

Exercise
Exercise I
,
'

Whatwill
[A] What
[A] willbe
bethe
theoutput
outputofofthe
thefollowing
followingprograms:
programs:

( 1(1)
) main()
main()
{
{
int i ;
int i;
for =
( i 1 ; 100 ; itt )
for ( i = 1 ; 1 0 0 ; i + + )
printf ( "%d\n", i ) ;
printf ("%d\n", i ) ;
}
}

(2)
(2) main()
main()
{
{
char ch :
char c h ;
for ( ch==665
for (ch ch<=
5 ; ;ch <=2255 ch++ )
5 5 ; ;ch++)
printf ("%d%c\n", ch, cch
printf ( "%d %C\n·, ch, h )) ;;
1

(3)
(3) main()
main()
{
{
unsigned char ch ;
unsigned char c h ;
for (ch
for ( ch == 665
5 ;;ch
ch <=
<= 2255 ch++ )
5 5 ;; ch++)
printf ("%d
printf ( "%d %c\n",
%c\n",ch,
ch, cch)
h ) ;;
}

(4)
(4) main()
main()
{
{
unsigned int
unsigned int ch
ch == 00 ;;
for (ch
for ( ch == 6655 ;; ch
ch <=
<= 22555 5 ;; ))
printf ( "%d %c\n·,
printf ("%d %c\n", ch, ch, cch++
h + + )) ;;
}
}

(5)-
(5) main()
main()
{
{
float aa == 0.7
float 0.7;:
202
202 Exploring
Exploring CC

doumeb =
dOLltJIeb = 0.7; 0.7 ;
long
long double
double cc == 0.7;
d.7 ;
== bb ||IIbb ==
ifif ((aa == == c ))
printf
printf ("Condition
( "Condnion satisfied");
satisfied" ) ;
else
else
printf
printf ("Condition
( "Condnion not not satisfied");
satisfied" ) ;
printf(
printf("a"a ==%f %f bb == %lf
%If cc == %Lf,
%Lf, a,a, b,b, cc)) ;;
}

(6)
(6) main()
main().
{{
float =
float yY = 0.9;
0.9 ;
long double zz == 0.9;
long double 0.9 ;
if (y
if(y==z)== z)
printf ("Diamonds
printf ( "Diamonds are are forever...");
forever..." ) ;
else
else
printf ("forever...
printf ( ·~=rever... forever...
forever... forever");
forever" ) ;
}

(7)
(7) main()
{{
int ii;;
int
float 1;
float f;
double d;
double d;
long II;;
long
ii=I=1=d=100/3;
= I = f = d = 100/3;
printf ("%d%ld%f%lf\n",
printf ("%d %Id %1%l1\n",i,i ,1,1,d)
l , f , d ) ;;
f=i=d=I=100/3;
f = i = d = I = 100/3;
printf ("%f%d%lf%ld\n",U
printf ( "%1%d %If %Id\n", f, i, d, d , I)l ) ;;
l=i=d=f=100/3;
| = i = d = f = 100/3;
printf ("%ld%d%lf%f\n",l,
printf ( "%Id %d %If %t\n", I, i,i, d,d ,f)f ) ;;
d=I=1=i=100/3;
d = I = f = i = 100/3;
printf ("%lf%ld%f%d\n",
printf ("%11%Id %1%d\n', d, d , I,l ,f,f ,i)i ) ;;
}
Datatypes-The
Datatypes- The Building
Building blocks
blocks 203
203

((8)
8) main()
main()
{{
auto inti =
int i = 10
10?~
register int j = 20=
20;
printf ( "main's ii and
printf ("main's and jj are
are %d %d\n", i,i, j)j ) ;;
%d %d\n",
change()
change(); ;
printf ( "main's ii and jj are
printf ("main's are %d %d\n", i,i, j)j ) ;;
}}
change()
change()
{
{
auto int i = 100;
auto int i = 100;
=
register int j 200 ;
register int j = 2 0 0 ;
printf ( "change's i and j are %d %d\n", i, j) ;
printf ("change's i and j are %d %d\n", i, j ) ;
}

((9)
9) inti =
int i = 10, =
10,jj = 20,k
20, k = 30
30; =
main())
main(
{{
int =
intii = 1, =
1,jj = 2,
2,kk = 3;
3; =
= = =
( "i = %d j = %d k = %d\n", i, i,j, k)
printf ("i k);
val()
val(); ;
}}
val()
val()
{
{
printf ( "i == %
printf ("i %dd jj == %d
%dkk == %d",
%d", i,i ,j,j ,k)k ) ;;
}

((10)
10) int num
num;;
main()
main()
{{
int i, j;
j;
for ( ii = 1 ; i <= 3 ;; iffi++))
({
=
jj = increment()
increment();;
printf ( "j == %d\n",
printf ("j %d\n", j)j ) ;;
}}
204 Exploring C

printf ("num
( "num = %d", num)
num);
}}
increment(
increment!))
{
{
num++ ;
num++;
return ( num ) ;
return ( n u m ) ;
}}

(11)
(11) main()
main()
{{
int z, Y;
y;
z = recsum (( 1 ) ;
=
Yy = recsum (( 11 )) ;
=
printf (("z
"Z = %d\ny =
%c\ny = %d",
% d " ,Z,z ,y)
y);
}}
recsum (i). (i)
inti;
int i;
{{
static int sum
static int sum == 00 ;;
if ( i ;:= 3)
if(i==3)
return ( sum ) ;
return ( s u m ) ;
else
else
{
{
sum = sum + 10 ;
sum = sum+ 1 0 ;
iff ;
i++;
recsum (i) ;
} recsum ( i ) ;
}
}

((12)
12) inti = 0;
inti=Q;
main()
main{)
{{
printf ( "main's ii == %d\n.,
printf ("main's %d\n", ii )) ;;
iff ;
i++;
vval()
a l ( ) ;;
("main's i = %d\n", i)i ) ;
printf ("main's
v a l ( ) ;;
val()
Datatypes- The Building
Datatypes-The Building blocks
blocks 205

}}
val( )
val()
{
{
=
i 100;
iprintf
= 100;
( 'val's i = %d\n" Ii) ;
printf
itt ; ("val's i = %d\n", i ) ;
} i++;

((13)
13) main()
main()
{{
Y, s == 2, tt == 55 ;
int y,
yy=fun(stt);
= fun ( s + 1 ) ;
printf ( "s == %dt
printf ("s %d Y == %
%d t == %dy %d",
d \ sS,, tt,, y)
y ) ;;
}}
int 1=
intt = 8;
8;
fun (s)
fun ( s )
int s;
ints;
{{
s++ ;
s++;
ttt ;
t++;
return ( s t t) ;
return ( s + 1 ) ;
}

114) main()
1.14) main()
{{
double x,
double d == 4.4
X, d 4.4;;
int ii == 2, yy;;
xx=(y=d/i)*2;
= (y = d / i ) * 2 ;
printf ("x( 'x = %lfy
%If Y = %d\n", xX, , y)
y);
y = (x = d / i ) * 2 ;
y=(x=d/i)*2;
printf ("x( "X = %lfy
%If Y = %d\n", xX,, yy)) ; ;..
}

((15)
15) main()
main()
{
{
double x,
X, d =
= 5.0;
5.0 ;
206
206 Exploring C
Exploring

inty;
int y;
x = d*(x = 2 . 5 / d ) ;;
x=d*(x=2.51d)
( "X == %H\n",
printf ("x %lf\n",xj;
x) ;
x == dd*(y
* ( y ==((int) ) 2 . 5++1.5)
i n t2.5 1 . 5 );;
printf ("x
( "x == %If
%lfy Y ==%cf\n"
%d\n",x,y);
I X, y) ;
}

(16)
(16) main()
main()
{{
static int
static int cc ==55 ;;
printf (
printf ("c = %~n"
"C = %cf\n", c-c -)) ;;
I

if(c)
if(c)
main( )
mainQ
}

(17)
(17) main()
main()
i
{
int cc ==5;
int 5;
printf
printf Cc( "C =
= %dvl" c- ) ;
%d\n",c-);
I

if(c) .
if ( c )
main()
main();;
}

(18)
(18) int ii;;
main()
main()
{{
int j;
intj;
for(;;)
101'(;;)
{{
if (j = function (i))
if(j=Mction(i))
printfn %d\n\j);
printf ( "j ==%crv1" j) ;
I

elSe
else
break ;
break;
}}
}}
function ((x)
function X)
Datatypes-The Building blocks
Datatypes-TheBuilding blocks 207
207

intx;
int x;
{{
static int
static = 22 ;;
int vv =
v--
v--; .
,
retum(v-x);
return(v-x);
}}

(19) mairrO
main()
{{
longnum
long = 2;
num =2;
short n = 2 ;
shortn=2;
signed no =
signed = 22 ;
( "num =
printf ("num = %ld = %d no
%Id n = no ==%d",
%d", num,
num,n,n,no)
no);;
}}

(20) main()
(20) main()
{{
char
char ch
ch == 122, ch1
ch1 =='z';
'z' ;
printf
printf ("ch = %c",ch);;
("ch = %c ", ch)
printf ("ch1 = %d", ch1
printf Cch1=%d", );
chl);
}}

(21) main()
main()
{{
unsigned int
unsigned = 252 5;;
int as =
unsigned b = 2255 ;
unsigned
long unsigned c =
long unsigned = 345L
345L;;
signed dd ==345L;
long signed 345L;
printf("a
prinlf % ubb == %u",
( "s = %u %u*,a,b);
a, b) ;
printf ("c
("C = %lu %W", c, d) ;
"Iu dd = %Id",
}
}

(22) main()
(22) main()
. {
{
printf ("in
( "in main i ==%d\n",
%d\n", ii);
);
fund();
func1() ;
208
208 Exploring
Exploring C
C

}}
=
int i = 5;
5;
func1()
func1()
{{
printf ("In
printf ( "In fund
func1 ii == %d\n",
%d\n", i)i ) ;;
}}

(23) main()
main()
{{
register float rr == 3.14
register float 3.14;;
. register double yy == 3.4
register double 3.4;;
printf ( "r == %fy
printf ("r %f Y == %%If",
l f , rr,, yy)) ;;
}

((24)
24) main()
main()
{{
auto int
auto int ii== 100;
100 ;
printf ( "i = %d\n",
printf ("i = %d\n",i); i) ;
{
{
=
int ii = 11 ;;
int
printf ( Hi= %d\n·, i) ;
printf ("i = %d\n",i);
{
{ i += 1 ;
iprintf
+ = 1 ;( "i = %d\n", i) ;
prinrf("i = %d\n",i);
}}
printf ( "j == %d\n",i);
prir}tf ("i %d\n", i) ;
}}
printf ("i =
( "i = %d\n",i);
%d\n", i) ;
}

((25)
25) ii = 0;
0;
main()
main( )
{{
printf ("in
( "in main i = %d\n", i ) ;
i++;
itt ;
vval()
a l ( ) ;;
Datatypes-TheBuilding,
Datatypes-The blocks
Building blocks 209
209

printf("in
printf ( "inmain =%dln·, i )i);
maini =i %d\n", ;
}
}
val()
val()
{
{ int i = 100;
inti = 100;
~(intf( 'in val i = %d\n·, i) ;
printf
itt ; ('in val i = %d\n", i ) ;
} i++;
}

(26) Which
(26) Whichofofthe
thefollowing
followingwould
wouldwork
work faster?
faster?

(a)
(a) main()
main()
{
{
registerint
register inti;I:
for ( i = 1 ; ;i i<=
for ( i = 1 100 ;i++)
<= 100; itt )
printf ( "%d\n",
printf("%d\n",i); i ) ;
}
}

(b)
(b) main()
main()
{
{
auto int i;
auto int i;
for ( i = 1 ; i <= 100 ; itt )
for ( i = 1 ; i < = 1 0 0 ; i + + )
printf ( "%dln·, i ) ;
printf("%d\n",i);
}
}

[B]
[B] Attempt the
Attempt the following:
following:

(1)
(1) For
For every
every non-zero
non-zero odd
odd number
number there
there exist
exist two
two consecutive
numbers
numbers which
which form
form aa pythagorian
pythagorian triplet.
triplet. For
For example,
example, 3, 3, 4,
4,
5 form
5 form a pythagorian triplet where 3
3 is an odd number, whereas
44 and 5 are
are consecutive numbers. Another Another example is is 9, 40,
40,
41.
41. Write
Write aa program
program toto find
find all
all such
such pythagorian
pytnagorian triplets
triplets for
for all
all
odd numbers in the range 1
odd numbers in the range 1 to 10. to 10.

(2) Square of 12 is 144. 21, which is a reverse of 12 has a square


441, which is same as 144 reversed. There are fewfew numbers
210
210 Exploring
ExploringCC

which have
which have this
this property.
property. Write
Write aa program
program to
to find out whether
find out whether
any more
any more such
such numbers
numbers exist
exist in
in the
the range
range 10
10 to
to 100.
100.
Datatypes-The
Datatypes- The Building
Buildirc blocks
blocks 211
211

Answers
Answers

Answers to [A]
[A]

(1)
(1) Output
Output

11
22

32767
32767
-32768
-32768
-32767
-32767

Explanation
Explanation

The usual form


The usual form of
of for
for loop
loop is
is as under:
as under:

for ((initialisation; condition;; increment)


in~ialisation; cond~ion

Observe the
Observe for loop
the for loop in in our
our program
program carefully.
carefully. Instead
Instead of of aa
condition,
condition, therethere is 100, aa truth
is 100, truth value.
value. To To begin with ii takes
begin with takes aa
value
value 1. After this
1. After this the
the condition
condition is is tested.
tested. Due
Due toto the
the presence
presence
of
of aa truth
truth value,
value, thethe execution
execution proceeds
proceeds to to printf(
printf(), which
), which
prints
prints out the value of i, i.e. 1. Then the control reaches i++., '.
out the value of i, i.e. 1. Then the control reaches
which
which increments
increments iito to 22 and
and then proceeds to
then proceeds to test
test the
the condition
condition
where
where it it finds
finds 100,
100, thethe truth
truth value.
value. Therefore,
Therefore, the control
the control
reaches
reaches printf()
printf( ) and and prints
prints outout 2.2. Once
Once again
again the
the increment
increment
and test is
and test performed and
is performed and then
then the new value
the new value ofof ii i.e.
i.e. 33 gets
gets
printed. This
.printed. This goes
goes on on indefinitely
indefinitely sincesince the
the condition
condition part is
part is
always going to
always going to be
be true,
true, irrespective
irrespective of of the
the value
value of of i. Once ii
i. Once
exceeds
exceeds the the integer
integer range
range of of +32767,
+32767, the the values
values from
from the the other
other
side of the range ( the negative side )
side of the range ( the negative side) are picked up. are picked up.
212
212 Exploring C
Exploring C

(2)
(2) Output
Output

65 A
65A
66
66BB

125}
125 }
1 2 6 --
126

-128
-128CC

--126
1 2 6 --
-125}
-125 }

-2
-1

65
65AA
66
66BB

Explanation
Explanation

What does
What does the
the declaration
declaration char
char ch ch do?
do? It
It reserves
reserves one
one byte
byte in
in
memory and
memory and associates
associates aa name
name ch ch with
with it.
it. Its
Its aa wrong
wrong notion
notion
that aa character
that variable stores
character variable stores aa character
character constant.
constant. This is
This is
because when
because when we we store
store an'
an 'A' in aa character
A' in character variable,
variable, what
what gets
gets
stored
stored isis the
the ascii
ascii value
value ofof 'A',
'A', i.e.
i.e. 01000001.
01000001. Decimal
Decimal
equivalent of
equivalent of this
this ascii
ascii code
code is is 65.
65. Thus,
Thus, storing
storing 'A'
'A' in
in aa
character variable
character variable isis as
as good
good asas storing
storing 6565 in it.
in it.

Now look
Now look at
at the
the for loop
loop and
and you
you would
would not
not be surprised to
be surprised to
find that
lind that ch
ch is
is being
being assigned
assigned aa value
value 65,65, even
even though
though it has
it has
been declared
been declared asas aa char.
char. Since
Since 65
65 is
is less
less than
than 255,
255, the condition
the condition
is satisfied
is satisfied and
and the control reaches
the control reaches the
the printf().
printf(). %d
%d prints
prints the
the
Datatypes-The
Datatypes-The Building
Building blocks
blocks 213

value stored in ch (i.e.


( i.e. 65 ) as an
an integer, whereas %c prints
the character corresponding to this value (i.e. (I.e. 'A' ). Then the
control proceeds to ch++ where ch is incremented to to 66 and
since
since the
the condition
condition isis satisfied,
satisfied, the
the printf()
printf( ) once
once again
again goes
goes to to
work,
work, this
this time
time printing
printing outout 66
66 and
and ''8'.
B ' . This
This goes
goes onon till
till ch
eh
reaches
reaclres 127.
127. After
After printing
printing 127
127 and
and its
its corresponding
corresponding charac-
charac-
ter,
ter, when ch++ attempts to increment it to 128, it falters. Why?
when ch++ attempts to increment it to 128, it falters. Why?
Because
Because aa char
char (( i.e.
i.e. 11 byte
byte)) can
can store
store numbers
numbers in in the
the range
range
-128
-128 to
to +127.
+ 127. Therefore
Therefore ch ch cannot
cannot take
take aa value 128, hence
value 128, hence thethe
value from the other side of the range i.e. -128
value from the other side of the range i.e. -128 is picked up, is picked up,
and
and tested
tested against
against 255.
255. Since
Since the
the test
test is
is satisified
satisified the printf()
the printf()
gets
gets executed.
executed. This
This goes
goes onon and
and on,
on, indefinitely,
indefinitely, because
because the
the
value
value ofof ch
ch would
would keep
keep oscillating
oscillating betwen
betwen -128 -128 to to +127
+ 127 and
and
hence
hence would
would never
never exceed
exceed 255.
255.

(3)
(3) Output
Output

65
65AA
€'66
6 BB

125}
1126-
26-

255
255

65
65AA
66
66BB

Explanation
Explanation

Like an ordinary char,


char, an unsigned
unsigned char
char is also 1 byte long.
But it has a bigger range ( 0 to 255 ), since unlike a char,
char, it
214
214 Exploring
Exploring C

doesn't sacrifice
doesn't sacrifice 11 bit
bit in
in storing
storing the sign of
the sign of the
the number.
number.
Through the
Through the loop
loop the ascii values
the ascii values and
and their
their corresponding
corresponding
characters get
characters get printed
printed from
from 6565 toto 255. Once ch
255. Once ch has
has become
become
255, and
255, printf() has
and printf() has been
been executed, the control
executed, the control reaches ch++
reaches ch++
and attempts to
and attempts to increment
increment ch ch to
to 256.
256. ch
ch being
being anan unsigned
unsigned
char
char cannot
cannot become
become 256
256 since
since its
its range
range is
is only
only 00 to
to 255, and
255, and
therefore
therefore becomes
becomes 0, 0, and
and the
the whole
whole procedure
procedure is is repeated
repeated all
all
over again. Thus,
over again. Thus, ch
ch keeps oscillating between
keeps oscillating between 00 to to 255
255 and
and
never becomes 256.
never becomes 256. So
So the
the condition
condition isis always
always satisfied
satisfied and
and
hence
hence this
this is
is an
an indefinite loop.
indefinite loop.

(4)
.(4) Output
Output

65 A
65A
6668
6B

125}}
125
1126-
26-

255
255

Explanation
Explanation

The for
The for loop
loop begins with 65
begins with 65 and
and goes
goes uptil
uptil 255,
255, printing each
printing each
of these
of numbers alongwith
these numbers alongwith theirtheir corresponding
corresponding characters.'
characters.
The incrementation of
The incrementation of ch
ch isis being
being done
done inin printf(
printf(). Since ++
). Since ++
comes after
comes ch, firstly
after ch, firstly its
its value
value would
would bebe used
used to to carry
carry out
out the;
the
printing, and
printing, then it
and then it would
would be be incremented.
incremented. Since
Since ch ch has been
has been
declared as
declared as an
an unsigned
unsigned int int there
there is
is no
no question
question of exceeding
of exceeding
the range, as
the range, as the range of
the range of an
an unsigned
unsigned int int is
is 00 to
to 65535.
65535.

(5)
(5) Output
Output

Condition not satisfied


satisfied
Datatypes-The
Datatypes- The Building
Building blocks
blocks 215
215

a == 0.700000
0.700000 bb==0.700000
0.700000cc==0.700000
0.700000

Explanation
Explanation

0.7 has NOTNOT been


been stored
stored in a, b and c,
band c, though
though apparently
apparently it
appears
appears so. What What actually
actually gets gets stored
stored in a, b bandand cc is
0.699999988,
0.699999988, 0.699999999
0.699999999 and and 0.7
0.7 respectively.
respectively. ThisThis is is be-
be-
cause
cause aa real
real number
number by by default
default is is always
always represented
represented as as aa long
long
double,
double, wh|ch
which occupies
occupies 10 10 bytes
bytes in in memory.
memory. Thus Thus 0.7 0.7 is is
represented
represented as as aa 10
10 byte
byte number
number in in memory.
memory. Now, Now, when
when this this
10
10 byte
byte number
number getsgets stored
stored in in aa 44 byte
byte float
float variable,
variable, cr cr an
an 88
byte
byte double
double variable,
variable, thethe precision
precision considerations
considerations forceforce thisthis
10 byte 0.7 to get stored as 0.699999988
10 byte 0.7 to get stored as 0.699999988 and 0.699999999 and 0.699999999
respectively.
respectively. Thus,
Thus, when
when it is tested
it.is tested whether
whether aa and and bb are
are equal,
equal,
or
or whether
whether b and cc are
band are equal,
equal, the
the condition
condition failsfails and 'Condition
and /Condition
not
not satisfied'
satisfied' gets
gets printed.
printed. However,
However, when when the the control
control reaches
reaches
printf( ), the output is once again 0.700000.
printf( ), the output is once again 0.700000. This is because This is because
the
the format
format specification
specification %f
%f converts
converts 0.699999988
0.699999988 to
to
0.700000,
0.700000, and and %lf
% If converts
converts 0.699999999
0.699999999 to to 0.700000.
0.700000.

(6)
(6) Output
Output

forever...
forever ... forever...
forever ... forever
forever

Explanation
Explanation

On
On first
first glance
glance youyou would
would be be surprised
surprised byby the
the output
output obtained.
obtained.
The
The reason
reason lies
lies in
in the
the fact
fact that
that inin the
the variable
variable y, y, 0.9
0.9 doesn't
doesn't get
get
stored.
stored: What
What is is stored
stored isis 0.899999976.
0.899999976. This This is is because
because in in C,
C,
any
any floating
floating point
point number
number is is represented
represented as as aa long
long double
double andand
aa long
long double
double is is 1010 bytes
bytes long.
long. Now,
Now, when
when thisthis 10
10 by!e
byte long
long
0.9
0.9 gets
gets stored
stored in in aa 44 byte
byte float
Ooat variable
variable y,y, due
due toto precision
precision
considerations
considerations what what getsgets stored
stored is is only
only 0.899999975.
0.899999976. As As
against
against this,
this, in
in zz exactly
exactly 0.90.9 gets
gets stored.
stored. Naturally,
Naturally, the the condi-
condi-
216
216 Exploring C
Exploring C

tion would
tion would fail
fail since
since contents
contents of
of y
y and
and zz are
are different. Hence
different. Hence
the none
the none too
too surprising
surprising output.
output.

(7)
(7) Output
Output

33 33
33 33 331000000
33100000033.000000
33.000000
33.000000 33 33.000000
33.000000 33 33.000000 33
33
33 33 33.000000
33 3;3 33.00000033.000000
33.000000
33.000000 33 33.000000
33.000000 33 33.000000 33
33

Explanation
Explanation

As seen
As seen in
in the output, the
the output, the answer
answer 33.333333
33.333333 isis never
never obtained.
obtained.
This is
This is because
because wewe are
are operating
operating on on two
two integers,
integers, 100
100 and
and 3.
3.
The result
The result of
of dividing
dividing (( for
for that
that matter
matter multiplying,
multiplying, adding
adding oror
subtracting ) integers
subtracting) integers is
is always
always another
another integer.
integer. In
In keeping
keeping with'
with
this rule, 100 / 3 is evaluated as 33.333333, but
this rule, 100 / 3 is evaluated as 33.333333, but the decimal'the decimal
part is
part is truncated
truncated before
before itit is stored in
is stored in any
any variable,
variable, be
be it
it an
an int
int
or aa Ooat.
or float.

In the
In first part,
the first when 100 / 33 is
part, when is assigned
assigned toto d,
d, 33.000000
33.000000 gets gets
stored. This
stored. This remains
remains as as it
it is
is when
when the
the value
value inin dd is' is stored
stored in
in f,f,
aa Ooat.
float. When
When thisthis Ooat
float value
value is is assigned
assigned toto I,1, itit is
is stored
stored after
after
demoting it
demoting it to
to 33,
33, aa long
long integer.
integer. Lastly,
Lastly, 33
33 isis again
again stored
stored in
in
i, an
i, an int.
into The
The first
first output
output displays
displays these values.
these values.

The second
The second part
part stores the result
stores the result in
in I,
1, d,
d, ii and
and f,f, in
in that
that order.
order. I1
collects 33,
collects 33, which
which isis interpreted
interpreted as as 33.000000
33.000000 by by the
the double
double
variable d.
variable d. When 33.000000 is
When 33.000000 is assigned
assigned to int variable
to int variable i,i, i« is
it is
demoted to
demoted 33 and
to 33 and then
then stored. Finally, 33
stored. Finally, 33 is is promoted
promoted to to aa real
real
number 33.000000
number 33.000000 whenwhen assigned
assigned to to f.

The third
The third and
and fourth parts of
fourth parts of the
the program
program can
can easily be
easily be
evaluated similarly,
evaluated similarly, keeping
keeping track of what
track of what type
type of
of variable
variable is
is
being.used.
being.used,
Datatypes-The Building blocks
Datatypes-TheBuilding blocks 217
217

(8)
(8) Output
Output

main's i and j are 1020


1020
change's i and j are 100 200
main's i and j are 10 20

Explanation
Explanation

ii and
and jj are
are declared
declared inin maine
main().) to to have
have an
an auto
auto and
and register
register
storage classes
storage respectively. The
classes respectively. The first printf()) outputs
first printf( outputs their
their
values
values asas 10
10 and
and 20,
20, and
and then
then the
the function
function change()
change( ) is called.
is called.
In
In change(),
change(), ii andjand j are
are again
again initialised
initialised to
to 100
100 and
and 200.
200. But
But
this pair of
this pair of ii and
andjj has
has got
got nothing
nothing to to do
do with
with the
the pair
pair used in
used in
main().
maine ). Initialising
Initialising this
this pair
pair to 100 and
to 100 200 doesn't
and 200 doesn't change
change
the values of
the values of the
the pair
pair used
used in
in maine
main( ). ). This
This is
is evident
evident from
from the
the
output of the second printf() in main(). In other
output of the second printf( ) in main(). In other words, the words, the
auto
auto and
and register
register storage
storage class variables are
class variables are local
local to the
to the
function in which they are defined, and are not
function in which they are defined, and are not known to any known to any
other function. Hence,
other function. Hence, they
they cannot
cannot be be modified
modified by by any other
any other
function.
function.

(9)
(9) Output
Output

ii=1j=2k=3
= 1 j=2 k= 3
i = 10 jj = 20 k = 30
30

Explanation
Explanation

If i,i, jj and
If and k have
have been
been defined
defined once
once on
on top
top of main( ),
of maine is
), is
redefining
redefining themthem again
again inside
inside maine
main()) allowed?
allowed? Yes, because
Yes, because
the
the twotwo sets
sets ofof i,
i, jj and
and k are
are two
two totally
totally different
different sets
sets of
of
variables.
variables. The The ones
ones defined
defined outside
outside main(
main()) are
are global
global vari-
vari-
ables,
ables, whereas those defined
whereas those defined inside
inside main()
main() are
are local
local variables.
variables.
Global
Global (( extern)
extern ) variables
variables are
are available
available to
to all
all functions.
functions. So
So
this
this leads
leads to
to aa conflict
conflict asas to
to which
which variables'
variables' values
values should be
should be
218
218 Exploring C
Exploring C

printed main( ). This conflict


printed in main( conflict is resolved
resolved by giving
giving
preference to
preference local variables
to local variables over
over the
the global variables. There-
global variables. There-
fore,
fore, the
the printf()
printf() in
in main()
main() would
would print
print out
out 1,2
1,2 and
and 33 whereas
whereas
the
the one
one in
in val()
val( ) prints
prints out
out 10,
10, 20
20 and
and 30.
30.

(10)
(10) Output^
Output.

1j ==11
j=2
j=3 3
num =3
nurn =3

Explanation
Explanation

Since num
Since num hashas been
been declared
declared outside
outside all
all functions,
functions, its storage
its storage
class is assumed
class is assumed to to be
be extern,
extern, andand its
its initial
initial value
value is
is assumed
assumed
to be 0. Through the for
O.Through fo~ loop, when increment()
inerement( ) is called for
the first
the time, num
first time, num is incremented to
is incremented to 11 and
and this
this value
value isis
returned, to
returned, be collected
to be collected inin j.
j . This
This value
value isis then
then printed
printed out out
through the printf().
through the printf(). Subsequent
Subsequent calls
calls to
to increment) through
inerement() through
the for
the for loop
loop would
would increment
increment num num every
every time
time and
and return this
return this
incremented value, only
incremented value, only to
to be
be printed
printed through
through thethe printf(
printf().).
Finally, the value
Finally, the value of
of num
num is is printed
printed inin main().
maine ). Note
Note that num
that num
is available to
is available to both
both the
the functions:
functions: main()
maine ) as as well
well as incre-
as inere-
ment( ).
ment

(11) Output
(11) Output

= 20
zz=20
y = 40
y=40

Explanation
Explanation

When recsum()) is
When recsum( is called
called from main()) for
from maine for the
the first
first time,
time, aa
value 11 gets
value gets collected
collected in
in variable
variable ii in
in the
the function
function recsum(
recsum( ).).
Datatypes-The
Datatypes-The Building
Building blocks
blocks 219

In recsum
recsum(( ), ), the
the variable
variable sumsum has has been
been declared
declared as as static,
static,
therefore it is initialised during the first call call to recsum()
recsum() to aa
value
value 0. O. First
First time
time around,
around, the the condition
condition (( ii == == 33 )) fails,
fails,
therefore
therefore sum
sum is is incremented
incremented to to 10,
10, ii is
is incremented
incremented to to 22 and
and
once
once again
again recsum(
recsum( )) is is called
caJled withwith ii equal
equal to to 22 -- this
this time
time
recursively.
recursively. Once
Once again
again the
the condition
condition fails
fails and
and sum
sum is is incre-
incre-
mented
mented to to 20,
20, ii to
to 33 and
and again
again aa recursive
recursive call call is
is made,
made, this
this time
time
with
with ii equal
equal to
to 3.3. Now
Now thethe condition
condition in in if is satisfied,
iris therefore
satisfied, therefore
the
the latest
latest value
value of of sum,
sum, i.e.
i.e. 20
20 isis returned
returned to to main(),
main( ), wherewhere itit
is
is collected
collected inin the
the variable
variable z.z.

Note that even though recsum()


recsum( ) is called several times, only only
during the first call sum is initiated to 0. O. During all subsequent
subsequent
calls
calls the
the declaration
declaration ofof sum
sum isis ignored,
ignored, andand the
the value
value of
of sum
sum
last
last time
time around
around is
is used
used in
in calculations.
calculations. This
This is
is because
because sum's
sum's
storage
storage class
class has
has been
been defined
defined as as static.
static. This
This is
is once
once again
again
proved
proved when
when recsum()
recsum() is is called
called from
from main()
main() thethe second
second time
time
(( yy = recsum
recsum (( 11)) ). The last
).The last value
value ofof sum,
sum, i.e
i.e 20
20 is
is used
used in
in
further calcualtions involving sum, resulting in y printing
further calcualtions involving sum, resulting in y printing out out
as
as 40.
40.

(12) Output
Output

main's i = 00
val'si =
val's i = 100
main's i = 101
101
val's =
val's ii = 100
100

Explanation
Explanation

To begin with, i is assumed as ah an extern


extern storage class variable,
as it is defined outside all functions. When the first printf()
printf() in
main()
maine ) is executed,
executed, i is 0. Next, i is incremented to 1 and the
O.Next,
function val()
val() is called. In val(),
val(), i is reinitialised to 100. This
value
value is is printed
printed out and ii is
out and is incremented
incremented to to 101.
101. When
When thethe
control
control goes
goes back
back to
to main(),
main,( ), the
the second
second printf()
printf( ) prints
prints out
out the
the
220
220 Exploring
Exploring C

latest val
value val() gets called,
ue of i, i.e. 101. After this once again val() called,
where ii is
where reinitialised to
is reinitialised to 100
100 and
and then
then printed out.
printed out.

All this
All this goes
goes toto highlight
highlight one
one fact
fact -- once
once aa variable
variable is
is declared
declared
as
as extern
extern it is available
it is to all
available to all the
the functions
functions in in the
the program
program and
and
hence can be
hence can easily manipulated
be easily manipulated in in any
any of
of the functions.
the functions.

(13) Output
(13) Output

ss=2t=5y=17
= 2t = 5y = 17

Explanation
Explanation

When fun(
When fun( )-is called, 77(i.e.s
loiscalled, (i.e. s ++ t)
t)is passed to
is passed to itit and
and isis collected
collected
in
in the
the variable
variable s. s. In
In fun(),
fun( ), ss isis incremented
incremented to to 88 whereas
whereas t, t,
which
which is an external
is an external variable
variable with
with an initial value
an initial value 8, 8, isis incre-
incre-
mented
mented to to 9.
9. The return statement
The return statement then then returns
returns the the sum
sum of of ss
and
and t,t, i.e.
i.e. 17,
17, which
which is is collected
collected in in main(
main()) in in the the variable
variable y. y.
Note that since s and t have been declared
Note that since sand t have been declared inside main( ) they inside main() they
are
are local
local variables.
variables. As As aa result,
result, changing
changing the the value
value of of ss in the
in the
function
function fun( fun( )) does
does notnot have
have any
any effect
effect onon the
the valuevalue of of ss in
in
main().
main( ). What
What aboutabout thethe effect
effect of of changing
changing the the value
value of of tt in
in
fun( )? This also will not have any effect on
fun( )? This also will not have any effect on the value of t in the value of t in
main().
maine ). ThisThis is is because
because herehere wewe havehave two
two variables
variables with with the
the
same name t.
same name t. Therefore
Therefore in in main()
main() when when wewe useuse t, t, it
it is always
is always
the local tt which
the local which gets gets aa priority
priority above
above thethe global
global t. Hence, even
t. Hence, even
though t is incremented to 9 in fun(), in main()
though t is incremented to 9 in fun(), in main() while printing while printing
out the value
out the value of of t,
t, its
its the
the local
local tt with
with aa value
value 55 that that isis used.
used.

(14) Output
(14) Output

x == 4.000000y
4.000000y ==22
x == 2.200000
2.200000yY ==44

Explanation
Explanation
Datatypes-The Building blocks
Datatypes-TheBuilding blocks 221
221

Let us analyse
analyse ths
the first expression
expression step
step by step
step after replacing
replacing
the values
values of the variables
variables in the expression.
expression.

xx == ((y
y ==4.4/2 )*2
4.4/2)*2
x= = (y
(y = 2.2)*2
= 2.2 )*2
xx=2*2
= 2*2
X =4
x=4

Note
Note that 2.2 is demoted
demoted to 22 while
while storing
storing itit in
in y,
y, since yy is
is an
an
integer
integer variable
variable and
and hence
hence can
can store
store only
only an
an integer
integer constant.
constant.

Onto
Onto the
the secondexpression
second-expression now.
now.

yy=(x=d/i)*2
= (x = d / i ) * 2
yY == ((xx == 2.2)
2.2)*2
,\ 2
yY == 2.2*2
2.2* 2
yY == 4.4
4.4

While
While storing
storing 4.4
4.4 in
in y,
y, itit is
is demoted
demoted to
to 4,
4, since
since yy is
is an
an integer
integer
variable.
variable.

(15) Output
(15) Output

xx == 2.500000
x=15.000000y
x = 15.000000y == 33

Explanation
Explanation

What
What follows
follows isis aa step
step by
by step
step evaluation
evaluation ofof the
the expressions
expressions
with
with the
the variables
variables being
being replaced
replaced by
by the
the values
values stored
stored in
in them.
them.

xx == d*(x
d * (x = 2.5/
2.5/d)
d)
5.0 * ( x = 2.5/5.0
xx == 5.0*(x 2.5/5.0))
xx== 5.0*(x
5.0 * (x == 0.5)
0.5)
xx==2.5
2.5
222
222 Exploring C
Exploring C

Let us
Let us similarly
similarly evaluate
evaluate the
the second expression:
second expression:

x == dd*(y
* (y ==( (int)
int) 2.52.5+ 1.5)
+ 1.5)
xx == 5.0
5.0*(y
* (y ==((int)2.5+1.5)
int) 2.5 + 1.5)
x = 5.0*(y = 2+1.5)
x=5.0*(y=2+ 1.5}
x == 5.05.0*(y
* (y ==3.5)
3.5)
x == 5.0"
5.0*33
xx == 15.0
15.0

What does
What does the expression (int)
the expression ( i n t ) 2.5 do?
do? It
It casts the value
casts the value 2.5
2.5
as an
as an integer.
integer. This
This process
process is
is often
often called typecasting and
called typecasting and it can
it can
be applied
be applied to any datatype.
to any datatype. For
For example,
example, (long
( long) ) 123
123 would
would
cast 123 as a
cast 123 as a long integer.
integer.

(16) Output
(16) Output

c=5
c=5
c=4
c=4
c=3
c=3
c=2
c=2
cc=1
=1

Explanation
Explanation

When printf()
When printf() is is executed
executed forfor the
the first time, firstly
first time, firstly value
value ofof ce
(i.e.5 ) is
(i.e.5) is printed
printed and and then
then cc is
is decremented
decremented to to 4.
4. The
The condition
condition
in if
in evaluates to
if evaluates to true
true since
since 44 is is aa truth
truth value
value (( recall
recall that
that any
any
non zero value is a truth value ), hence main()
non zero value is a truth value ), hence maine ) is called once is called once
again. But
again. But this
this time
time ce is
is not
not reinitialised
reinitialised to to 5,
5, since
since its storage
its storage
class has
class has been
been declared
declared as as static.
static. Thus
Thus thethe control
control jumps
jumps
straightaway to
straightaway to printf(),
printf( ), where
where the the current
current value
value of of c,
c, i.e.
i.e. 44
gets printed, c gets decremented to
gets printed, c gets decremented to 3 and once again the3 and once again the
condition is
condition tested. Since
is tested. Since this
this time
time alsoalso the condition evaluates
the condition evaluates
to true,
to true, and
and maine
main( )) getsgets called
called yet yet again.
again. This
This process
process is is
repeated till
repeated till cc becomes
becomes 0, 0, wherein
wherein the the condition
condition fails
fails and
and hence
hence
main(
main() ) doesn't
doesn't get get called.
called.
Datatypes- The Building
Datatypes-The Building blocks
blocks 223
223

What is to be understood from this program is that the value


of the static
static storage class variable is initialised only once and
thereafter the latest value of the variable persists between
different function calls.

(17) Output
(17) Output

c=55
c =

c=55
C =

c=55
c =

Explanation
Explanation

Unlike the previous program, here variable c has not been


defined as static,
static, and hence it is initialised to 5 every time
main()) gets
maine gets called.
called. Thus
Thus when
when printf(
printf()) isis executed
executed for for the
the
first
first time,
time, asas cc has been initiated
has been initiated toto 5,
5, it
it gets
gets printed
printed out and
out and
then —reduces
then •• reducesitittoto4.4.Now,
Now,the thecondition
conditionisissatisfied
satisfied(since
( sincecc
is
is non-zero
non-zero ), ), therefore main( )) gets
therefore maine gets called
called again.
again. But
But the
the
moment
moment control reaches int
control reaches =
int cc = 5,
5, this
this statement
statement gets executed
gets executed
and
and cc isis reset
reset to
to 5.
5. Once
Once again
again 55 gets
gets printed,
printed, cc gets decre-
gets decre-
mented, condition gets satisfied and main() gets
mented, condition gets satisfied and maine ) gets called. Thus called. Thus
cc never
never becomes
becomes 00 and and hence
hence thethe condition
condition never
never becomes
becomes
false.
false. In
In other
other words,
words, the control falls
the control falls in
in an
an indefinite
indefinite loop.
loop.

(18) Output
(18) Output

ji == 1i

Explanation
Explanation

In this program, having declared ii as an extern


extern variable, the
control enters the for loop in main().
main(). Here function()
function() is called
224
224 Exploring C
Exploring C

with aa value
with value 0. O. InIn function(
function^ ) this this value
value is is collected
collected in in the
the
variable x.
variable Next vv is
x, Next is initiated
initiated to to 2, decremented to
2, decremented to 11 and
and then
then
the difference
the difference (v (v -- xx )),, i.e.
i.e. 1,1, is
is returned
returned to to main(),
main(), wherewhere it is
it is
collected in
collected in the
the variable
variable jj.. SinceSince jj isis 1,
1, the
the condition
condition is satisfied
is satisfied
and j's
and j ' s value
value gets
gets printed.
printed. Since Since the the for
for loop
loop is is an indefinite
an indefinite
loop, once
loop, once again
again the the control
control reaches
reaches the the ifif statement.
statement. From From
here, again
here, again aa call
call to function()) is
to function( is made,
made, with with ii equal
equal to to O.
0. In
In
function()
function() the the latest
latest value
value of of v,
v, i.e.
i.e. 11 isis decremented
decremented to to 00 and
and
the difference
the difference (( 0 0 -- 00 )) is is returned
returned to to maine
main( ), ), where
where it it is
is
collected in j . Now the condition fails,
collected in j. Now the condition fails, since j is 0, and the since j is 0, and the
control reaches
control reaches the else block.
the else block. Here
Here the the break
break takes
takes the control
the control
outside the
outside for loop
the for loop andand since
since 'l}ere
'here are
are no statements outside
no statements outside
the loop,
the loop, the execution is
the execution is terminated.
terminated.

(19) Output
(19) Output

num = 22 nn =
num = = 22no = 22
no =

Explanation
Explanation

Each of
Each the variables
of the variables num, and no have
num, n and have been
been assigned
assigned aa value
value
2, which
2, which is getting printed
is getting printed out through the
out through the printf(
printf( ).). That's
That's
hardly aa surprise.
hardly surprise. What
What isis to
to be
be appreciated
appreciated here
here is
is the com-
the com-
pactness C
pactness C offers
offers inin the
the variable
variable declarations.
declarations. Instead
Instead ofof
declaring signed
declaring signed long
long int num we
int num we cancan get
get away
away with long
with long
num. Similarly, instead
num. Similarly, instead of
of short
short signed
signed int
int nn we
we are allowed
are allowed
to use
to short n.
use short n. Likewise,
Likewise, wewe can
can use signed no
use signed no instead
instead of
of short
short
signed int no.
signed int no.

(20) Output
(20) Output

ch
ch = zch1
:1! ch1 ==122
122

Explanation
Explanation
Datatypes-The Building blocks
Datatypes- The Building blocks 225
225

Does chi =
chl = 'z'
V really store the character 'z' chl? Not really.
'z' in chi?
What is stored in chlchi is the ascii value of ''z',
z \ which is 122.
Understand that a char
Understand char variable never holds characters. It can
hold only values in the range -128 to +127.
+ 127. Once this fact sinks
in, the output of the program can be easily understood. The first
printf( ) prints out a character corresponding to the value
printf(
stored
stored inin ch,
ch, whereas
whereas the
the second
second printf(
printf( )) prints
prints the
the value
value
stored in chi.
stored in chl.

(21) Output
(21) Output

a == 25
25bb==2525c C = 345
= 345 d =d345
= 345

Explanation
Explanation

The first
The first two
two declarations
declarations make
make oneone fact
fact very
very clear
clear -- while
while
declaring aa variable
declaring variable to
to be
be of
of the
the type unsigned int,
type unsigned int, the
the int
int can
can
as well be dropped from the declaration. Observe
as well be dropped from the declaration. Observe that in the that in the
next
next two declarations too
two declarations too the
the word
word int
int has
has been
been dropped.
dropped. In In
these
these declarations
declarations aa capital
capital L L occurs
occurs after
after 345.
345. This ensures
This ensures
that
that 345
345 isis treated
treated as
as aa long
long int.
int. In
In place
place of
of aa capital
capital LL aa lower
lower
case 1 is also acceptable. Also observe the format specifications
case I is also acceptable. Also observe the format specifications
used in printf():
used in printf(): %u
%u forfor an
an unsigned
unsigned int, %luforan
int, %Iu unsgined
for an unsgined
long int and
long int and %Id
%ld for
for aa long
long signed
signed into
int.

(22) Output
(22) Output

Error message:
Error message: Undefined
Undefined symbol
symbol V
'i' in function main
in function main

Explanation
Explanation

Note that here i has been declared in between


beWeen the functions
functions
main() funcl().). Since this declaration falls outside both
maine ) and funel(
the functions its
the functions its storage
storage class
class is
is assumed
assumed to
to be
be extern.
extern. Thus
Thus ii
should be available
should be available to both the
to both the functions.
functions. However,
However, since
since ii
226
226 Exploring C
Exploring C

physically occurs
physically occurs after
after maine
main( ), ), it
it is
is not available to
not available to main(
main( ). ).
Hence the
Hence the error
error message. What if
message. What we don't
if we don't want
want to
to shift
shift the
the
declaration to
declaration to top
top of main()) and
of maine and yetyet want
want to
to make
make ii available
available
to main()?
to main()? To To achieve
achieve this,
this, the
the declaration
declaration extern
extern inti;
inti; should
should
be made
be made inside
inside main().
maine ). This tells the
This tells the compiler
compiler that
that down
down thethe
line somewhere
line somewhere ii has
has been
been declared
declared outside
outside all
all functions.
functions. If
If you
you
run the
run the program with this
program with this change
change bothboth printf()s
printf( )s would
would output
output
5.
5.

(23) Output
(23) Output

r = 3.140000
3.140000 Yy = 3.4r.-)OOO
3.400000

Explanation
Explanation

The register
The register storage
storage class
class variables
variables areare stored
stored in CPU
in CPU
registers. Since
registers. Since CPU
CPU registers
registers are
are 22 bytes
bytes long,
long, how
how can
can aa float
float
or aa double
or double variable
variable bebe declared
declared toto have
have aa register storage
register storage
class? Should
class? Should the compiler not
the compiler not flash
flash an
an error
error message?
message? It It
doesn't, because it doesn't expect you to know the details
doesn't, because it doesn't expect you to know the details about about
what are
what CPU registers,
are CPU registers, how
how many
many bytes
bytes long
long are
are they,
they, etc.
etc.
Hence it
Hence it makes
makes this
this concession.
concession. However,
However, internally
internally itit as-
as-
sumes auto
sumes auto storage
storage class
class for
for these
these variables
variables and
and proceeds
proceeds with
with
the execution.
the execution.

(24) Output
(24) Output

100
i = 100
i == 1
=2
i =2
i == 22
i == 100
100

Explanation
Explanation
Datatypes-The Building blocks
Datatypes- The Building blocks 227
227

In the
In the outermost
outermost block block (( aa block
block isis statements
statements within within aa pair
pair of
of
braces ) the
braces) the variable
variable ii has has been
been declared
declared as as anan auto
auto storage
storage
class variable,
class variable, with with an an initial
initial value
value 100. This value
100. This value gets
gets printed
printed
through the first printf(). Then the control
through the first printf( ). Then the control reaches inside the reaches inside the
next block,
next block, where
where againagain ii is is declared
declared to to have
have aa value
value 1. This ii
1. This
is different,
is different, since
since itit has
has been
been defined
defined inside
inside another
another block.
block. The
The
value of
value this ii is
of this is then
then printed
printed out out through
through the the second
second printf(
printf().).
Inside the next block, this i is incremented to
Inside the next block, this iis incremented to 2 and then printed 2 and then printed
out. Then
out. Then the the control
control reaches
reaches outside
outside this block where
this block another
where another
printf()
printf() is is encountered.
encountered. This This printf()
printf() is is within
within the same block
the same block
in which the second i has been defined. Hence
in which the second i has been defined. Hence it prints out the it prints out the
value of this i, which is still 2. And now
value of this i, which is still 2. And now the control reaches the control reaches
outside the
outside the block
block in in which
which the the second
second ij has has been
been defined.
defined.
Therefore the
Therefore the second
second ii dies.
dies. TheThe first
first ii is
is however
however stillstill active,
active,
since
since the control has not gone out of the block in which it
the control has not gone out of the block in which has
it has
been
been defined. Hence the last printf( ) prints out the value of
defined. Hence the last printf( ) prints out the value of
this i,
this i, which
which is is 100.
100.

(25) Output
(25) Output

Error mesage: Declaration


Error mesage: Declaration needs
needs type
type or
or storage class
storage class

Explanation
Explanation

We get
We the error
get the message because
error message because we
we have neither mentioned
have neither mentioned
the type
the type nor
nor the
the storage
storage class
class of
of the
the variable
variable i.
i. Saying
Saying int ii = 00 =
would make
would the program
make the program work.
work. .

(26) Output
(26) Output

Same output for


Same output for both:
both:

1
22
33
228
228 Exploring
Exploring C
C

99
99
100
100

Explanation
Explanation

Which
Which of of the
the two
two programs
programs works
works faster
faster depends
depends on on the
the status
sta tus
of
of the
the CPU
CPU registers
registers at at the
the time
time of of program
program execution.
execution. If If the
the
CPU
CPU happens
happens to to be
be using
using all
all the
the 1414 registers,
registers, ii will
will not
not bebe
allotted
allotted aa register
register storage
storage class,
class, andand its
its storage
storage class
class will
will be
be
assumed
assumed to to be
be auto.
auto. In
In this
this case,
case, both
both the
the programs
programs willwill take
take
the
the same
same time
time to to run.
run. However,
However, if if we
we are
are lucky,
lucky, and
and the
the CPU
CPU
does
does allow
allow aa register
register atat our
our disposal,
disposal, the the first
first program
program will
decidedly
decidedly run run faster.
faster. This
This is
is so
so because
because registers,
registers, being CPU's
being CPU's
internal memory, are accessed faster than normal memory
internal memory, are accessed faster than normal memory
locations.
locations.

Solutions
Solutions to
to [B]
[B]

(1) Program
Program

main()
main( )
{{
unsigned int i, j, kk;;

for(i
for ( i = 1 ;; i <<== 99 ;; i = i + 2 )
{{
( i== 11 ; ; j++ )
for (j
for
{
{
k=j+1;
k=j + 1;
iiff (( ii **i i ++ ij ** ij ==
= = kk * kk ))
{{
("\n%u %u %u", i,i ,i,j ,k)k ) ;;
printf ("\n%u%u%u",
printf
break;
break;
Datatypes-The Building blocks
Datatypes- The Building blocks 229
229

}}
}}
}}
}}

Sample run
Sample run

1 32768
3276832769
32769
345
345
551213
1213
772425
24 25
994041
4041

Explanation
Explanation

Here iiis
Here is bei
being used for
ng used for the
the odd
odd nurnber
number whereas
whereas jj andand kk signi
signify
fy
the consecutive
the numbers. Since
consecutive numbers. Since ii represents
represents the the odd
odd number,
number,
it varies
it varies from
from 1 1 to
to 9
9 in
in steps
steps of
of 2. 2. If
If sum
sum of of squares
squares ofof ii and
andj j
equals the
equals the square
square ofof k,
k, then
then i,
i, j,j , kk forms
forms aa pythagorian
pythagorian triplet.
triplet.
The moment
The moment such such aa triplet is encountered
triplet is encountered it it is
is printed
printed out.
out. Note
Note
that i, jj and
that and kk have
have been
been declared
declared as as unsigned
unsigned ints.ints. This
This is
is
because the
because the range
range ofof such
such integers
integers is is 0
0 to
to 65535.
65535. In In this program
this program
we do
we do need
need aa range
range bigger
bigger than
than -32768-32768 to to +32767.
+32767.

(2)
(2) Program
Program

main()
main( )
{{
unsigned
unsigned long
long num,
num, rnum,
mum, square,
square, rsquare,
rsquare, n2,
n2, num2
num2;;
int d1, d2, d3, d4,
intd1,d2,d3,d4, d5; d5 ;

for (num
for (num == 10;
1 0 ; num
num <=
<= 100;
100; num++)
num++)
{{
num2 = num;
num2 num;
d1
d 1 == nnum2
u m 2%
% 110;
0;
230
230 Exploring C
Exploring C

num2/10;
num2 = num2/10;
n u m 2%
d2 = num2 % 10
10;
num2 = num2/10;
num2/10;
n u m 2%
d3 = num2 % 10
10;
num2 = num2/1
n u m 2 / 100 ;
num2%
d4 = num2 % 101 0 ,;
num2 == num2/10;
num2 num2/10;
d5
d5 == num2;
num2;

mum = d5 + d4 ** 10 + d3 * 100 + d2 * 1OOOL


rnum d1 * 10000L ;
1000L +.d1

(mum % 10 ==
while (mum = =0)
0)
rnum = rnum
mum m u m/10;
/10;

square = num * num


num;;
1r

rsquare = rnum * rnum


rnum;;

d1 = square % 10; 10;


square/10;
square = square /1 0 ;
d2 = square % 10; 10;
square/10;
square = square /10 ;
d3 = square % 10; 10;
square/10;
square = square /10 ;
d4 = square % 10; 10;
square/10;
square = square /1 0 ;
d5 = square;
square;
n2 = d5 + dd44 ** 10
10++ dd33 ** 100 + dd22 ** 1000L d1 * 1OOOOL
1000L ++d1 10000L;;

while ( nn22 % 10 ==
= =00 )
n2 = n 2 / 1 0 ;
n2=n2/10;

if ((rsquare
rsquare == n2 n2))
printf (("\n%lu", n u m)) ;
"\n%lu·, num
}}
}}
Datatypes-The Building blocks
Datatypes-The Building blocks 231
231

Sample run
Sample run

10
10
11
11
12
12
13
13
20
20
21
21
22
22
30
30
31
31
100
100

Explanation
Explanation

Within the for loop, firstly the digits of the number ((say, say, 1212))
are
are separated
separated out into variables
out into variables ddll through
through dS,d5, and
and then using
then using
these, the reversed
these, the reversed number
number (( saysay 2121)) is
is constructed
constructed and and stored
stored
in the variable
in the rnum. The
variable rnum. while loop
The while loop that
that follows
follows trims any
trims any
trailing zeroes from
trailing zeroes from this
this reversed
reversed number.
number. ThenThen squares
squares of of the
the
original number ( 12 ) and the reversed
original number ( 12 ) and the reversed number ( 21 ) arenumber ( 21 ) are
calculated.
calculated. TheThe set
set ofof statements
statements that that follow
follow segregate
segregate the the
digits of the
digits of the square
square of of the
the original
original number
number (( 144)144 ) and
and then
then
using these segregated
using these segregated digits,
digits, it
it constructs
constructs the the reverse
reverse of the
of the
square ( 441). The while loop then trims out any trailing
square ( 441 ). The while loop then trims out any trailing zeroes zeroes
that
that might
might be be present
present in in this
this reverse
reverse of square of
of \square original
of original
number.
number. Now Now if if this
this number
number is same as
is same as rsquare
rsquare calculated
calculated
earlier,
earlier, then
then the
the number
number in in question
question satisfies
satisfies the
the property
property andand
hence is printed
hence is printed out.out.

variables have been declared as unsigned


Note that some of the variables unsigned
long ints.
long ints. This
This is just to
is just to ensure
ensure that
that the
the range
range is
is not exceeded
not exceeded
while constructing
constructing the reversed numbers.
numbers. .
7
The
The CC Preprocessor
Preprocessor
T
T
source
he facility of Preprocessing is something which you do not
he
have with many other high level languages. As the name
suggests, the Preprocessor is a program that processes our
source program before passing it on for for compilation. Though the
facility is not an indispensable one, it is popular with C programmers
programmers
as it helps in better coding
coding' of a program. The commonly used
preprocessor directives are:

(a) Expansion
Macro Expansion
(b) File Inclusion
(c) Conditional Compilation
Compilation

Let us now understand these preprocessor directives one by one.

Macro Expansion
Macro Expansion

Here's
Here's a simple example illustrating the use of macro expansions.
expansions.

#defineNUM100
#define NUM 100
#defineSQUARE(x)(x*x)
#define SQUARE(x) (x * x)
main()
main(}
{{
int
int ii ==5;5;
f
The C
The C Preprocessor
Preprocessor 235
235

if ((SQUARE(i)
SQUARE(i) <= <= NUM
NUM))
printf ("Eat,
printf merry...");
( "Eat, drink and be merry...I ) ;

else
printf (("for
printf "for tomorrow
tomorrow you
you may have to diet!"
diet!");
);

The above
The above program
program would
wbuld output:
output:

Eat, drink and be


drink and be merry...

The first
The first two
two statements
statements in in the
the program
program are are called macro definitions.
called macro definitions.
They comprise
They comprise of of 'macro
'macro templates'
templates' NUM NUM and and SQUARE(x)
SQUARE(x) and and
their corresponding
their corresponding 'macro 'macro expansions',
expansions', 100 100 and
and (( xx •* xx ).
). During
During
preprocessing, the
preprocessing, the macro
macio templates
templates areare replaced
replaced byby their correspond-
their correspond-
ing macro
ing macro expansions.
expansions. The first macro
The first expansion is
macro expansion is aa simple
simple macro,
macro,
whereas the
whereas the second
second oneone is
is said
said to
to be
be taking
taking anan argument
argument x. x. ((Note
Note that
that
there is
there is no
no space
space between
between SQUARE
SQUARE and and (x)
(x) ).
). In
In our
our program,
program, we we .
have chosen the argument to be i, so the preprocessor
have chosen the argument to be i, so the preprocessor expands the expands the
macro in
macro terms of
in terms of i.
i.

Thus, before
Thus, before the
the program
program is sent to
is sent to the
the compiler,
compiler, the the preprocessor
preprocessor
replaces NUM
replaces NUM by by 100,
100, and
and SQUARE(i)by
SQUARE(i) by (i· (i * i).
i). The
The if statement
if statement
having been
having been rewritten
rewritten as
as if(
if( (i
(i •* i)i) <=
<= 100
100 ),), compilation
compilation proceeds
proceedsjust
just
as usual.
as usual.

File Inclusion
Inclusion

This directive
This directive causes
causes one
one file
file to
to be
be included
included in in another.
another. The presence
The presence
of aa #include
of #include statement
statement inin aa program
program causes
causes thethe entire
entire contents
contents ofof the
the
said file
said file to
to be
be inserted
inserted at
at that
that point
point in
in the
the program.
program. A A typical
typical use
use of
of
this feature
this feature would
would be to store
be to store frequently
frequently used
used functions
functions and
and macro
macro
definitions
definitions in in aa single
single file
file and#include
and #include it it in
in whichever
whichever file
file we want.
we want.

The file inclusion


The file inclusion directive
directive can
can be
be written
written in
in two
two ways:
ways:
236
236 Exploring C
Exploring C

fflnclude "ac"
#include ·ac· Thiscommands
This commandsthe thepreprocessor
preprocessortotolook
lookfor
forthe
thefile
file
a.c
a,c in the current directory as well as the specified
specified
list of directories mentioned in the search path that
might have been set up.

include
#include <ac>
eacs The file a.c
a,e is looked up only in the specified list of
directories.
directories.

Conditional Compilation
Conditional Compilation

The last on our list is conditional compilation using the preprocessor


preprocessor
commands #ifdef and #endif.
#endif. Saying

#ifdef LABEL
statement
statement 11 ;;
statement
statement 22 ;;
#endif

will
will ensure
ensure that
that statements
statements 11 and
and 22 will
will get
get compiled
compiled only
only ifif LABEL
has
has been
been #defined.
#defined If If LABEL
lABEL has has not
not been
been defined
defined asas aa macro,
macro, thethe
two
two statements
statements won't
won't bebe sent
sent for
for compilation
compilation at at all.
all. Conditional
compilation
compilation cancan bebe used
used toto make
make aa program
program portable.
portable. For For two
different
different makes
makes ofof computers,
computers, we we can
can write
write aa single
single program
program and
conditionally
conditionally compile
compile only
only the
the code
code pertaining
pertaining to
to either
either of
of the
the two
two
machines.
machines, The
The program
program would
would look
look like:
like:

.. main()
main()
{{
#ifdefPCAT
#ifdefPCAT
code for
code for aa PC/AT
PC/AT
#else
#else
code for aa PC/XT
code for PCIXT
#endif
#endif
code common
code common to to both
both the
the computers
computers
}}
The
TheCCPreprocessor
Preprocessor 237
237

Our
Our program
program would
would run
run smoothly
smoothly on
onaaPC/AT
PC/ATasaswell
well as
asaaPC/XT,
PC/XT,
depending
depending on
onwhether
whether PCAT
peAT has
hasbeen
been defined
definedor
ornot.
not.
238
238 Exploring
Exploring C
C

Exercise
Exercise

[A]
[A] What will be the output of
of the following programs:
programs:

(1)
(1) #define DEF
main()
main( )
{
{
int i == 2;
inti 2;
#ifdef DEF
( "square of ii == %d", ii** i)i ) ;;
printf ("squareof
#else
printf ( "i == %d·,
printf("i % d " ,i)i ) ;;
#endif
}}

(2)
(2) #defineNO
#define NO
#defineYES
#defineYES
main()
main( )
{
{
int i = 5, jj;;
iif(i>5)
f(i>5)
jj=YES;
= YES;
else
jj=NO;
= NO;
printf (("%d",j);
"%d", j ) ;
}}

(3)
(3) #defineMESS(m)
#define MESS( m) printf (("m")
"m" )
main()
main()
{
{
MESS( "But someWhere in my wicked miserable past..") ;
MESS( "But somewhere in my wicked miserable past..")
MESS( "there must have been a moment of truth!" ) ;
MESS( "there must have been a moment of truth!");
}}

(4) #defineGOTONEXTUNEprintf("\n")
#define GOTONEXTUNE printf( "\n")
The
The CCPreprocessor
Preprocessor 239
239

main()
main()
{{
printf ("It's
printf ( "It's better
better to
to keep
keep your
your mouth
mouth shut..")
shut.." ) ;;
GOTONEXTUNE;
GOTONEXTUNE;
printf ("..
printf ( ".. and
and have
have people
people think
think you
you are
are aafool..");
fool.." ) ;
GOTONEXTLINE;
GOTONEXTUNE;
printf ("..
printf ( "..than
than to
to open
open itit and
and remove
remove all doubt'" ) ;
all doubt!");
}}

((5)
5) #define
#define MESS(
MESS( m)
m) printf(
printf( "m")
"m" )
#define
#define GOTONEXTUNE
GOTONEXTUNE printf(
printf( "\n")
"\n" )
main()
main()
{{
MESS("A
MESS( galaxy of
"A galaxy of persons
persons were
were born
born on
on this
thisday ..") ;
day..");
GOTONEXTUNE;
GOTONEXTUNE;
MESS( "But
MESS( "But somehow
somehow youyou seem
seem to
to be the best!!")
be the best!!" ) ;;
}}

((6)
6) #define
#define ISUPPER(
ISUPPER( xx)) ((xx >=
>= 65
65 &&
&& xx <=
<= 90)
90)
#define
#define ISLOWER(
ISLOWER( xx)) ((xx >=
>= 97
97 &&
&& xx <=
<= 122)
#define ISALPHA(
ISALPHA( xx)) (ISUPPER(
( ISUPPER( xx)) ||IIISLOWER(
ISLOWER( x ) )) ..
main()
main( )
{{
char ch
char =
ch ='+';
'+' ;
ifif (ISALPHA(
( ISALPHA( ch c h )) ))
printf ("ch
printf ( "ch contains
contains an
an alphabet")
alphabet·) ;;
else
else
.
printf ("ch
printf ( "ch doesn't
doesn1 contain
contain an
an alphabet")
alphabet") ;;
}}

(7) #defineTHIS
#define THIS
#defineTHAT
#define THAT
main()
main()
{{
#ifdefTHIS
#ifdefTHIS
#ifdefTHAT
#ifdefTHAT
240
240 Exploring
Exploring C

printf (("Definitions digest");


"Definitions are hard to digest" );
#else
Heise
printf (("But forget");
"But once mugged up, hard to forget" );
#endif
}}

(8) #defineTHIS
Hdefine THIS
#defineTHAT
#define THAT
rnain( )
main()
{{
Hifdef
#ifdef THIS && THAT
prlntf ( "Defintions are hard to digest"
printf ("Defintions );
digest");
Heise
#else
printf (("But
"But once mugged up, hard to forget" );
forget");
Hendif
#endif
}}

(9)
(9) #Hdefine
d e f i n eMEAN(
M E A Na,( ab,
, bc,, cd,
, de)
, e )(( a ++bb + c + d + e)
e ) /5
/5
main())
main(
{{
int a, b,
int a, c, d,
b, c, d, e,e, mm ;;
a=1;
a =1
b
b =2;
= 2;
=3;
c = 3;
C
d
d -=4;
4;
e =5;
= 5;
m == MEAN(
m MEAN(a, a, b,
b,c, C, d,
d ,e)e ) ;;
printf ( "Mean of
printf ("Mean of the
the five is == %d")
numbers is
five numbers %d") ;;
}}

((10)
10) #defineCUBE(X)(X*X*X)
#define CUBE(X} (X * X * X)
main()
main( )
{
int
int aa;;
a == 27/
2 7 / CCUBE(3)
UBE(3);
printf
printf ("%d", a)
( "%d", a ) ;;
TheC C
The Preprocessor
Preprocessor 241
241

}
}

( 1(11) #define CUBE(X)( X(X* *XX* X* )X)


1 ) #defineCUBE(X)
main()
main()
{
{
int a, b;
intb=3
a, b;;
b a= 3CUBE(b++)
= ; I b++ ;
a = CUBE(b++)/b++;
= =
printf ( "a %d b %d", a, b) ;
printf ("a = % d b = %d", a, b ) ;
}
}
(12)
(12)

#define CUBE(X) (X *X *X)


#defineCUBE(X)(X*X*X)
main()
main()
{
{
=
int a, b 3;
int a, b = 3 ;
a = CUBE(++b) / ttb ;
a = CUBE(++b)/++b;
printf ("a = %d b = %d", a, b) ;
printf("a = % d b = % d " , a , b ) ;
}
}

( (13)
1 3 ) #define COND( (aa>=
#defineCOND >=65 &&aa<=
65&& <= 90)
90)
main()
main()
{
{
char a = 'R';
chara = 'R';
if (COND)
if ( C O N D )
printf ( ·UPPi:R CASE" ) ;
printf ("UPPER CASE");
else
else
printf ( "LOWER CASE" ) ;
printf ("LOWER CASE");
}
}

((14)
14) #define COND(a)
#define COND(a) aa >=
>= 65 && aa <=
65 && <= 90
90
main()
main()
{ .
{
. char ch = 'R' ;
charch = 'R';
. if (-C.9ND(ch) )
if(COND(ch))
242
242 Exploring
Exploring C
C

printf ("ch
( ·ch is in upper case");
case' ) ;
else
printf ("ch
( 'eh is in lower case");
case' ) ;
}}

(15)
(15) # d e f i n COND(a)
#define e C O N D ( aif) (i fa( a>=
> =65
6 5&&
& &aa <=
< = 9900 ))
main()
main( )
{{
char ch == 'R';
charch 'A' ;
COND(ch)
COND(ch)
printf (("Uppercase");
printf ·Upper case· ) ;
else
"Lower case' ) ;
printf (("Lowercase");
}}

(16) #define print(int) printf("int


printf( "int == %d\n",
%d\n., int)
int)
mainQ
main()
{
{
intx=3;
int x = 3;
print(x) ;
print(x);
}}

(17) #define P( format, var)


var) printf ("var
(·var = %format\n", var)
%format\n·, var)
main()
main()
{{
int i = 3;
inti 3;
float a == 3.14
float 3.14;;
P(( dd,, ii)) :;
P
P
P(( f,f , a)
a ) ;;
}}

(18) #define INTEGER int


INTEGERint
main()
main,)
{{
INTEGEA aa == 10,
INTEGER 10, bb == 20
2 0 ;;
printf("a = % d b = % d " ,a,a ,b)
printf ( "a = %d b = %d·, b ) ;;
Preprocessor
C Preprocessor
The C 243
243

}}

((19)
1 9 ) #define far**
Ndefine DATATYPE char far
mainQ
main()
{{
DATATYPEs;
DATATYPES;
=
ss = 0xb8000000;
Oxb8000000 ;
*s = ' A ;;
*s='f{
}}

((20)
2 0 ) #defineAND&&
Ndefine AND &&
Ndefine OR II
#defineOR||
#define
Ndefine LE
LE <=
<=
#define
Ndefine GE
GE >=>=
main()
main()
{{
char ch
char ch =='D';
'0' ;
ifif ((( (c ch GE 65
h GE 65AND
AND ch ch LE
LE90)
90 )OR
OR (ch
( chGE
GE 97
97 AND
AND ch
chLE
LE 122))
122) )
printf ("Alphabet");
printf ( "Alphabet" ) ;
else
else
printf ("Not
printf an alphabet");
( "Not an alphabet .) ;
}}

( (21)
21) #define ISLP(y)
#define ISLP(y) ( ((( y y:%
/ % 400 ==00)) ||II(y
400 == (y %% 100 != 00&&
100!::: &&yY%%44:::=
== 00))) )
main()
main()
{ {
intyy== 1992;
int 1992;
ifif (ISLP(y))
( ISLP(y) )
printf ("Leap
printf ( "Leap year");
year" ) ;
else
else
printf("Not
printf ( "NotaaLeap
Leapyear");
year" ) ;
}}

(22) #defineMAX(
(22) #define MAX(a,a,b)b) ((a)
( (a)>>(b)
(b)??(a):
(a) :(b))
(b) )
main()
main( )
{{
244
244 Exploring C
Exploring C

int m, x = 5,
int =
5, Y =
y = 66 ;:
=
m = MAX
M A X ((xx + y, y, 10)
1 0 ) :;
printf ("%d",
( "%d", m m ) ;:
=
m = MAXM A X(x,
( x ,y)y ) * 1100:
00;
printf ("\n%d",
printf ( "'n%d", m ) :m ) ;
}}

(23) #define
#define ISLOWER(a) ( aa >= 97 && a <= 127)
127)
#defineTOUPPER(a)
#define TOUPPER(a) ((aa - 3322 )
main()
main()
{{
char eh == 'e'
char ch 'c';:
ifif ((ISLOWER(ch))
ISLOWER(eh) )
eh
ch == TOUPPER(eh)
TOUPPER(ch);':
printf
printf (("%c",
"%e", eh)
c h ) ;:
}}

(24)
(24) #define
#define E exit(O) exit(O)
main()
main()
{{
int =
int ii = 4: 4;
ifi f (i( i <<== 55))
E:
E;
else
else
printf ( "Get out
printf ("Get out anyway!" ):
anyway!");
printf ( "WELL!"
printf ("WELL!"); ) ;
}

(25) #define
#define exit exit(O)
exit(O)
main(
main())
{{
printf ("To
( "To be or not to be..." );
be...");
exit;
exit;
( "is the question.
printf ("is question."); H ) ;

}
The
The C
C Preprocessor
Preprocessor 245

((26)
26) #define IT
IT 0.1
0.1
#defineHRA0.2
#define HRA 0.2
#defineDA0.3
#define DAO.3
main()
main( )
{{
float bas_sal,
float bas_sal, net_sal;
net_sal;
bas_sal = 1000;
bas_sal = 1000;
net-sal == bas_sal*(1
net_sal *
bas-sal (1 ++ HRA+
HRA + DA
D A -- IIT)
T ) ;;
printf (oGross salary =
%f, net_sal)
printf ("Gross salary = %f, net_sal); ;
}}

, ((27)
27) #define MYFILE
MYFILE "conio.h"
·conio.h"
#include MYFILE
main()
main( )
{
{
window (10,10,40,20)
window ( 1 0 , 1 0 , 4 0 , 2 0 ) ;;
cprintf ( °A pinch of
cprintf ("A pinch of probably
probably is is much
much better
better than...");
than ...") ;
cprintf ( "A pound of perhaps!")
cprintf ("A pound of perhaps!"); ;
}

((28)
28) main()
main()
{
{
window (20,
window ( 2 0 , 110,
0 , 40,
4 0 , 15)
1 5 ) ;;
#include "conio.h"
#include "conio.h"
( "The love in your heart
cprintf ("The heart was not put to stay...");
stay..." ) ;
( "Love is not love till you give ittt away.");
cprintf ("Love away." ) ;
}
246
246 Exploring C
Exploring C

Answers
Answers

(1)
(1) Output
Output

square of ii = 44
square

Explanation
Explanation

Since DEF
Since has been
DEF has been defined, #ifdef DEF
defined, #ifdef DEF evaluates
evaluates to true,
to true,
hence square of
hence square of ii is
is calculated
calculated and
and printed
printed through printf().). Is
through printf( Is
it
it not necessary while
not necessary while defining
defining DEF
DEF to to use
use aa macro expansion
macro expansion
following
following DEF?
DEF? No,No, since
since we
we don't
don't intend
intend to
to use
use the
the value
value ofof
the macro expansion anywhere in the program.
the macro expansion anywhere in the program. All that we All that we
want
want isis to
to conditionally
conditionally compile
compile the
the program
program subject
subject to
to the
the
condition
condition whether
whether DEFDEF has
has been
been defined
defined oror not.
not.

(2)
(2) Output
Output

Message: Expression
Error Message: Expression syntax in function main

Explanation
Explanation

We have assigned
We have assigned values
values of
of YES
YES and
and NO
NO to
to j in
in the if-else,
the if-else,
but what
but what are
are the values of
the values of YES
YES and NO? They
and NO? They have
have only
only been
been
defined as macros
defined as macros without
without being
being given
given any
any expansions. Hence
expansions. Hence
the error message.
the error message.

(3)
(3) Output
Output

mm
mm

Explanation
Explanation
The
The C
C Preprocessor
Preprocessor 247

During preprocessing
preprocessing MESS( "But.... past.")
"But ••••past.. " ) gets replaced
by printf
printf ( "m"
"m" ). Naturally, on execution this printf()
printf( ) prints
out m. The same thing happens to the next statement, which
also prints out an m.

(4) Output
Output

It's better to keep your mouth shut..


shut..
.... and have people think you are a fool..
fool..
.... than to open ittt and remove all doubt!

Explanation
Explanation

During preprocessing
preprocessing the preprocessor replaces all occurren-
ces of GOTONEXTLINE
GOTONEXTLINE in main() maine ) with printf(
printf( "\n"
"\n" ).).
Hence during execution, the three messages are output on on
different
different lines.
lines.

(5)
(5) Output
Output

m
m

Explanation
Explanation

The preprocessor
preprocessor replaces both the occurrences of MESS with
printf(
printf( "m"
"m" ). Similarly,
Similarly, GOTONEXTLINE
GOTONEX1LINE is replaced by
printf(
printf( "\n"
"\n" ). Thus, when the program is sent for
for execution,
it has been converted to the following form:

main()
main( )
{
{
printf( "m");
printf( "m" ) ;
printf("\n" );
printf("\n");
printf( "m");
printf( "m" ) ;
248
248 Exploring C
Exploring

}}

This would output


This would output two
two ms
ms on
on different
different lines.
lines.

(6)
(6) Output
Output

ch doesn't contain
ch doesnt contain an
an alphabet
alphabet

Explanation
Explanation

The first
The first and second macros
and second macros have
have the
the criteria
criteria for
for checking
checking
whether their
whether their argument
argument xx is
is an
an upper
upper oror aa lower case alphabet.
lower case alphabet.
These two
These two criteria have been
criteria have been combined
combined in in the
the third
third macro,
macro,
ISALPHA. Thus
ISALPHA. Thus when
when the
the program goes for
program goes for compilation, the
compilation, the
if statement
if statement has been converted
has been converted toto the
the form:
form:

ifif (ch >= ,65


( ch >= 65 &&
&& ch <= 901|
ch <= 90 II ch
ch >=
>= 97
97 &&
&& ch
ch <=
<= 122)
122)

As ch
As ch has
has been initialised to
been initialised to character
character +,
+, the
the conditions
conditions in
in the
the
if fail and the control rightly passes to the else block, from
if fail and the control rightly passes to the else block, from
where the
where the output
output is obtained.
is obtained.

(7)
(7) Output
Output

Unexpected end of
Unexpected end of file in conditional
file in conditional

Explanation
Explanation

The macros
The nus
macros THIS and and 1HA
THAT T have been correctly
have been correctly defined.
defined.
The error
The error lies
lies in
in the imbalance of
the imbalance of Nifdef
#ifdef and
and #endif
#endif statements
statements
in the
in the program.
program. Inserting another #endifwould
Inserting another #endif would guarantee
guarantee the
the
.. output
output "Definitions
"Definitions are
are hard
hard to
to digest".
digest". This
This also
also goes
goes to
to show
show
that the
that the #ifdefs
Nifdefs cancan be
be nested the same
nested the same way
way the
the ordinary
ordinary ifif
statements can
statements can be.
be.
The
The C
C Preprocessor
Preprocessor 249

((8)
8) Output
Output

Definitions
DefinRions are hard to digest

Explanation
Explanation

Logical operators are perfectly acceptable in #IifdefSiateID:ents.


i f d e f statements.
Since both THIS
11I1S and THAT 11IA T are defined, the preprocessor
allows
allows only
only the first pprintf(
the first r i n t f ( )) to
to go
go for
for compilation,
compilation, which
which gets
gets
executed
executed and
and we
we get
get our
our output.
output.

(9)
(9) Output
Output

Mean of the five numbers =


numbers is = 3

Explanation
Explanation

The preprocessor
preprocessor substitutes the macro MEAN with its expan-
sion.
sion. This
This expansion
expansion is
is the
the formula
formula toto calculate
calculate the
the average
average of
of
55 numbers.
numbers. With
With the
the values
values ofof 55 numbers
numbers inin this
this program,
program, the
the
result
result turns
turns out
out to
to be
be 3,3, which
which then
then gets
gets printed
printed out through
out through
pprintl().
rintfO. .

(10) Output
(10) Output

Explanation
Explanation

The macro CUBE(X)CUBE(X) is defined to give the cube of its argu-


ment. In the program,
program, the preprocessor replaces CUBE(3)
CUBE(3) by
((33 ** 3 **33)) and then sends the program for compilation.
compilation. Thus,
a is calculated
calculated as,
250
250 Exploring
Exploring C

aa =
= 27
2 7/ /( (33•*33 •* 33 ))
a== 27/27
27/27
aa=1
= 1

Hence the
Hence result.
the result.

(11) Output
(11)_ Output

a8=9b=7
=9b=7

Explanation
Explanation

Here, the
Here, the argument
argument of
of the
the macro
macro CUBE(X)
CUBE(X) is is made
made to
to be
be b++.
b++.
The preprocessor
The preprocessor puts
puts the
the macro
macro expansions
expansions inin place
place of
of the
the
macro templates
macro templates used
used in
in the
the program,
program, so
so that
that what
what reaches the
reaches the
compiler is:
compiler is:

1>++ * b++
a8:;= ((b++ b++ * b++
b++)) I/ b++
b++

As ++++ succeeds
succeeds b, b, first
first the
the value
value of
of aa is
is derived
derived using
using the
the initial
initial
value ofb(
value of b( i.e.
i.e. 3 3),), after which, the
after which, the ++
++ does
does its job on
its job on b.
b. Hence
Hence
((33 * 33 * 33 )) // 33 ,, i.e.
i.e. 99 gets
gets stored
stored in
in a.
a. Since
Since b++
b++ isis encountered
encountered
four times
four times in in thethe program,
program, bb is is incremented
incremented four four times,
times, result-
result-
ing in
ing in the final value
the final value of b as 7.
of bas 7. Thus,
Thus, aa stores
stores 9 and b,
9 and b, 7
7 as the
as the
output would
output would vouch vouch for. for.

(12) Output
(lZ) Output

a8=49b=7
= 49b = 7

Explanation
Explanation
i

Once again,
Once again, CUBE(X)
CUBE(X) is is expanded
expanded toto give
give the
the cube
cube ot its
ot its
argument. In
argument. In the
the program,
program, the the argument
argument isis taken
taken to
to be
be ((++b),
++b ),
having initialised
having initialised bb to
to 33 at
at the outset. The
the outset. The preprocessor, before '
preprocessor, before'
The
The C
C Preprocessor
Preprocessor 251
251

sending
sending the
the program
program for
for compilation,
compilation, converts
converts the
the statement
statement
containing the macro to:
containing the macro to:

aa = ((++b*++b*++b)/++b
ttb * ttb * ttb )/ ttb

The
The unary
unary operator
operator ++++ has
has aa higher
higher priority
priority than
than that
that of
of the
the
binary operators ** and/.
binary operators and /. Therefore,
Therefore, first
first the
the multiple
multiple incremen-
incremen-
tations
tations of
of bb take
take place.
place. AsAs ++b
++b occurs
occurs four
four times
times inin the
the
statement,
statement, bb is
is incremented
incremented four
four times.
times. Thus,
Thus, bb now
now has
has aa value
value
7.
7. This
This value
value is
is used
used to
to calculate
calculate the
the result
result as:
as:

aa=(7*7*7)/7
=(7*1*1)11
aa = 343
3 4 3// 7
aa::= 49

(13) Output
(13) Output

UPPERCASE

' I

Explanation
Explanation I

When
When 'R''R' is
is stored
stored inin the
the variable
variable a,
a, what
what gets
gets stored
stored is
is the
the
ascii
ascii value
value ofof the
the letter
letter 'R',
'R', which
which is
is 82.
82. The
The criteria
criteria for
for the
the
character
character inin aa being
being anan upper
upper case
case alphabet
alphabet is is defined
defined inin the
tbe
macro
macro COND.
CONDo DuringDuring preprocessing,
preprocessing, in in the
the if
if statement,
statement, the
the
COND
COND is is replaced
replaced by by (a
( a >= 6565 && aa <= 90).
90 ). Since
Since aa contains
contains
82
82 the
the condition
condition is is satisfied
satisfiedand and we
we get
get the
the output
output asas UPPER
UPPER
CASE.
CASE.

What
What wewe must
must bring
bring to
to your
your notice
notice is
is that
that this
this macro
macro is without
is without
any
any argument.
argument. Hence
Hence it it will
will work
work only
only for
for aa variable
variable called a.
called a.
If
If we
we replace
replace the
the variable
variable aa with
with any
any other
other variable,
variable, say
say bb in
in
the
the declaration
declaration statement,
statement, we we would
would getget an
an error
error message:
message:
'variable
'variable aa not defined'.
not defined'.
252
252 Exploring
Exploring C

(14) Output
Output

ch is in upper case

Explanation
Explanation

We
We have
have taken
taken care
care to
to provide
provide anan argument
argument toto the
the macro
macro
COND(a).
COND(a). So,
So, during
during preprocessing
preprocessing the if statement
statement becomes:
becomes:

iiff ((ch
c h >>=
= 665
5 &&&
& cch
h <<=
= 990)
0)

Since
Since ch
chisis stated
stated to be capital
capital 'R'
'R' in the program,
program, we rightly
rightly
get
get the
the output
output as as 'ch
'ch is
is in
in upper
upper case'
case'

(15) Output
Output

Upper case
Uppercase

Explanation
Explanation

During
During preprocessing
preprocessing COND(ch)
COND(ch) gets gets replaced
replaced by by if
if ((ch
c h <=
<=
65 && ch <= 90). Since ch has been initiated to ' R \ naturallyy
65 && ch <= 90 ). Since ch has been initiated to 'R', naturall
during
during execution,
execution, the
the condition
condition is
is satisfied
satisfied and
and 'Upper
'Upper case'
case'
gets
gets printed.
printed.

What
What if
if we
we define
define the
the macro
macro as
as shown
shown below:
below:

#define
#define C0ND(a)
CONO(a) (if
{ if ((aa >=
>= 65
65 &&
&& aa <=
<= 990)
0 ) ))

Do
Do you
you still
still expect
expect the
the program
program to to work
work as as itit did
did before?
before? ItIt
doesn't.
doesn't. WeWe get
get an
an error
error message
message because
because here
here thethe keyword
keyword ifif
too
too has
has been
been placed
placed within
within parentheses
parentheses inin the
the macro
macro definition.
definition.
As
-Asa~result,
result, after
after preprocessing
preprocessing the
the program
program takes
takes thethe following
following
form:
fomi:
The C
The Preprocessor
C Preprocessor 253
253

(if ( ch >=
( if (ch 65 && ch
>= 65 ch <=
<= 90
9 0 ) ))
printf ( 'Upper case'
printf ("Upper case"););
else
else
printf ("Lower
printf ( 'Lower case");
case' )/;

Obviously, when
Obviously, when this
this form
form is
is sent
sent to
to the
the compiler,
compiler, itit flashes
flashesan
an
a syntax error in the if statement due to the pair of parentheses
a syntax error in the if statement due to the pair of parentheses
surrounding
surrounding it.
it.

(16)
(16) Output
Output

int =
int= 33

Explanation
Explanation

The output
The not xx ==33 but
output isis not int ==3.3. When
but int When the
the preprocessor
preprocessor
replaced the
replaced themacro
macro withwith its
itscorresponding
corresponding expansion,
expansion,ititsub-
sub-
stituted only the int outside the double quotes, and
stituted only the int outside the double quotes, and left the one left the one
within the quotes untouched. Thus after preprocessing, the
within the quotes untouched. Thus after preprocessing, the
print(x)
print(x) became
became printf
printf ("int =
( "int = %d",
%d", xx) .).During
Duringexecution
execution
the
thefunction
functionprintf()
printf( )prints
printseverything
everythingwithin
withinits
itsquotes
quotesasasitit
is,is,except
exceptfor
forthe
theformat
formatspecifications.
specifications.HenceHencethe
theresult.
result.

(17)
(17) Output
Output

var==49.920013ormat
var 49.920013ormat
var= =3.140000ormat
var 3.140000ormat

Explanation
Explanation

Duringpreprocessing,
During preprocessing, the
theformat
format ininthe
theprintf()
printf( )statement
statement
doesnot
does notget
getreplaced
replacedbybythe
theargument
argumentd.d.Thus
Thusthe
the'printf()
printf( )
statements, after preprocessing, look like this:
statements, after preprocessing, look like this:

printf("var
printf =
( 'var= %format
%format\n",
\n°,i )i); ;
254
254 Exploring C
Exploring C

printf ("var=
( ·var = %format\n·
%format\n", a)
I a);

This is only in keeping


keeping with what the previous
previous example il-
lustrated, that the macro
lustrated, macro template
ternplate within the quotes doesn't
doesn't get
replaced by
replaced the macro
by the macro expansion.
expansion. When
When these
these printf(
printf( )s
)s are
are
executed,
executed, the material within
the material within quotes
quotes gets
gets dumped
dumped on on to
to the
the
screen
screen as
as it is, except
it is, except when
when aa format
format specification
specification or
or an
an escape
escape
sequence (like '\n'
sequence (like '\n' )) is
is encountered.
encountered.

Look at
Look at the
the first
first output.
output. Where
Where did
did 'f'
' f go?
go? And
And why
why were
were the
the
numbers printed
numbers printed at all? This has the simple explanation
explanation that
our argument format
format happened
happened to have as its first letter, an 'f'.
T.
The printf() interpreted %f
printl( ) interpreted %f as the format specification,
specification, and
'ormat' as something
'ormat' something we wanted
wanted to write on the screen literally.
literally.

Note that we got the expected


expected value for a, a float,
Ooat, but an absurd
one for int
int i, since the printf(
printf()) attempted to'
to- print out an int
int
using %f.
using %f.

(18) Output
(18) Output

a = 1 0 b = 20
a=10b=20

Explanation
Explanation

We #define
We #define the
the keyword
keyword intint as
as INTEGER,
INTEGER, and use this
and use this macro
macro
in the
in declaration of
the declaration of variables
variables inside
inside main(). By the
main( ). By the time
time the
the
compiler
compiler sees
sees it,
it, the
the preprocessor
preprocessor has
has substituted the macro
substituted the macro
INTEGER with
INTEGER with int
int in
in the
the declaration
declaration statement.
statement. Hence our
Hence our
program works without
program works without aa hitch.
hitch.

(19) Output
(19) Output

A
The C Preprocessor
The C Preprocessor 255
255

Explanation
Explanation

Normal pointers
Normal pointers contain
contain anan address
address which
which isis 16-bit
16-bit long. These
long. These
pointers are
pointers are called
called near
near pointers.
pointers. To
To access
access the
the address
address ofof top
top
left comer
left corner ofof the
the screen
screen wewe need
need aa 32-bit
32-bit pointer.
pointer. Such
Such pointers
pointers
are called
are called far
far pointers.
pointers. These
These pointers
pointers are
are declared
declared by by qualify-
qualify-
ing them
ing them withwith thethe keyword
keyword far far while
while declaring
declaring them.
them.
0xb8000000 is
Oxb8000000 is an
an address
address that
that refers
refers to
to the
the first
first element
element onon the
the
screen, i.e.
screen, i.e. the
the top
top left corner of
left comer of your monitor. This
your monitor. This address
address isis
aa 32-bit
32-bit address,
address, soso requires
requires the
the keyword
keyword far far to
to be
be associated
associated
with it.
with it. The
The declaration
declaration char
char far
far *s
*s signifies
signifies that
that sswill contain
will contain
aa 32-bit
32-bit address.
address.

The preprocessor
The preprocessor replaces
replaces the macro DATA
the macro DATATYPE TYPE with char
wi th char
far * in
far in the program, and
the program, and the
the character
character 'A'
'A' gets
gets printed
printed at the
at the
top left
top left corner
comer onon the screen. What
the screen. What should
should be be noted
noted is
is that
that we
we
have been able to print a character on the screen without
have been able to print a character on the screen without using using
aa printf().
printf(). That
That is
is the
the power
power of
of pointers
pointers for
foryou!
you!

(20) Output
(20) Output

Alphabet
Alphabet

Explanation
Explanation

Before maine
Before main()) macro definitions have
macro definitions have been
been given
given for
for logical
logical
operators &&
operators && and II, as
and ||, as also
also for
for relational
relational operators
operators <=<= and >=.
and >=.
These are
These are then
then used
used to
to build
build aa criteria
criteria for
for checking
checking whether
whether ch ch
contains an
contains an alphabet
alphabet oror not.
not. All
All macros
macros are
are substituted
substituted by their
by their
expansions prior
expansions prior to
to compilation,
compilation, and and since
since 'D'
'D' satisfies
satisfies the
the if
if
condition, 'Alphabet'
condition, 'Alphabet' is is printed out.
printed out.

(21) Output
(21) Output

Leap year
256
256 Exploring C
Exploring C

Explanation
Explanation

The macro
The macro ISLP(y)
ISLP(y) takes
takes as
as its
its argument
argument anyany year
year y,y, and
and tests
tests
if the
if the year
year is
is aa leap year or
leap year or not. For aa year
not. For year to
to be leap, either
be leap, either it
it
should be
should be an integral multiple
an integral multiple ofof 400,
400, or
or if
if the
the year
year is not
is not
divisible
divisible byby 100,
100, anan integral
integral multiple
multiple of of 4.
4. Why
Why is is this
this so
so and
and
why we
why we are
are not
not told
told this
this in
in school,
school, II leave
leave for
for you
you toto figure
figure out.
out.
The year
The year 1992
1992 is is not
not divisible
divisible by 400, hence
by 400, hence the
the first
first condition
condition
fails, but
fails, but the
the second
second part
part of
of the
the condition
condition holds
holds good.
good. Hence
Hence
the output that the year is indeed a leap year is
the output that the year is indeed a leap year is obtained. obtained.

(22) Output
(22) Output

11
11
600
600

Explanation
Explanation

The macro
The macro MAX(
MAX( a, b b )) is
is defined
defined using
using the
the conditional
conditional
operators ? and
operators? and :.
:. The
The preprocessor
preprocessor converts the first
converts the first assign-
assign-
ment statement
ment statement for
for mm to the following
to the following form:
form:

m = (((x + y ) > ( 1 0 ) ) ? ( x + y ) : ( 1 0 ) ) ;
m=(((xty»(10))?(Xty):(10));

In place
In place of
of a,
a, the
the argument
argument is is taken
taken as
as x
x + y,
y, and
and in
in place
place of
of b,
b,
the number
the number 10. 10. If
If you
you haven't
haven't recognised
recognised thethe conditional
conditional
operators, think
operators, think back
back to
to the
the decision
decision control
control instructions.
instructions. The
The
statement is
statement is interpreted
interpreted as:
as:

If xx + y
If y is
is greater
greater than
than 10, m
m is
is to
to be
be assigned
assigned value
value x
x + y,
y,
otherwise the
otherwise value 10.
the value 10.

As xx and
As and yy have
have been
been initialised
initialised as
as 55 and
and 66 respectively,
respectively, their
their
sum is
sum 11, which
is 11, which isis greater
greater than
than 10.
10. Hence
Hence m m is
is assigned
assigned aa value
value
11, which
11, which isis printed
printed out.
out.
The C
C Preprocessor
Preprocessor 257
257

The second
The second assignment
assignment statement
statement after
after preprocessing
preprocessing be-
be-
comes:
comes:

m == ((( ((x)
m ( x ) >> (y)
( y ) )) ? ((x) y ) ) **1100;
x ) :: ((y)) 00;

Since value
Since value ofy,
of y, i.e.
i.e. 6,
6, is
is greater
greater than
than x,
x, which
which is
is 5,
5, value
value ofy
of y
is multiplied
is multiplied with
with 100,
100, and
and the
the result
result is
is printed out as
printed out as 600.
600.

(23) Output
(23) Output
e

c
C

Explanation
Explanation

The macro
The macro ISUPPER
ISUPPER is is used
used toto check
check whether
whether its its argument
argument
is an
is an upper
upper case
case alphabet
alphabet oror not.
not. If the
the argument
argument is is aa lower case
lower case
alphabet, the
alphabet, the macro
macro TOUPPER
TOUPPER changes changes itit to
to the
the upper
upper case.
case.
The difference
The difference inin the
the ascii
ascii values
values ofof lower
lower case
case andand upper
upper case
case
letters is
letters 32, so
is 32, so this
this number
number isis subtracted
subtracted from
from the the ascii value
ascii value
of the
of the lower
lower case letter to
case letter give the
to give the corresponding
corresponding upper case
upper case
letter. Thus, in this case V gets converted
letter. Thus, in this case 'c' gets converted to 'C'. to ' C .

(24) Output
(24) Output

No output
No output

Explanation
Explanation

E is
E is defined
defined asas aa macro
macro for
for the
the function
function exit(O),
exit(0), which
which uncon-
uncon-
ditionally terminates
ditionally terminates the
the execution
execution of of the program. Since
the program. Since ii has
has
been assigned
been assigned aa value
value less
less than
than 5,
5, the
the control
control enters
enters the
the ifblock,
if block,
where the
where the compiler
compiler finds
finds the
the exit(0). Control is
exit(O). Control is immediately
immediately
taken out
taken of the
out of the program,
program, leaving
leaving nono chance for the
chance for the 'WELL!'
'WELL!'
to get
to get printed.
printed.

L
258
258 Exploring C
Exploring C

(25) Output
(25) Output

To be or not to be...

Explanation
Explanation

From the
From the above
above program
program we we can
can gather
gather that
that macros
macros need not
need not
necessarily be
necessarily defined in
be defined in capital
capital letters.
letters. Capital
Capital letters
letters are used
are used
only to
only to facilitate
facilitate our
our comprehension
comprehension of of the
the program;
program; i.e.i.e. to
to
make out
make out which
which is is aa variable
variable and
and which
which isis aa macro.
macro. After
After
executing the
executing first printf(
the first printf(), ), the
the compiler
compiler finds
finds the
the exit(0),
exit(O), as
as
substituted by the preprocessor, and hence terminates
substituted by the preprocessor, and hence terminates the ex- the ex-
ecution.
ecution.

(26) Output
(26) Output

= 1400.000000
Gross salary = 1400.000000

Explanation
Explanation

When the
When the preprocessor
preprocessor sends
sends the
the program
program for
for compilation,
compilation, IT,
IT,
HRA and
HRA and DA have been
DA have been replaced
replaced by
by 0.1,
0.1, 0.2 and 0.3
0.2 and 0.3 respec-
respec-
tively. With
tively. With bas_sal
bas_sal set
set to
to 1000,
1000, the
the net
net salary
salary is
is calculated
calculated
as:
as;

net_sal = bas_sal * ((11 ++ 0.2


0.2 ++ 0.3
0.3--0.1
0.1)
) ;;

Next the
Next result is
the result is printed
printed out.
out.

(27) Output
(27) Output

A pinch of probably is much better than


perhaps!
...A pound of perhaps! ..
The C
The C Preprocessor
Preprocessor 259
259
r
I

Explanation
Explanation

The name
The name ofof aa file can be
file can be used
used asas an
an expansion
expansion for
for aa macro
macro
definition. Saying
definition. Saying #include MYFILE is
#include MYFILE is same
same as
as saying
saying #in-
in-
clude "conio.h",
clude "conio.h", as as this
this is
is what
what the
the preprocessor
preprocessor sends for
sends for
compilation after replacing
compilation after replacing the
the macro
macro MYFILE.
MYFILE.

The file "conio.h"


"conio;h" is a header file which is required by the
function window().
window(). This function defines an active text mode
window. Here, the area on the console from
window. from the 10th column,
th

th th th
10 row
lO" 1
row toto the
the 40
40 " column,
l
column, 20 20'" rowrow isis made
made active. The
active. The
function cprintf()
cprintf() sees to it that the output of our program goes
only to
only to this
this particular area on
particular area on the
the screen.
screen. (( printf(
printf(), on the
), on the
other hand simply
other hand simply sends
sends the the formatted
formatted output
output to
to the
the portion
portion ofof
the screen where
the screen where the cursor is
the cursor is currently
currently located.
located. )) We can
We can
appreciate
appreciate the point better
the point better when
when we we take
take note
note of
of the
the fact
fact that
that
we
we have
have our output in
our output in two
two different
different lines,
lines, without
without having
having
inserted
inserted aa newline
newline '\n\ As the
'\n'. As the message
message getsgets printed,
printed, when
when thethe
cursor
cursor comes
comes to to the right edge
the right edge of
of the
the window,
window, it automatically
it automatically
goes
goes to the left
to the left edge
edge on on the next line
the next and prints
line and prints the
the remaining
remaining
message there.
message there.

(28) Output
Output

Error message: Expression syntax in function main


message: Expression

Explanation
Explanation

The above
The above scheme
scheme would
would never
never work,
work, as
as the
the #include
#include must
must be
be
specified outside
specified outside the function maine
the function main(). That is
). That is why
why we
we get an
get an
error message.
error message.
A
A Tryst with
with· Arrays
provides a facility called array that enables the user to
provides

C combine similar datatypes


combine datatypes into a single entity. Ordinary vari-
ables are capable of holding only one value at a time. If there
is a large amount of similar
similar data to be handled, then using a different
different
variable
variable for each data item would make the job unwieldy, tedious and
confusing. Instead,
Instead, on combining
combining all this similar data into an array,
the whole task of organising
organising and manipulating
manipulating data would become
become
easier and more efficient. The following figure shows the use of an
array in aa program.
array in program.

main()
main() 0[0] n[l]
n[0] n[2] 0[3]
0[1] 0[2] n[3] n[4]
0[4]
{{
r- float
c-
float aV_9,
ayg, sum
int i,i, n[51
iot n[5];;
sum == 00;; 10
110 I 2020 I 30 I 40 I 5050 I
30 40

printf
printf (("Enter numbers");;
"Enter 5 numbers") 4000 4002
4000 4002 4004
4004 4006
4006 4008
4008
for ( i == 0;
for (i i <= 44;; itt
0 ; i<= i++)) Notes
Notes
scanf
scant ("%d", &n[q);;
("%d", &n[ij) -- Array
Array elements
elementsare arestored
storedinincon-
con-
tiguous memory
tiguous memorylocatioes,
locations.
for (i = 0; i <= 4; i++)
for(i=O;i<=4;i++) -- The
The size
size of
of Ihe
thearray
arrayshould
shouldbebemen-
men-
sum
sum == sum
sum + n[ij
n[i];; tioned while declaring
tioned while e.g.0[5].n[S\.
declaringit.it.e.g.
-- Array
Array elements
elementsare arealways
alwayscounted
counted
from 00onwards.
from onwards.
avg = sum/S;
sum/5;
- Array
Array elements
elementscan canbebeaccessed
accessedusingusing
%f", sum,
printf ("%f %r, sum, avg);
avg ) ; the position
the position ofof the
the elemegt
element ininthe
the
} array, e.g. o[i]
array. e.g. n[i] refers
referstotoii element.
element.

Figure 8.1 Array "atwork


at work
A Tryst
Tryst with
with Arrays
Arrays 263
263

With the
With the basics
basics of
of arrays
arrays under
under our
our belt,
belt, let's
let's delve
delve into
into aa few
few smaller
smaller
issues.
issues.

(a)
(a) Like ordinary variables,
Like ordinary arrays too
variables, arrays too can
can be
be initialised
initialised during
during
declaration. For
declaration. example:
For example:

int num[6] =
num[6]= {2, { 2 , 4,
4 , 112,5,45,5}
2,5,45,5};
int n[] ={
n[ ] = { 22,, 44,, 112,
2 , 5,5 ,45,
4 5 ,55}} ;
float press[ ={
press[]] = {12.3,34.2 -11.3};;
12.3, 34.2 -23.4, -11.3}

If the array
If the array is
is initialised
initialised where
where it
it is
is declared,
declared, mentioning
mentioning the
the
dimension of
dimension the array
of the array is
is optional,
optional, asas in
in the
the 22nd and
and 3rd
3
n d r d

examples above.
examples above.

(b)
(b) In C,
In C, there
there is is no
no check
check toto see
see if
if the
the subscript
subscript used
used for
for an array
an array
exceeds
exceeds the the size
size of
of the
the array.
array. Data
Data entered
entered with
with aa subscript
subscript
exceeding
exceeding the array size
the array size will
will simply
simply be be placed
placed inin memory
memory
outside
outside thethe array;
array; probably
probably on on top
top of
of other data, or
other data, or on
on the
the
program
program itself. This will
itself. This will lead
lead to
to unpredictable
unpredictable results,
results, to
to say
say
the least, and
the least, and there
there will
will be
be no
no error
error message
message to to warn
warn you
you that
that
you
you are
are going
going beyond the array
beyond the array size.
size. In
In some cases the
some cases the com-
com-
puter may just
puter may just hang.
hang.

The moral
The moral to be derived
to be derived is:
is: toto keep
keep your
your program
program fit and
fit and
fighting, see
fighting, to it
see to it that
that you
you never
never attempt
attempt toto reach
reach beyond
beyond thethe
legal array
legal array size.
size. The
The point
point is,
is, the
the onus
onus ofof doing
doing so
so lies
lies on the
on the
programmer's shoulders and
programmer's shoulders and not
not on
on the
the compiler's.
compiler's.

Arrays and
Arrays Functions
and Functions

Let's venture
Let's venture further
further and
and see how arrays
see how arrays and
and functions
functions interact
interact with
with
one another.
one another. How
How dodo we
we pass
pass array
array elements
elements to
to aa function?
function? Naturally,
Naturally,
by value
by value and/or
and/or by
by reference.
reference. The
The following
following figure
figure shows
shows both these
both these
calls at
calls at work.
work.
264
264 Exploring
Exploring C
C

MAIN()
main() m[0]
m[O] m[l]
m[l] m[2]
m[2] m[3]
m[3] m[4]
m[4]
{
Iint
RRT i I;
NT mD
Iint MQ=={ 55,
{ 55,65,
65,75,
75,85,95};
85, 95 } ; I I I I I
55
55 65
65 75
75 85
'85 95
95 I
5000
5000 5002
5002 5004
5004 5006
5006 5008
FOR (I = 0; I <= 4 ; I++)
for(i=O;i<=4;iH)
{ ..
nn kk
d ( m[i]) ;/;*/*
D(M[IL) CALL BYvalue
call by */
VALUE*/
r
S(&M[0);/*CALLBYREF.*/
s ( &m(ij ) ; call by ref. */
}
}
Contents
Contents of
of nn and
and kk when
when first
first call
call to
to
D(N)
d(n) dO and
and sQ
sO isis made.
made.
NTnN; ;
Iint
{
{
printf
PRINTF (("%D",N);
"%d", n) ;
}

ss(k)
(k)
int *k ;
INT*K;
{{
PRINTF(·%d·,
printf *k l;
("%D",*K);
}.
Figure
Figure 8.2
8.2 Call
Call by value/reference
by value/reference

Let
Let us
us now
now digress
digress aa bit
bit and
and see
see what
what lies
lies below
below the
the outer
outer garb
garb of
of
pointers.
pointers. Having
Having explored
explored that,
that, we
we would
would once
once again
again get
get back
back to
to
arrays,
arrays, better equipped.
better equipped.

Pointers: A
Pointers: A second look
second look

We had
had our
our first
first tryst
tryst with
with pointers
pointers in
in Chapter
Chapter 5. 5. We
We may
may recall
recall that
that
a pointer
pointer isis aa variable
variable which
which stores
stores the
the address
address of of other
other variables.
variables. If If
a pointer
pointer variable
variable stores
stores the
the address
address of of aa char
char variable,
variable, we
we call
call itit aa
char
char pointer.
pointer. SameSame logic
logic applies
applies to
to an
an int pointer
pointer or
or aa float pointer.
pointer.
With
With this
this much
much knowledge
knowledge under
under our
our belt,
belt, its
its time
time to
to have
have aa closer
closer
look
look at
at pointers
pointers and and how
how they
they relate
relate to
to arrays.
arrays.
A Tryst with Arrays
TrystwithArrays 265
265

incrementing aa pointer,
On incrementing pointer, it
it points'to
points 'to the immediately next
the immediately next location
location
of its
of type. The·
its type. The way
way aa pointer
pointer can
can be incremented, it
be incremented, it can
can be
be decre-
decre-
mented as
mented as well,
well, to
to point
point to
to earlier
earlier locations.
locations. This
This is
is illustrated
illustrated in the
in the
following figure.
following figure.

j k

3
I 1.5
1.5 I 'c'
I
1002 2004
2004 5006
5006

Suppose the
Suppose the following statements are
following statements are now executed:
now executed:
x = &i
x=&i y = &j
y=&j z = &k
z=&k
The contents
The contents of x, yy and
of x, and zz would
would now
now be:
be:
xx yy z

1002
1002 I ~ 2004 ~ 5006

1212 4758
4758 7234
7234

Suppose the
Suppose the following statements are
following statements are now executed:
now executed:
x++
x++ y++
y++ z++
z++
The contents
The contents of
of x,
x, y and
and zz would
would now
now be:
be:
x
x yy zz

1004
1004 I 2008
2008 I 5007
5007 I
1212 4758
4758 7234
7234

Figure 8.3 Incrementation


Figure 8.3 Incrementation of
of pointers
pointers

Pointers and
Pointers and Arrays
Arrays

Pointers and
Pointers and arrays
arrays go
go hand
hand in
in hand.
hand. In
In fact,
fact, use
use of pointers presents
of pointers presents
another way
another way of
of accessing
accessing array
array elements. This derives
elements. This derives from
from two
two facts:
facts:
266
266 Exploring C
Exploring C

(a)
(a) Array
Array elements
elements are
are always
always stored
stored in
in contiguous
contiguous memory loca-
memory loca-
tions.
tions.
(b)
(b) A pointer
pointer when
when incremented
incremented always
always points
points to
to the immediately
the immediately
next location
next location of
of its type.
its type.

Let's concoct
Let's concoct aa program which highlights
program which highlights this
this correlation.
correlation. It
It is
is shown
shown
in the
in the following
following figure.
figure.

•• num[O]
num[0] num[l]
num[1] num[2]
num[2] num[3]
num[3] num[4]
num[4]

I 23
23 34
34 12
12 44
44 56
56 I
4001
4001 4003
4003 4005
4005 4007
4007 4009
4009

]I
j j
On incrementing
incrementing
4001 4003
4003
I
6485
6485 6485
6485

*j =23
= 23 *j ==34
34

main()
main()
{
* int num[]1== {23,
int num[ {23, 34,
34,12,44,56};
12,44,56} ;
int i,i, *j;
int *j;

=
jj = &num[0]
&~~m[~l f;1* assignas~!gn address
address of
of zeroth
zeroth element
element */
*/
for ((iI -= 00 ;, i<=
I <= 44 ;, 1++
i++))
{{
printf ("address
printf ("address = %d\t", &num[i]) ;
%d\t", &num[ij)
printf ("element = %d\n",
printf ("element * j ) ;;
%d\n·, *j)
J++ ;
}}
}

Figure 8.4 Interaction


Figure 8.4 Interaction of
of array
array and pointer
and pointer
A Tryst
Tryst with Arrays
withArrays 267
267

Two Dimensional
Dimensional Arrays
Arrays
It is
is also
also possible
possible {or
for arrays
arrays toto have
have two
two or
or more
more dimensions.
dimensions. The
The
two-dimensional array
two-dimensional array is
is also
also ca!led
called aa matrix.
matrix. The
The following
following program
program
shows aa two-dimensional
shows two-dimensional array
array at
at work.
work.

main())
main(
{{
ints[4][2],i;
int S[4][2], i ;

for ( ii =
=00 ;; ii <=
<= 33 ;; itt ))
{{
printf (("\nEnter
printf "\nEnter roll
roll no.
no. and
and marks"
marks"); );
scanf
scanf (( %d%d",&s[i][0]
,"%d %d", &s[i][O], &s[ij[1])
&s[i][1]);;
1

}}

for ( ij = 00 ;; ij <= 33 ;; itt


i++))
printf (("%d%d\n",s[i][0],slO[1]);
printf "%d %d\n", s[ij[O], s[ij[1]) ; ,I
}}

The program
The program is fairly simple.
is fairly simple. Through the first
Through the first for
for loop,
loop, we
we read
read the
the
values of
values of roll
roll no.
no. and
and marks
marks into
into the
the two-dimensional
two-dimensional arrayarray s[4][2]
s[4][2]
and through
and through thethe second
second for
for loop
loop we
we print
print out
out these
these values.
values.

A few tips
A few tips about
about the
the program
program are
are in
in order.
order.

(a)
(a) Before using
Before using the 2-D array
the 2-D array its
its dimension
dimension must
must be mentioned.
be mentioned.
This has
This has been done in
been done in our
our program
program by
by the statement int
the statement int s[4] [2].
s[4][2].

(b) The
The elements
elements of the 2-D
of the 2-D array
array s[ ] [ ] can
s[][] can be
be accessed
accessed using
using the
the
subscript notation
subscript notation s[i]|j], where ii represents
s[i][j], where represents the
the row number
row number
and jj represents
and represents the
the column number
number in in which
which the
the element
element isis
present.
present.
268
268 Exploring
Exploring C

(c)
(c) The arrangement of
The arrangement array elements
of array elements into
into rows and columns
rows and columns is is
only conceptually
only conceptually true,
true, since
since in
in memory there are
memory there are no
no rows
rows and
and
columns. Hence
columns. Hence even
even 2-D array elements
2-0 array are arranged
elements are linearlyy
arranged linearl
in memory.
in memory. This
This arrangement
arrangement is is shown below.
shown below.

8[0][0] s[0][l]
s[0][0] 8[0][1] s[l][0] s[l][l] s[2][0]
8[1][0] 8[1][1] s[2][l] s[3][0]
8[2][0] 8[2][1] s[3][l]
8[3][0] 8[3][1]

1~1~lml~I~I~I~lnl
100 56 127 67 345 34 167

4002
4002 4004
4004 4006
4006 4008
4008 4010
4010 4012
4012 4014
4014 4016
4016

Figure 8.5 Arrangement


Figure 8.S Arrangement of
of 2-0
2-D array
array in
in memory
memory

(d)
(d) A 2-0
A 2-D array
array can
can be
be declared
declared and
and initialised
initialised at
at the
the same
same place.
place.
When this
When this is done, mentioning
is done, mentioning the
the row
row dimension
dimension is optional.
is optional.
Such
Such aa declaration
declaration would
would look like:
look like:

static int S[4][]


s[4][]== {{
100,56,
100,56,
127,67,
127,67,
345,34,
345,34,
167,72
167,72
}} ;;

(e)
(e) A
A 2-D
2-D array
array can
can be be considered
considered as as an
an array
array ofof aa number
number of 1-D
of 1-0
arrays. Since all that the compiler remembers about
arrays. Since all that the compiler remembers about a 1-0 array a 1-D array
is its
is its base
base address,
address, to to remember
remember aa 2-0 2-D array
array it
it obviously
obviously mustmust
be remembering
be remembering aa series series ofof base
base addresses
addresses of of the 1-D arrays
the 1-0 arrays
present in
present it. Thus,
in it. Thus, if if we
we consider
consider thethe 2-D
2-0 array
array s[4][2], the
5[4] [2], the
base addresses of the four 1-D arrays would
base addresses of the four 1-0 arrays would be stored in 5[0],be stored in s[0],
s[l], s[2], s[3]. Naturally,
5[1],5[2],5[3]. Naturally, the the expression
expression 5[2]
s[2] + 11 would
would givegive
the address
the address of of the
the first
first element
element in in the
the second
second 1-D 1-0 array. The
array. The
value at
value at this
this address
address can can be
be obtained
obtained by by the
the expression
expression *( *( 5[2]
s[2]
+ 1 ) . But as we learnt in 1-D arrays, s[2] can
+ 1 ). But as we learnt in 1-0 arrays, 5[2] can be expressed in be expressed in
pointer notation
pointer notation as as *(*( s5 + 22 ).
). Therefore
Therefore *( *( s[2]
5[2] ++ 11 )) can
can bebe
expressed as
expressed as *(
*( *(*( 5s + 2)
2 ) + 11). Thus, it
). Thus, it can
can be
be deduced
deduced thatthat the
the
A Tryst
Tryst with
with Arrays
Arrays· 269

expressions 's[2]
expressions s[2][l] and *(
[1] and *(*(s + 22 )) ++ 1l )) both
*( s + both refer
refer to
to the
the same
same
element present
element present in
in the
the first column of
first column the second
of the row.
second row.

Array of Pointers
Array Pointers
The way
The way there
there can can be
be an array of
an array of ints
ints or
or an
an array
array ofof floats, similarly
floats, similarly
there can
there can be be an array of
an array of pointers.
pointers. Since
Since aa pointer
pointer variable always
variable always
contains an
contains an address,
address, an an array
array of
of pointers
pointers would
would be be nothing
nothing but
but aa
collection of
collection of addresses.
addresses. The The addresses present in
addresses present in the array of
the array pointers
of pointers
could be
could be addresses
addresses of of isolated
isolated variables
variables or or addresses
addresses of of array
array ele-
ele-
ments or
ments or any
any other addresses. All
other addresses. All rules
rales that
that apply
apply toto an ordinary array
an ordinary array
apply in
apply in toto
toto to the array
to the array ofof pointers
pointers asas well.
well. The
The following
following figure
figure
shows the
shows the contents
contents and and arrangements
arrangements of of an
an array
array ofof pointers called
pointers called
arr. As you can observe, arr contains addresses
arr. As you can observe, arr contains addresses of isolated int of isolated int
variables i,
variables i, jj,, k
k and
and II..

I Jj K
k 1

o
» 1 o o o
4008
4008
5

5116
5116
19

6010
6010
71

7118
7118
Suppose the
Suppose the following statements are
following statements are now
now executed:
executed:

arr[0]
arr[O] ==&i&i arr[1]= =&j&j
arr[1] arr[2]
arr[2] = &k= &k arr[3]
arr[3] = &1= &l
The contents of
The contents of the
the array
array arr
arr would
would now
now be:
be:

ARR[0]
arr[O] ARR[L]
arr[l] ARR[2]
arr[2] ARR[3]
arr[3]

4008
4008

7602
7602
5116
5116

7604
7604
6010

7606
7606
7118
7118

7608'
7608 ~_j
Figure 8.6 Array
Figure 8.6 Array of
of pointers
pointers
270
270 Exploring C
Exploring C

Exercise
Exercise

[A]
[A] What
What will
will be the
the output
output of the
the following
following programs:
programs:

(1) main()
main()
{{
int
-jilt8[5], ii ;;
a[5],
static int
static int b[5]
b[5];;
( i =
for ( i 0 ;; ii < 55 ;; i++)
for 0 itt )
printf ("%d %d
printf ("%d %d %d\n",%d\n", i,a[i],
i, ali], b[i]);
b[i]) ;
}

(2) main()
main()
{{
static int
static int sub[5] = {{10,20,30,40,50};
sUbf5] = 10, 20, 30, 40, 50} ;
h1li ;
inti;
for ( i = 0 ; i <= 4 ; itt ) ;
for ( i = 0; i <= 4; i + + ) ;
{
{
if (i <= 4)
if(i<=4)
{
{ sub[ij = i * i;
sub[i]
printf (="%d\n",
i * i; sub[ij ) ;
printf ("%d\n", sub[i]);
}
}
}}
}

(3) int
int b[5];
b[5] ;
main()
main()
I{
static
static int a[5];
a[51 ;
int i;
i;
for
for (( ii == 0;
0 ; ii <=
<= 44;; i++)
itt )
printf
printf (("%d%d\n",b[i],a[ij);
"%d %d\n", b[i], ali] ) ;
}}
A
A Tryst with Arrays
TrystwithArrays 271
271

((4)
4) main()
main()
{{
static float
static arr[] == {{ 11.2,
float arr[] . 2 , 112,
2 , 22.4,
. 4 , 24,
2 4 , 3.5,
3 . 5 ,35}
3 5 } ;;
int i; ,
int i;
for ((ii == 00 ;; ii <=
for <= 55; ; i++)
it+ )
printf ("%f", arr[i]);;
printf ( "%f ", arr[i])
}}

(5)
(5) main()
mainn
{{
int size
int =
size = 1100 ;;
int arr[size] ;
int arr[size];
for ( i = 1 ; i <= size; iff )
for
{ (.i = 1 ; i <= size; i++)
{ '
scant ("%d", &arr[ij ) ;
scanf ("%d",&arr[i]);
printf ("\n%d·, arr[i] ) ;
} printf ("\n%d", arrp]);
}' }
}

((6)
6) main()
main()
{{
int i,i, jj = 10,
int = 10, arrsize;
arrsize ;
int arr[arrsize];;
int arr[arrsize]
if (j == == 10)
10)
arrsize == 20
arrsize 20;
else
else
arrsize = 40
arrsize 40 ;
=
for ( ii = 0 ;; i < arrsize; i++))
arrsize ; i++
arr[i] == 100
arrp] 100;;
}
}

(7) main()
main()
{{
intarr1[10],arr2[10],
int arr1 [10], arr2{1 0], i;i;
for ( ii = 0 ;; i <= 9 ; if+
i++))
{{
272 ' Exploring
Exploring C

arr1[0 = 'A' + i;i;


arr1[ij
arr2[i] = 'a' + ii;;
arr2[ij
printf ("%d", arr2[i]-arr1[i]);
( "%d ', arr2[ij - arr1[i]) ;
}}
}}

((8)
8) main()
main()
{{
static int
static b[} == {{ 110,
intb[] 0 , 20,
2 0 ,30,
3 0 ,40,
4 0 ,50}
5 0 } ;;
int i;
inti;
for
for (( ii =
=00 ;; ii <=
<= 44 ;; iff
i++))
printf
printf ("%d", i[b]);;
( "%d ., i[b))
}

(9)
(9) main()
main()
{{
static
static intint array[10}
array[10] = = {{ 1,
1 , 2,
2 ,3, 4 , 5,
3 ,4, 5 , 6}
6 } ;;
int i;
inti;
for ((ii == 00 ;; ii <=
for <= 99 ;; iff
i++))
printf (("%d",array[ij);
printf "%d ., array{i1) ;
}

(10)
(10) main()
main()
{
{.
static
static int t a ( ]=={ {2,
i n a(] 2 ,3,3 ,4,4 ,5,
5 ,6}6 } ;;
int i;
inti;
for(i=5;i>0;)
for ( i = 5 ; i > 0 ; )
printf ( "%d .," ,a(--i])
printf ("%d a [ - i ] ) ;;
}

((11)
11) main()
main()
{{
stjltic
static int a(5] == {{ 5,
inta[5] 5 , 110,
0 , 15,
1 5 ,20,
2 0 ,25}
2 5 } ;;
inti,
int i, j, m, n;
n;
i = ++a[1]
++a[l];;
jj == a[1]++
a[1]++;;
A Tryst
Tryst with
withArrays
Arrays 273
273

printf ("i = %d ji = %d a[1]


printf ("i a{1] = %d\n", i,i, j,i, al1])
a l l ] ) ;;

1i ==11;;
mm == a(i++];
a[i++]; .
printf ( "i == %d m == %d\n", i,i, m
printf ("i m)) ;

ii=2;
= 2;
n = a{++ij;
a[++i];
printf
priritf( ("i"i = %
%dd n = %d", ii,, n)
n ) ;;
}

((12)
12) main()
main()
{{
int arr(25),
arr(25), i; i;
for ((ii = 0;
0 ; it <=
<= 100
100;; itt
t++)
)
{{
arr(i) 100;
arr(O = 100;
printf
printf (( "%d
" % d",a arrm
r r ( i ) ) ;;
}}
}

((13)
13) main()
main()
{
{
static int
static int a[
a[]] == {{ 110,
0 , 20,
2 0 , 30,
3 0 , 40,
4 0 , 50}
5 0 } ;;
int I:
int j; . .
for ( ji = 0 ;; ij < 5 ;; i++
j++))
{ ,
{ '
printf (("%d",*a);
"%d", *a) ;
aft ;
a++;
}}
}}

(14) main()
main()
{{
Static a[] = {{13.24,1.5,1.5,
float a{]
static float 5.4,3.5};
13.24, 1.5, 1.5, 5.4, 3.5 } ;
float *j, *k;
*k ;
274
274 Exploring
Exploring C

j ==a;a ;
kk=a+4;
=a+4;
H *2;
j =j*2;
kk=k/2;
=k/2;
printf (("%f%f",*j,*k);
printf "%1 %1",*j, *k) ;
}

((15)
15) main()
main()
{{
int
int n[25]
n[25];;
n[O] =
n[0] = 100;
100;
n[24] == 200;
200;
printf ("%d %d", *n,
printf ("%d %d", *n, **(( nn ++ 224) *( nn ++ 0)
4 ) ++ *( 0 )) ;
}

((16)
16) main()
main()
{{
static
static int int b[] == {{ 110, 0 , 20,
2 0 ,30,
3 0 ,40,
4 0 ,50
5 0}} ;
int i,i, *k;
int *k;
kk -::&&b[4]
b [ 4 ] -- 44 ;;
for ( ii = 0 0 ;; i <= <= 44 ;; iH
i++))
{{
printf (( "%d
printf " % d"," ,*k)
*k);
kH; ;
k++
}}
}

((17)
17) main()
main()
{{
static inta[]
static int a[] = {{ 2, 2 , 4,
4 , 6,
6 , 8,
8 , 10}
10} ;
int i;
inti; ,
for
for (( ii == 00 ;; ii <=
<= 44 ;; iH
i++))
I
{.
* ( aa ++i )i )= =a [a[ij
*( i ] ++ i[a];
i[a] ;
printf
printf ("%d", * ( i ++ a)
( "%d ", *( i a ) )) :;
}}
A Tryst with Arrays 275

} .

((18) main()
1 8 ) main()
{{
static
static int int a[5]
a[5] == { 22,, 44,, 66,, 88,, 11O}
0 } ;;
int i,i, bb == 55;;
int
for ( i = 0 ; i < 5 ; i++)
for(i=O;i<5;i++)
{{
ff( (a{ij,
a [ g , &&b)
b ) ;;
printf ("%d%d\n",a[i],b);
printf ( "%d %d\n", a[i], b) ;
}}
}

x , yy))
ff ( (x,
int
int x, X, **yy ;;
{
{
xx == *( y ) ++== 22;;
* ( y)
}}

((19)
19) main()
{{
static int
static int a[5]
a[5] == {{ 22,, 33,, 44,, 55,, 6€ }};;
int i
inti; ;
change (a)
change ( a ) ;;
for (( ii == 44;; ii == 00;; i--
for i-))
prinrf( "%d", a[ij
rrintf( "%d " a(0); );

change (b) (b)


int *b;
int * b ;
{{
int ii;;
int
for ( i == 00 ;; ii <=
for (i <= 44 ;; itt
i++))
{
{
*b = *b + 1 ;
*b = *b + 1 ;
b++ ;
b++;
}
276
276 Exploring
Exploring C

. }}

(20)
(20) main()
main()
{{
int arr[] ='= {O,
int arr[] { 0 , 1,
1 , 2,
2 ,3,3 ,4}4 } ;;
int i, *ptr;
int i, *ptr;
for (ptr
for ( ptr ::= &arr[O]
&arr[0];; ptrptr <= &arr[4] ; ptr++
<= &arr[4]; ptr++))
printf ( "%d .,
printf ("%d ",*ptr);*ptr) ;
}}

(21)
(21) main()
main()
{{
int = { 0 , 1,
arr[1 ::;{O,
intarr[) 1 , 2,
2 ,3,
3 ,44 }} ;;
int
int i,i, *ptr;
*ptr;
for
for ({ptrptr == &arr[O],
&arr[0], ii == 00 ;; ii <=
<= 44 ;; iff
i++))
printf ( "%d .,
printf ("%d",ptr[i));ptr[ij ) ;
}}

(22)
(22) main()
main()
{{
int arr[J =
int arr[] = {O,
{ 0 ,1, 1 ,2,2 ,3,3 ,4}4 } ;;
int i,i, *p;
int *p;
for arr, ii == 00 ;; pp + ii <=
for (( pp == arr, arr + 44 ;; PH,
<= arr p++, iH)
i++)
printf ( ·%d ., *(
printf ("%d",*(p + i ) ) ;P + i) ) ;
)
(23)
(23) main()
main()
{{
int arr[] == {O,
int arr[] { 0 , 1,
1 ,2,
2 ,3,
3 ,44 }} ;;
int i, *ptr
int i, *ptr; ;
for ptr == arr
for ((ptr ptr == arr
arr ++ 44 ;; ptr arr;; ptr -- )
ptr--)
printf ("%d
printf ( '%d "",*ptr);
*ptr) ;
}}

(24)
(24) main()
main()
{{
A Tryst
Tryst with Arrays
withArrays' 277
277

int
int arr[]
arr[ ) == {O,{ 0 , 1,
1 , 2,
2 , 3,
3 ,44 }} ;;
int
int i,i, *ptr
*ptr;;
for
for (ptr
( ptr == arr
printf
arr + 4,
printf ("%d",
°;
4, ii == 0 ; ii <=
ptr[-0);;
( "%d " ptr[-ij)
<= 44 ;; iH
i++))

((25)
25) main()
main()
{{
int arr[] == {O,
int arr[] { 0 , 11,, 2,
2 , 3,
3 , 44 }} ;;
int *ptr, i
int *ptr, i; ;
for (ptr
for ( ptr == arr
arr ++ 44 ;; ptr
ptr >=>= arr;
arr ; ptr--
ptr-))
printf ("%d",
printf ( "%d " arr arr [[ pptrt r-- arr]
a r r ])) ;;
}

((26)
26) main()
main()
{{
static int
static a[] == {O,
int a[] { 0 , 11,, 2,
2 , 3,
3 , 44 }} ;;
static int
static int *p[ ={
*p{ ]1 = { aa,, aa ++11,, aa +t 2, 3, aa ++ 44 }} ;;
2, aa ++ 3,
int **ptr =
int **ptr = p;p ;
printf ("%d%d\n",
printf ( "%d %d\n·, a, a, *a)
* a ) ;;
printf ("%d
printf ( "%d %d %d %d\n",
%d\n", p, *p, **p) ;
p,*p,**p);
printf ( "%d %d %d\n", ptr,'*ptr,
printf ("%d %d %d\n", ptr,'*ptr, **ptr); **ptr) ;
}

((27)
27) main()
main()
{{
static int aa[][ ] =={{O,0 , 1,
static int 1 ,2,
2 ,3,
3 , 4}
4 } ;;
static int *p[ ] = {
static int *p[ ] = { a , a + 1, a ++ 2,
a, a + 1, a 2, aa ++ 3,
3, aa +-l- 44 }} ;;
int **ptr
int **ptr = p; = p ;
ptr++;
ptrH;
printf ( "%d %d %d\n", ptr - p, *ptr - a, **ptr) ,
printf ("%d %d %d\n", ptr - p, *ptr - a, **ptr) •
*ptrH;
*ptr++;
printf ( "%d %d %d\n", ptr - p, *ptr - a, **ptr) ;

printf
*Hptr; ("%d %d %d\n", ptr - p, *ptr - a, **ptr) ;

*++ptr;
2278
78 . Exploring
Exploring C
C

printf ("%d
( '%d %d
%d %d\n",
%cM', ptr
ptr -- p,
p, *ptr
*ptr -- a,
a, **ptr);
**ptr) ;

++*ptr;
++*ptr;
printf ("%d
printf ( "%d %d
%d %d\n",
%d\n', ptr
ptr -- p,
p, *ptr
*ptr -- a,
a, **ptr);
**ptr) ;
}}

(28) main()
main()
{
{
static int
static int a[]
a[] == {O,
{ 0 ,1,
1 ,2,
2 ,3,
3 ,44 }} ;;
static int *P[] = {
static int*p[] = {a, a + 1 , aa ++ 2,
a, a + 1, 2, aa ++ 3,
3, aa ++ 4}
4 } ;;
int **ptr
int **ptr;;
ptr == p;
p;

**ptr++;
**ptr++ ;
printf ("%d
( "%d %d
%d %d\n",
%d\n", ptr - p,
p, *ptr - a,
a, **ptr);
**ptr) ;
*++*ptr;
*++*ptr;
printf ("%d
( "%d %d
%d %d\n",
%d\n", ptr - p,
p, *ptr - a,
a, **ptr);
**ptr) ;
++**ptr;
++**ptr;
printf ("%d
( "%d %d %d\n",
%d\n", ptr - p,
p, *ptr - a,
a, **ptr);
**ptr) ;
}}

(29)
(29) main()
main()
{{
static int
static int n[3][3]
n[3][3] == {{
22,4,3,
,4,3,
6, 8, 5,
6,8,5,
3,5,1
3, 5,1
}};;

I* Assumethat
{* Assume thatarray
arraybegins
beginsatataddress 404* *
address404
printf ("%d
( "%d %d %d",
%d", n, n[2], n[2][2]
n[2][2]);
);
}}

(30)
(30) main()
main()
{{
static int n[3][3] ,~{
«{
AA Tryst
Trystwith
withArrays
Arrays 279
279

22,4,3,
,4,3,
6, 8, 5,
6,8,5,
33,5,1
,5,1
}}; ;
inti,i,*ptr;
int *ptr ;
ptr == nn;;
ptr
printf ("%d",
printf ( "%d ",n[2]);
n[2] ) ;
printf ( "%d ", ptr[2] ) ;
printf ("%d", ptr[2]);
printf ( "%d ", *(
printf ("%d", *( ptr ~r ++ 22 )) )); ;
}

((31)
31) main()
main()
{{
static intn[3][3]
static int n[3][3] = { ={
22,4,3,
,4,3,
6,6,8,5,
8, 5,
3,5,1
3, 5,1
}}; ;
int i,
int i, j ;j;
o r ((i i== 22; ;i i== 00 ;;i i--
ffor - - ))
{
{
for(j;::2;j;::O;j--)
for(j = 2 ; j = 0 ; j ~ )
printf ("%d
printf ( "%d %d\n". *( *( nn ++ i)i) ++ ji)> )) ;;
n[i][J1,*(*(
%d\n', n[i][fl,
}}
}}

((32)
32) main()
{{
static inta[3][3]
static int a{3][3] = { ={
1,2,3,
1,2,3,
4,5,6,
4, 5,6,
7,8,9
7, 8,9
}} ;;
int *ptr[31== {{a(0],a[1],a[2)};
int*ptr[3] a{01,a{1], 8[2J} ;
int **ptr1 = ptr;;
int "ptr1 ;::ptr
int i;
int i; .
for ( i = 0 ; i <= 2 ;; i++
for ( i 0
;:: ; i<= 2 i++))
280
280 Exploring
Exploring C
C

printf
printf ("%d
( ·%d ",*ptr[i]};
", *ptr[q ) ;

printf
printf ( "'In"
V )) ;;
for ( ii == 0;
0 ; i <=
<= 22;; iff
i++))
printf ("%d Y * a [ g) ;;
printf ( "%d ., *a[ij

printf
printf (("\n");
"\n° ) ;
for ( ii= 0;0 ; ii <= 2 ;; i++)
<= 2 iff )
{{
printf ("%d
printf ( '%d .,",**ptr1);
**ptr1 ) ;
ptr1++
ptr1++; ;
}}

(33) main()
main{)
{{
static
static int t[3][2][4] =={{
int t[3][2][4]
{{
2,4,3,6,
2,4,3,6,
1,6,7,9
1,6,7,9
},},
{{
8,2,1,1,
8,2,1,1,
2,3,7,3
2, 3, 7, 3
},
{{
1,6,2,4,
1,6, 2,4,
0, 7, 9. 5
0,7,9.5
}
}
}} ;;
printf f("%d",
% d \ t[2j[1]l3],
t[2][11l3],*(*(*(*(*(*(tt ++2)2)++11) )++3))3)) ; ;
}}

[B]
[B] Attempt
Attempt the following:
the following:

(1)
(1) The
The first
first difference
difference DlD1 of
of aa sequence
sequence AA of
of N
N elements
elements isis
obtained by
obtained by subtracting
subtracting each
each element,
element, except
except the
the last,
last, from the
from the
A Tryst
Tryst with
with Arrays
Arrays 281
281

next element
next element in the array.
in the array. The
The second
second difference
difference 02
D2 is
is defined
defined
as the first difference of 01,
D l , and so on. For example, if

A: 1,1,2,4,7,11,16,
2, 4, 7, 11, 16,22, 22, then
D l : 1,2,3,4,5,6
01: 1, 2, 3, 4, 5, 6
D 2 : 11,, 11,, 11,, 11,, 11
02:
D3:
03: 0, °
0, 0, 0
0,0,0,

Write a program that reads a sequence


sequence of 25 elements in an
array and
array finds its
and finds its first,
first, second,
second, and
and third
third differences.
differences.

(2) A common problem in statistics is that of generating frequency


frequency
distribution Assuming that the data consists
distribution of the given data. Assuming
of 50
of 50 positive integers in
positive integers in the
the range
range 11 to
to 25,
25, write
write aa program
program
that
that prints
prints the
the number
number ofof times each integer
times each occurs in
integer occurs in the
the data.
data.

(3)
(3) A square
A square matrix,
matrix, thatthat is,
is, one
one having
having the
the same
same number
number ofof rows
rows
and columns,
columns, is called a diagonal matrix if its only non-zero non-zero
elements are on the diagonal from upper left to lower right. It It
is called upper triangular, if all elements below the diagonal
are zeroes,
are zeroes, and
and lower
lower triangular,
triangular, if
if all
all elements
elements above the
above the
diagonal are zeroes.
diagonal are zeroes. Write
Write aa program that reads
program that reads aa matrix
matrix and
and
determines
determines ifif it
it is
is one
one of
of these
these three
three special matrices.
special matrices.

(4)
(4) The Miniaturization
The Miniaturization Unlimited
Unlimited sells sells 55 types
types of
of memory
memory chips
chips
through its
through retail outlets
its retail outlets inin 10
10 cities.
cities. The
The weekly
weekly sales
sales of the
of the
company are stored
company are stored iinn aa 55 xx l10
0 xx 77 array
array SALES
SALES such that
such that
SALES(
SALES( L,L, K,
K, MM)) denotes
denotes the the sales
sales of
of the
the L*
L th memory
memory chip in
chip in
the Kth
K city on the M
th Ih
Mth day of the week. Write a program that
computes:
computes:

(a)
(a) The total
The total weekly
weekly sale
sale of
of each
each type
type of
of memory chip
memory chip
(b) The total weekly sale in each city and
( c) average daily sale of the company
The average

(5) You have been called upon to write a match-making program


for aa marriage
for beaureau. The
marriage beaureau. beaureau's questionnaire
The beaureau's questionnaire has
has 8~

L
282
282 Exploring C
Exploring C

statements, and
statements, and the
the applicant
applicant indicates
indicates her
her or
or his
his degree
degree of
of
agreement on
agreement on aa scale
scale of
of 11 to
to 5.
5. The
The response
response of
of the
the applicant
applicant
is entered
is through the
entered through the keyboard.
keyboard. EachEach response
response contains the
contains the
applicant's code
applicant's code number,
number, sexsex (F
(F oror M),
M), and
and responses
responses toto the
the
questionnaire (8
questionnaire (8 integers).
integers). You
You may
may assume
assume that
that there
there are no
are no
more than
more than 50
50 applicants.
applicants.

Your program
Your program should
should match
match each
each person
person with
with the
the three
three most
most
compatible persons
compatible persons ofof the opposite sex,
the opposite sex, and
and should print the
should print the
code number
code number of of the applicants along
the applicants along with
with the
the code
code numbers
numbers of of
their prospective mates. As a measure of compatibility
their prospective mates. As a measure of compatibility of two of two
persons, use
persons, use the
the cosine
cosine of
of difference
difference between
between the responses;
the responses;
the larger
the larger the cosine, the
the cosine, the more compatible the
more compatible the couple.
couple.

(6)
(6) A
A magic
magic square
square isis an
an n
nxxn matrix, where
n matrix, where each
each of
of the integers
the integers
1,
2
n n,2, appear
1, 2, 33, ,..., appear exactly
exactly once
once and
and the
the sums
sums ofof every
every row
row
column, and
column, and diagonal
diagonal areare equal.
equal. It
It has
has been
been proved
proved that for
that for
even values of n, no magic square exists. Here is a magic
even values of n, no magic square exists. Here is a magic square square
for nn =
for = 3:3:

88 11 66

33 55 77

44 99 22

Figure 8.7 Magic


Figure 8.7 Magic square
square

The following
The following is
is aa procedure
procedure for
for constructing
constructing an
an nn xx nn magic
magic
square for
square any odd
for any odd integer
integer n.
n.

Place initial
Place initial number
number in
in the middle of
the middle of the top row.
the top row. Then
Then after
after
integer kk has
integer has been
been placed,
placed, move
move up
up one
one row
row and
and one
one column
column
___________ A Tryst with Arrays
--=A:..=...=T...:..ryl,.;;.s;.;..t~with
Arrays 283
283

to the
to the right
right to
to place the next
place the next integer
integer kk + 1,
1, unless
unless one
one of
of the
the
following occurs:
following occurs:

(a)
(a) If aa move
If move takes you above
takes you above the
the top
top row
row inin the
the jth
j * column,
column,
move 'to
move to the
the bottom
bottom ofof the
the jjth* column
column and and place the
place the
integer there:
integer there.
(b) If
If aa move
move takes
takes you
you outside
outside to
to the
the right
right of
of the
the square
square inin
the th row,
the ii* row, place
place the
the integer
integer in
in the th row
the ii* row at
at the
the left
left side.
side.
(c) If
If aa move
move takes
takes you
you toan
to an already
already filled
filled square
square or or if
if you
you
move out
move out of
of the
the square
square at
at the
the upper-right-hand
upper-right-hand comer, corner,
place kk + 11 immediately
place immediately below
below k. k.

Write aa program
Write program to
to construct
construct aa magic
magic square
square for
for any
any odd
odd integer
integer
n.
n.
284
284 Exploring C
Exploring

Answers
Answers

Answers to [A]

(1)
(1) Output
Output

001000
1000
11 -750
-750
221230
1230
312450
312450
443470
3470

Explanation
Explanation

Since the
Since storage class
the storage class of
of the
the array
array a[a[]] has
has not been mentioned,
not been mentioned,
the default
the default storage
storage class auto is
class auto assumed for
is assumed for it.
it. As
As against
against this,
this,
the storage
storage class of b[] has been explicitly mentioned as static.
ofb[] static.
The default value of auto
auto storage class variables
variables is any garbage
value and the default value of staticstatic storage class variables
variables is
0. Therefore all zeroes
O.Therefore zeroes are printed
printed out for b[],
b[ ], whereas
whereas garbage
garbage
values are
values printed out
are printed out for
for a[
a[].].

(2)
(2) Output
Output

No output

Explanation
Explanation

Surprised? You
Surprised? You expected
expected numbers
numbers like
like 100,
100, 400,
400, 900,
900, etc. to
etc. to
be printed. Then
be printed. Then what
what went
went wrong?
wrong? Look
Look atat the for loop
the for loop
carefully. There is a semicolon
semicolon at the end of it. Thus the loop
is reduced to
is reduced to the
the following
following form:
form:

for ( i.i== 00 ;; i <=


<= 44 ;; iff
i++))
A Tryst
Tryst with Arrays
withArrays 285
285

This loop
This loop repeats
repeats the
the null
null statement
statement (( ;; )) 55 times
times and
and then
then the
the
control comes
control comes out
out of
of the.
the loop.
loop. AtAt this
this time
time the
the value
value ofof ii has
has
become 55 and
become and hence
hence thethe ifif condition
condition fails
fails and
and the control
the control
reaches the
reaches the closing
closing brace
brace ofof main().
main(). The
The execution
execution is therefore
is therefore
terminated wi
terminated without any output
thout any output to to the
the screen.
screen. Take
Take care
care not
not to
to
place aa semicolon
place semicolon after
after for. IfIf you
you do
do so,
so, now
now you
you know
know whom
whom
to blame.
to blame.

(3)
(3) Output
Output

00
00
00
00
00
00
00
00
00
00

Explanation
Explanation

Default initial
Default initial value
value of
of aa static
static or
or extern
extern storage
storage class
class variable
variable
is o. Thus,
is 0. Thus, though
though thethe arrays
arrays b[
b[ ]] and
and a[a[ ]] have
have not
not been
been
initialised, the
initialised, the fact that their
fact that storage class
their storage class is
is extern
extern and
and static
static
respectively causes
respectively causes their
their default
default initial
initial values
values toto be o. Hence
be 0. Heoce
the output.
the output.

(4)
(4) Output
Output

1.200000 12.000000 2.400000


1.20000012.000000 2.400000 24.000000
24.000000 3.506000
3.500000 35.000000
35.000000

Explanation
Explanation

Were you
Were you expecting
expecting anan error
error message
message because
because inin the
the array
array
initialisation some
initialisation some values
values areare integers whereas others
integers whereas others are'
are
floats? Well,
floats? Well, the
the initialisation
initialisation is
is perfectly
perfectly alright.
alright. When
When wewe
286
286 Exploring C
Exploring C

initialise arr[l]
initialise arr[l] toto aa value
value 12,
12, what
what really
really gets
gets stored
stored in
in arr[l]
arr[l]
is 12.0.
is 12.0. Same
Same thing happens when
thing happens when we try to
we try to store
store 24
24 or
or 35
35 inin
the array.
the array. They
They are
are promoted
promoted to to Doats
floats before
before storing
storing the
the values.
values.
Thus the
Thus the array
array contains
contains all floats, thereby
all Doats, thereby meeting
meeting the basic
the basic
requirement of
requirement of the array that
the array that all
all its elements must
its elements must be similar.
be similar.
Since
Since printf()
priBtf( ) always
always prints
prints aa float with aa precision
Doat with precision of
of 66 digi
digits
ts
after the
after the decimal
decimal point,
point, each
each array
array element
element has
has been
been printed
printed
with six
with places "after
six places after thethe decimal point.
decimal point.

(5)
(5) Output
Output

Error message:
Error message: Constant
Constant expression required in
expression required in function main
function main

Explanation
Explanation

While declaring
While declaring the
the array,
array, its
its size
size should always be
should always be mentioned
mentioned
with aa positive
with integer constant.
positive integer constant. Thus
Thus arr[lO]
arr[10] is
is acceptable,
acceptable,
whereas arr[size]
whereas arr [size] is
is unacceptable,
unacceptable, irrespective
irrespective of
of whether
whether size
size
has been
has declared earlier
been declared earlier to
to array
array declaration
declaration or
or not.
not. Hence the
Hence the
error message.
error message.

(6) Output
Output

Error message:
Error Constant expression
message: Constant expression required
required in function main
in function main

Explanation
Explanation

Depending upon
Depending upon thethe value
value ofj,
ofj , we
we are
are attempting
attempting to to determine
determine
the value
the value of
of arrsize,
arrsize, andand then
then expecting
expecting this
this value
value to to be
be used
used
in the
in the array declaration. This
array declaration. This isis too
too ambitious,
ambitious, because
because whenwhen
the array
the array declaration
declaration statement
statement is is executed,
executed, C C has
has to
to know how
know how
much space
much space is
is to
to be
be reserved
reserved for the array.
for the array. So,
So, if
if we
we expect
expect that
that
the size
the size of the array
of the array can
can bebe determined
determined in in if,
if, and
and then
then this
this size
size
should be
should be used
used to to declare
declare the
the array,
array, then
then byby the
the time
time control
control
reaches the
reaches the if
if it
it has
has already lost the
already lost the opportunity
opportunity to to declare
declare the
the
A Tryst
Tryst with Arrays
withArrays 287
287

array.
array. Moral
Moral is,
is, nothing
nothing else
else except
except aa positive
positive integer
integer is accept-
is accept-
able
able in
in the
the array
array size declaration.
size declaration.

Suppose
Suppose we we declare
declare an an array
array saying arr[25] and
saying int arr[25] and then later
then later
in
in the
the program
program feel feel that
that this
this much
much space
space isis not
not sufficient and
sufficient and
we
we wish
wish to to store
store aa few
few more
more elements
elements in in the
the array,
array, then
then can we
can we
change
change the the size
size of
of the
the array
array during
during execution
execution of of the program?
the program?
By
By nono means.
means. Once Once youyou have
have declared
declared thethe size
size of
of the
the array its
array its
size
size can
can never
never be be changed
changed during
during program
program execution.
execution. In In that
that
sense
sense wewe can can say
say that
that the
the memory
memory allocation
allocation of of anan array
array isis
static,
static, i.e.
i.e. it
it cannot
cannot be be changed
changed on on the
the run
run during
during execution.
execution. To To
overcome
overcome this this limitation
limitation C C provides functions like
provides.functions malloc()
like~moc()
and
and calloc(
calJoc( ), ), which
which dynamically
dynamically allocate memory/during
allocate memory during
execution.
execution. This This memory
memory can can be
be increased
increased or or decreased
decreas d as as per
per
the
the program's
program's need need during
during program
program executi
execution.on. '

(7)
(7) Output
Output

32323232323232323232
323232 32 32 32 32 32 32 32

Explanation
Explanation

arrl[ ] and arr2[


arr1[]and arr2[] ] are
are declared
declared as as arrays
arrays capable
capable of of storing
storing 1010
integers.
integers. Through
Through thethe for
for loop
loop we
we are
are storing
storing numbers
numbers from from 6565
to
to 74
74 in
in arrl[
arr1[ ]] and
and numbers
numbers fromfrom 9797 toto 106
106 inin arr2[
arr2[ ].]. How
How
come?
come? Because
Becau.se whenever
whenever we we mention
mention 'A' 'A' it
it is
is replaced
replaced by by its
its
ascii
ascii value
value 65,
65, whereas
whereas 'a''a' is
is replaced
replaced by by its
its ascii
ascii value
value 97.
97.
Therefore,
Therefore, the
the operation
operation 'A''A' ++ ii is
is perfectly
perfectly acceptable,
acceptable, as as itit
just
just adds
adds value
value of
ofii to
to 65.
65. Once
Once the
the values
values areare stored
stored inin the
the two
two
arrays,
arrays, the
the difference
difference of of the
the values,
values, i.e.
i.e, 32,
32, is
is printed
printed through
through
the
the printf().
printf( ).

(8)
(8). Output
Output

10203040
102030405050

L
288
288 Exploring C
Exploring C

Explanation
Explanation

Using i[b] in any other


other language
language would
would have
have definitely resulted
resulted
into an
into error. But
an error. But 110t
not iinn C.
C. Why?
Why? Because
Because all other languages
all other languages
use pointers to
use pointers to access
access array
array elements,
elements, but
but somehow
somehow hide hide this
this
fact from the
fact from the user.
user. Whereas
Whereas C C says
says that
that if
if II am
am going
going to to use
use
pointers internally
pointers to access
internally to access array
array elements,
elements, then
then let
let the user
the user
as
as well
well know
know it.it.

When we
When we mention
mention the
the name
name of of the
the array,
array, we
we get get its
its base
base
address. When
address. When wewe say bp], internally
say b[i], internally CC converts
converts thisthis to
to *(
*( bb +
ii )),, which
which means
means value
value at
at the
the address
address which
which isis ii locations
locations after
after
the
the basebase address.
address. Now
Now you
you would
would agree
agree that
that *(
*( b b + ii )) is same
is same
as
as *( *( ii + b
b ),
), which
which is
is same
same asas i[b].
i[b]. Therefore,
Therefore, the the above
above for for
loop prints the
loop prints the array
array elements
elements stored
stored in
in the
the array
array b[].b[ ].

(9)
(9) Output
Output

11234560000
234560000

Explanation
Explanation

The array has been declared to be capable of holding 10 10


integers, but while
integers, but while initialising
initialising the array only
the array only 66 elements
elements areare
stored
stored inin it. This is
it. This is perfectly
perfectly acceptable.
acceptable. WhatWhat would
would be be the
the
values
values of the elements
of the elements thatthat have
have not
not been
been initialised? Garbage
initialised? Garbage
or zero? Since
or zero? Since thethe storage
storage class of the
class of the array
array has
has been declared
been declared
as static, the
as static, rest of
the rest of the
the elements
elements havehave aa value
value O.This
0. This is
isbecause
because
by
by default, any static storage class variable has a value 0.
default, any static storage class variable has a value This
O.This
fact is justified
fact is justified by by the
the output
output ofof the
the program
program which
which shows
shows thethe
last
last four
four elements
elements as as 0, whereas the
0, whereas the first
first six
six elements
elements areare
having
having thethe values
values to which they
to which they have
have been
been initialised
initialised inin the
the
array declaration.
array declaration.

(10) Output
(10) Output
A Tryst
Tryst with Arrays
withArrays 289
289

665432
5432

Explanation
Explanation

'Dimension of
'Dimension of the
the array
array not
not mentioned'. Possibly you
mentioned'. Possibly you expected
expected
this error
this error message.
message. But But no
no such
such error
error message
message is displayed.
is displayed.
Does that
Does that mean
mean that
that we can drop
we can drop the
the dimension
dimension while declaring
while declaring
the array?
the array? Yes,
Yes, provided
provided we we are
are initialising
initialising the
the array
array at
at the
the
same place
same place where
where we we are
are declaring
declaring it.
it. And
And in
in this
this program
program this
this
is what
is what we
we are
are doing.
doing. So,So, the
the compiler
compiler gets
gets past
past the declaration
the declaration
without faltering for a second.
without faltering for a second.

In the-for
In the. for loop,
loop, printf()
printf( ) uses uses the expression a[--i].
the expression a[--i]. Can
Can -- ~
operator be
operator be used
used with
with an array subscript?
an array subscript? By By all
all means.
means. Here,
Here,
since --
since —precedes
precedesi,i,firstly
firstly i iisisdecremented
decrementedand andthen
thenitsitsvalue
value
is used
is used inin accessing
accessing thethe array
array element.
element. Thus,
Thus, first
first time through
time through
the for
the for loop,
loop, when
when the
the, control
control reaches
reaches a[--i]
a[--i] with
with ii equal
equal toto 5,
5,
firstly i is reduced to 4 and then this 4 is used to access
firstly iis reduced to 4 and then this 4 is used to access the array the array
element a[4].
element a[4]. This
This is
is done
done repeatedly
repeatedly through
through thethe for loop till
for loop till
ah the
all the array
array elements
elements have
have been
been printed.
printed.

(11) Output
(11) Output

ii == 11
11 j j == 11
11a[1]
a[1] == 12
12
ii=2m=12
= 2 m = 12
ii=3n=20
= 3 n = 20

Explanation
Explanation

In =
In ii = ++a[1],
++a[l], since
since ++
++ precedes
precedes a[l],
a[1], firstly
firstly the
the value
value of of a[l],
al l],
i.e. 10
i.e. 10 would
would bebe incremented
incremented to to 11,
11, and
and then assigned to
then assigned the
to the
variable i.i. As
variable As against
against this,
this, in
in the
the next
next statement,
statement, firstly
firstly the
the
element a[l]
element (i.e. 11)) would
a[1] (i.e.l1 would be
be assigned
assigned totojj and
and then
then the
the value
value
of a[l]
of a[1] would
would bebe incremented
incremented to to 12.
12. The
The values
values ofof i,
i, jj and
and a[l]
a[l]
arc then printed out.
are then printed out.
290
290 Exploring C
Exploring

Next, iiis
Next, is reset
reset to 1. In
to 1. In m
m = a[i++],
a[i++], since
since ++++ succeeds
succeeds i,
i, firstly
firstly
ali], i.e.
a[i], i.e. 12
12 is
is assigned
assigned to to variable
variable m,
m, and
and then
then the value of
the value of i,
i,
i.e.
i.e. 1, is incremented
1, is incremented to to 2.
2. The
The values
values ofi
of i and
and m
m are
arethen
then printed
printed
out.
out.

After that ii is once again reset to 2. In D n = a[++i]


a[++i] since ++
precedes i,
precedes firstly it
i, firstly it is
is incremented
incremented toto 33 and
and then
then the
the value
value of
of
a[3], i.e.
a[3], i.e. 20 is assigned
20 is assigned to the variable
to the variable n.
D. Finally,
Finally, the values of
the values of
ii and
and D
n are
are printed
printed out.
out.

(12) Output
(12) Output

Error message:
message: Function definition out of place in function
function
main
main

Explanation
Explanation

People who
People who migrate
migrate to
to CC from
from Basic
Basic oror Fortran
Fortran are
are likely to
likely to
commit this
commit this error.
error. For
For arrays, C uses
arrays, C square brackets,
uses square whereas
brackets, whereas
Basic
Basic oror Fortran
Fortran use
use parentheses.
parentheses. TheThe moment
moment the compiler
the compiler
finds
finds (( )),, it
it expects
expects aa reference
reference to
to aa function,
function, and
and arr
arr has not
has not
been defined as a function. Hence the error
been defined as a function. Hence the error message. message.

Would the
Would the program
program work
work if if we
we change
change arr(25)
arr(25) and
and arr(i) to
arr(i) to
arr[25]
arr[25] and arr[i]? Well,
and arr[i]? Well, wewe can't
can't say.
say. This
This is
is because
because in
in the
the
for
for loop
loop we are storing
we are elements beyond
storing elements arr[24], which
beyond arr[24], which is the
is the
last legal array
last legal array element.
element. ItIt means
means wewe are
are exceeding
exceeding the
the bounds
nounus
of
of the
the array.
array. Would
Would we we get
get an
an error
error message?
message? Certainly not.
Certainly not.
This
This isis because
because C C never
never performs
performs bounds
bounds checking
checking on an array.
on an array.
It
It is always the
is always the programmer's
programmer's responsibility.
responsibility. When
When the
the array
array
is
is declared,
declared, it would reserve
it would reserve 2525 contiguous
contiguous locations
locations inin
memory.
memory. Through
Through thethe for
for loop
loop when
when we
we write
write beyond
beyond arr[24],
arr[24],
it
it might
might overwrite
overwrite something
something important
important which
which might
might bebe
present beyond this element. In worst possible case
present beyond this element. In worst possible case the com- the com-
puter would hang.
puter would hang.
A Tryst
A Tryst with
with Arrays
Arrays 291
291

(13) Output
(13) Output

Error message:
message: Lvalue required in function main

Explanation
Explanation

Whenever we mention the name name of the array, we get its base
address. Therefore,
address. Therefore, first
first time
time ttirough
th.rough the the loop,
loop, the printf())
the printf(
should print the
should print the value
value at
at this
this base
base address.
address. There
There isis no problem
no problem
upto this. The
upto this. The problem
problem lieslies inin the
t h e next
next statement,
statement, a++.
a++. Since
Since
C doesn't perform
Cdoesn't perform bounds
bounds checking
checking on on anan array,
array, the
the only
only thing
thing
that
that it
it remembers
remembers aboutabout an an array
array once declared is
once declared is its base
its base
address. And a++ attempts to change this base
address. And a++ attempts to change this base address, which address, which
C won't allow
C won't allow because
because if if it
it does
does so,so, itit would
would be be unable
unable toto
remember
remember the the beginning
beginning of of tthe
h e array.
array. Anything
Anything which
which cancan
change
change -- in
in compiler's
compiler's langauage
langauagee -- is is called
called lvalue. Since value
lvalue. Since value
of
of aa cannot
cannot bebe changed
changed through
through ++, ++, itit flashes
flashes the error saying
the error saying
•Lvalue required' so that ++ operator can
'Lvalue required' so that ++ operator can change it. change it.

(14) Output
(14) Output

Error message:
Error message: Illegal use of
Illegal use of pointer
pointer in
in function main
function main

Explanation
Explanation

j and k have been declared as pointer pointer variables, which would


contain the addresses of t1oats.
floats. IIn.
n other words,
words,jj and k are floatfloat
pointers. To begin
pointers. To begin with,
with, the
the base
base address
address ofof the
the array
array a[a[ ]] is
is
stored in jj.. The
stored in The next
next statement
statement is is perfectly
perfectly acceptable;
acceptable; the the
address
address of
of thethe 44th float
th
t10at from
from tthe
h e base
base address
address is is stored
stored in
in k.
The next two
The next two statements
statements are
are erron.eous.
erroneous. This
This isis because
because the
the only
only
operations
operations thatthat can be performed
can be performed on on pointers
pointers areare addition
addition and
and
subtraction.
subtraction. Multiplication
Multiplication or or division
division ofof aa pointer, is not
pointer. is not al-al-
lowed. Hence the
lowed. Hence the error
error message,
message.
292
292 Exploring C
Exploring

(15) Output
(15) Output

100300
100300

Explanation
Explanation

n[ ]] has
D[ has been
been declared
declared as as an
an array
array capable
capable of holding 25
of holding 25 ,
elements numbered
elements numbered from from 0 0 to
to 24.
24. Then
Then 100
100 and
and 200 are
200 are
assigned to D[O]
assigned to n[0] and
and D[24]
n[24] respectively.
respectively. Then
Then comes
comes the
the most
most
important part
important part -- the
the priDtf(
printf()) statement.
statement. Whenever
Whenever we mention
we mention
the name
the name of
of the
the array,
array, we
we get
get its
its base
base address
address (Le.
(i.e. address
address ofof
the zeroth
the zeroth element
element of of the
the array
array).). Thus,
Thus, *n would give
*D would give the
the value
value
at this
at this base
base address,
address, which
which inin this
this case
case is
is 100.
100. This
This is then
is then
printed out.
printed out. Look
Look at at the
the next
next expression,
expression,

**(( nn + 24
2 4 )) + *(
* ( nn + 00 ))

n gives
D gives the
the address
address of
of the
the zeroth
zeroth element,
element, nn + 1 1 gives
gives the
the
address of
address of the
the next
next element
element ofof the
the array,
array, and
and soso on.
on. Thus,
Thus, Dn+
24
24 would
would give
give the address of
the address of the
the last
last element
element ofof the array, and
the array, and
therefore *(
therefore *( n
D++ 24)
24 ) would
would give
give the
the value
value atat this
this address, which
address, which
is"200
is "200 in
in our
our case.
case. Similarly,
Similarly, *(
*( nD+ + 00)) would
would give
give 100
100 and the
and the
addition of
addition the two
of the would result
two would result into
into 300,
300, which
which isis outputted
outputted
next.
next.

(16) Output
(16) Output

1020 3040 50
1020304050

Explanation
Explanation

First look
First look atat Figure
Figure 8.8.
8.8. The
The array
array elements
elements are
are stored
stored inin
contiguous memory
contiguous memory locations
locations and
and each
each element
element is
is an
an integer,
integer,
hence is
hence occupying 22 locations.
is occupying locations.
A Tryst
Tryst with Arrays
withArrays 293
293

b[0]
b[O] b[l]
b[I] b[2]
b[2] b[3]
b[3] b[4]
b[4]

10
10 20
20 30
30 40
40 50 |

4002
4002 4004
4004 4006
4006 4008
4008 4010
4010

Figure 8.8
Figure 8.8

The expression
The expression &b[4]
&b[4] gives gives the
the address
address of of b[4]
b[4] (4010
( 4010 in this
in this
case ).
case ). From
From this
this address
address if if we
we subtract
subtract 4, 4, we
we get
get 4002.
4002. Or
Or diddid
you expect
you expect toto get
get 4006?
40061 Remember
Remember that that by
by subtracting
subtracting 4 from
4 from
4010 what
4010 what we mean is:
we mean is: get
get the
the address
address of of an
an integer
integer which
which is is
44 integers
integers to
to the
the left
left of
of the
the integer
integer whose
whose address
address is is 4010.
4010. Now,
Now,
address of
address of the
the integer
integer whichwhich is is 44 integers
integers to to the
the left
left of the
of the
integer whose address is 4010, is the
integer whose address is 4010, is the address 4002. This address 4002. This
address, 4002,
address, 4002, is stored in
is stored in k,
k, which
which has has been
been declared
declared as as aa
variable capable
variable capable of of holding
holding an an integer's
integer's address.
address. First time
First time
through the for
through the for loop
loop *k lICk would
would result
result into
into 10,
10, i.e.
i.e, value
value at the
at the
address
address contained in k. k++ then increments k such that it
contained in k. k++ then increments k such that it
contains the
contains the address
address of of the
the next
next integer,
integer, i.e. 4004. Next
i.e. 4004. time
Next time
.. through
through thethe for
for loop
loop lICk
*k would
would yieldyield thethe value
value at at address
address
contained in k, i.e? value at the address
contained in k, i.e? value at the address 4004, which is 4004, which is 20.
20.
Similarly, the loop prints out the rest of the
Similarly, the loop prints out the rest of the elements of the elements of the
array.
array.

(17) Output
(17) Output

48121620
48121620

Explanation
Explanation

Imbibe the
Imbibe the following
following two
two facts
facts and
and the
the program
program becomes
becomes very
very
simple to
simple to understand:
understand:
294
294 . Exploring
Exploring C

Mentioning
Mentioning thethe name
name of the
the array
array gives
gives the
the base
base address
address
of the array.
of the array.
Array elements
Array elements are
are stored
stored in contiguous
contiguous memory loca-
memory loca-
tions.On adding
tions.On adding 1 to
to the
the address
address of
of an
an integer,
integer, we
we get
get the
the
address of the
address the next integer.
next integer. .

With those
With those facts
facts clearly
clearly laid
laid out,
out, let
let us
us now
now try
try to
to understand
understand
the program. Remember
the program. Remember that that internally
internally C C always
always accesses
accesses
array
array elements
elements using pointers. Thus.when
using pointers. Thus, when we we say
say a~],
a[i], inter-
inter-
nally
nally CC converts
converts it it to
to *(
*( aa +
+ ii),
), w
which means value
hich means value of
of ii integer
integer
from the
from the base
base address.
address. Now, Now, if the expression
if the expression ali]
a[i] is
is same
same as as
*( aa + ii))then
*( then *( *( ii + aa )) must
must bebe same
same as i[a]. But
as ila]. But *(
*( aa + ii )) is
is
same as
same as *(
*( ii +
+ aa )).. Therefore
Therefore ali]afi] must
must bebe same
same asas ila].
i[a].

Thus a[i],
Thus *( aa +
ali], *( + i),
i ) , *(
*( ii +
+ aa )land
and i[a] refer to
ila] refer to the
the same
same element
element
- the
the iili
1 element
th
element from
from the the base
base address.
address.

Therefore the
Therefore the expression
expression used used inin the
the for
for loop,
loop, *(
*( aa +
+ i)
i ) = a[i]
ali]
+ i[a] is
+ i[a] is nothing
nothing but but ali] a[i] = ali]
a[i] ++ ali].
a[i]. Thus
Thus all
all that
that is
is done
done in
in
the
the for loop is
for loop is each
each array array element
element is is doubled
doubled and
and then printed
then printed
out through printf(
out through p r i n t f ( ))..

(18) Output
(18) Output

27
27
49
49
611
611
8813
13
1015
1015

Explanation
Explanation

After initialising
After initialising the
the array
array when control enters
when the control enters the loop,
the for loop,
the function f()
the function f() gets
gets called
called with
with value
value of ali]
afi] and
and address
address of b.
b.
In f()
In f() these
these are
are collected
collected inin variables
variables xx and
and y. Then
Then comes the
comes the
expression
expression xx = *( y )) ++=
*( y = 2.
2. Here
Here *(
*( yy )) ++=
= 22 is
is evaluated
evaluated first
first
r
r
A
A Tryst
Tryst with
with Arrays
Arrays 295
295

and then the result of


of this expression is assigned to x. The first
time through the for loop *( .( y )) gives 5, to which 22 is is added
and the result is stored at *(
.( y ). It
It means 7 is assigned to b. b.,
x

=
Finally, the = operator assigns 7 to x. However, on assigning
aa new
new value
value to
to x,
X; the
the array
array element
element a[0]a[O] inin main()
lDaiD( ) remains
remains
unchanged.
unchanged. Thus,
Thus, during
during every
every call
call to
to ff(( )),, b's
b's value
value keeps
keeps
getting
getting updated
updated whereas
whereas there
there is
is no
no change
change in in the
the values
values of
of the
the
array
array elements.
elements.

a[0] \)

[Q 0 4008

x y

[2J ~

Figure 8.9

(19) Output
Output

776543
6543

Explanation
Explanation

While calling change()


change( ) we are passing the base address of the
array, which as per Figure 8.10 is 4002. This address is col-
lected in b in the function change().
change( ). Then the control enters
the for loop, where we meet the expression *b ·b = *b =
·b + 1. This
means replace the value at the address contained in b, with
. value at the address contained in b plus 1.1. Every time b++ is
executed, the address
address of the next integer gets stored in b. Thus,
296 Exploring
Exploring C

using the
using the address stored in
address stored in b,
b, we
we get an access
get an access to
to array elements
array elements
which are
which are now
now changed
changed toto 3,3, 4, 5, 6 and
4,5,6 and 7.
7. Once
Once the control
the control
comes back
comes back from
from change(),
change(), thethe current array contents
CUJTentarray contents are then
are then
printed out
printed out from
from end
end to
to beginning
beginning through the forloop.
through the for loop.

a[0]
3[0] a[l]
3[1] a[2]
a[2] a[3]
a[3] a[4]
3[4]

22

4002
4002
33

4004
4004
4

4006
4006
5
5

4008
4008
66

4010
4010
1I
bb bb
| b++
b++
~
4002 1 - [2!]4004 |

Figure
Figure 8.10

(20) Output
Output

01234
01234

Explanation
Explanation

Refer to Figure
Refer to Figure 8.11 for
for aa better
better understanding
understanding of
of the
the program.
program.

Here ptr
Here ptr has
has been
been declared
declared as as an
an integer
integer pointer,
pointer, i.e.
i.e. aa variable
variable
capable of
capable of holding
holding the address of
the address of an
an integer.
integer. InIn the
the for
for loop,
loop, in
in
the initialisation
the initialisation part,
part, this
this ptr
ptr isis assigned
assigned the the address
address of of the
the
zeroth element
zeroth element of the integer
of the integer array.
array. Suppose
Suppose this this address
address turns
turns
out to
out to be
be 6004.
6004. Then
Then address
address of of the
the first
first element
element of of the
the array
array
would be
would be 6006,
6006, address
address of of the
the second
second element
element would
would be be 6008,
6008,
and so'
and so on.
on. InIn the
the condition
condition partpart ofof the
the for
for loop,
loop, thethe address
address
stored in
stored in ptr
ptr isis compared
compared with the address
with the address of of the
the fourth array
fourth array
element, i.e. 6012. Since for the first time
element, i.e. 6012. Since for the first time the condition is the condition is
satisfied ( since 6004 is less than 6012 ), the
satisfied ( since 6004 is less than 6012 ), the control reaches control reaches
printf( )) where
printf( where the the value
value at at address
address 6004,6004, i.e.
i.e. 00 gets printed.
gets printed.
A Tryst
Tryst with Arrays
withArrays 297
297

After executing
After executing printf()
printf() the
the control
control reaches
reaches ptr++,
ptr++, where
where ptr
ptr
is incremented such
is incremented such that
that it
it contains
contains the
the address
address of of the next
the next
integer. Since the
integer. Since the next
next integer
integer is is stored
stored at at 6006,
6006, ptr
ptr now
now
contains
contains 6006. Once again
6006. Once again the condition is
the condition is tested.
tested. Since
Since 6006
6006
is also smaller
is also smaller than
than 6012,
6012, thethe condition
condition isis satisfied
satisfied hence
hence the
the
printf() prints out
printf( ) prints out the
the value
value at at 6006,
6006, i.e.
i.e. 1.
1. And
And then
then ptr++
ptr++ isis
executed again so
executed again so that
that it
it contains
contains the
the address
address of of the next
the next
integer,
integer, i.e.
i.e. 6008.
6008. This
This process
process continues
continues tilltill all
all the array
the array
elements have been printed.
. elements have been printed.

arr[0]
arr[O] arrfl]
arr[l] arr[2]
arr[2] arr[3]
arr[3] arr[4]
arr[4]

00 11 22 33 44 I,
|
6004
6004 6006
6006 6008
6008 6010
6010 6012
6012

ptr
ptr ptr
I ptr++
Rtr++
~
6004 J " * E} 6006 |

Figure 8.11
8.11

(21) Output
(21) Output

01234
01234

Explanation
Explanation

In the
In the initialisation
initialisation part
part of
of the
the for loop, multiple
for loop, multiple initialisations
initialisations
are being
are being done.
done. Firstly,
Firstly, ptr
ptr isis set
set up
up with
with the base "addressof
the base address of
the array
the array and
and then
then ii is
is set to o.
set to 0. Since
Since () 0 is
is less
less than
than 4,
4, the
the
. condition
condition isis satisfied
satisfied for
for the
the first
first time
time andand the
the control
control reaches
reaches
printf(). Here the
printf( ). Here the value
value ofof the
the expression
expression ptr[i]
ptr[i] gets
gets printed.
printed.
Now
Now ptr[i]
ptr[i} is
is nothing
nothing butbut *(*( ptr
ptr ++ ii ).
). Since
Since ptr
ptr contains the
contains the
base
base address
address ofof the
the array,
array, ((ptr
ptr + ii )) would
would give the address
give the address of
of
298
298 Exploring C
Exploring

the jth
the i integer
integer from
from the
the base
base address.
address. Since
Since ji is loi:!f
is going toto vary
vary
from 00 to 4,
from 4, this would give
this would addresses of 0Oth,
give addresses , 1 ,2 , 3nl and
, 2 ,3
t h
and
r d

44th integers
t h
integers from the the base
base address
address of the
the array.
array. Naturally,
Naturally, the
the
expression
expression *( *( ptr
ptr + ii )would
) would give
give values
values at at these
these addresses.
addresses.
Thus,
Thus, thethe for loop
loop would.print
would print out
out all
all the
the array
array elements.
elements.

(22) Output
(22) Output

0024
24

Explanation
Explanation

The following figure


The following figure would
would help
help in understanding
understanding the program.
the program.

arr[0]
arr[O] arr[l]
arr[l] arr[2]
arr[2] arr[3]
arr[3] arr[4]
arr[4]

00

6004
6004
11

6006
6006
22

6008
6008
33

6010
6010
4

6012
6012
I
Figure 8.12
Figure 8.12

Note that
Note that in the for loop
in the loop there are multiple
there are multiple initialisations and
initialisations and
multiple
multiple incrementations,
incrementations, each
each separated
separated by by the comma
the comma
operator.
operator. In In initialisation
initialisation part,
part, pp is
is initialised
initialised to to the base
the base
address
address of of the
the array,
array, whereas
whereas ii is
is initialised
initialised to to o.
0. After
After these
these
initialisations
initialisations thethe control
control reaches
reaches the
the condition.
condition. TheThe condition
condition
is aa little
is little complicated
complicated so so let
let us
us isolate
isolate itit for
for aa clearer under-
clearer under-
standing.
standing.

i <= arr + 44
p + i<=

Here enjoys a higher


Here + enjoys higher priority
priority than
than <=. Therefore,
Therefore, first p + ii
and a r r + 44 are
and arr are performed
performed and then the
and then the <= goes
goes to
to work,
work. pp + ii
yields 6004,
yields whereas arr
6004, whereas arr +
+ 44 evaluates
evaluates to
to 6012.
6012. Since
Since 6004
6004 is
is

A Tryst
Tryst with
with Arrays
Arrays 299
299

less than
less 6012, the
than 6012, the condition
condition is is satisfied
satisfied andandthethecontrol
controlreaches
reaches
printf(), where
printf(), where value
value atat (p
( p +.i),
+ i ) , i.e.
i.e. 00 gets
gets printed
printed. Then
Then the
the
control reaches
control reaches thethe incrementation
incrementation part part of thethe for
for loop,
loop, where
where
p++ increments
p++ increments p to to 6006,
6006, and andi++i++ increments
increments ii to to 1. Next,
1. Next,
once again the
once again the condition
condition is is tested-This
tested. This time i gives 6008
time p + igives 6008
(since
( since p isis 6006 and iiis
6006 and is 11 )) and
and arr
arr + + 44 gives
gives 6012
6012. Since
Since the
the
condition
condition once
once again
again gets
gets satisfied,
satisfied, the printf( )) prints
the printf( prints out
out the
the
value
value atat (( p
p + ii)),, i.e.
i.e. 2.
2. Similarly,
Similarly, next next time
time around
around 44 gets
gets
printed and then
printed and the condition
then the condition fails fails therefore
therefore the execution is
the execution is
terminated.,
terminated.,

(23) Output
Output

443210
3210

Explanation
Explanation

The following
The following figure
figure would
would lead
lead to
to aa better
better understanding
understanding of
of
the program.
the program.

arr[0]
arr[O] arr[l]
arr[IJ arr[2]
arr[2] arr[3]
arr[3] arr[4]
arr[4]

I O
0 11 22 33 44
I
|

6004
6004 6006
6006 6008
6008 6010
6010 6012
6012
ptr
ptr ptr
ptr

6012 | ~r-- " ' ~ 6010


** |
• 6010
~

Figure 8.13
Figure 8.13

. In the initialisation
In the initialisation part,
part, ptr is assigned
assigned the address of the
the address the last
last
element in
element in the
the array.
array. This
This is
is because
because arr
arr + 44 gives
gives the
the address
address
of the fourth
of the fourth integer
integer from
from the
the base
base address.
address. First
First time
time through
through
the
the loop the condition'
condition evaluates to true,
true, since
since the
the address
address of
of

l
loop the evaluates to
300
300 Exploring C
Exploring

the fourth elemer


elemerlt (6012)
( 6012 ) would
would certainly be bigger than the
base address
base address (( 6004
6004 )) of
of the
the array.
array. Next,
Next, the
the control reaches
control reaches
printf(), which prints out the value at address contained
printf(), which prints out the value at address contained in in ptr,
ptr,
i.e.
i.e, value
value at
at address
address 6012.
6012. Next,
Next, the
the statement
statement ptr— gets
ptr-- gets
executed which reduces
executed which ptr to
reduces Ptr to 6010.
6010. Since
Since 6010
6010 is
is also bigger
also bigger
than
than 6004,
6004, the
the condition
condition isis satisfied
satisfied once
once again, and the
again, and value
the value
at 6010 gets printed through the printf( ). This
at 6010 gets printed through the printf( ). This process is process is
repeated for all
repeated for all the
the array elements.
array elements.

(24) Output
Output

4 321 0
43210

Explanation
Explanation

arr[0]
arr[O] arr[l]
arr[l] arr[2]
arr[2] arr[3]
arr[3] arr[4]
arr[4]

L• 0

6004
6004
11

6006
6006
2

6008
6008
33

6010
6010
4
4

6012
6012
1I
Figure 8.14
Hgure8.14

The above figure shows the arrangement


arrangement of the array elements
elements
in memory.
memory.

In the initialisation
In initialisation part of the for loop, ptr ptr is assigned a value
6012, since arr arr + 4 gives
gives the address of the fourth integer from
the basebase address
address of the array. Here, the variable ii is also
initialised
initialised to to 0. Since the
O.Since the condition
condition is is satisified
satisified for
for the
the first time
first time
(( ii being 0 ), the printf() prints out the value of
being 0 ), the printf( ) prints out the value of ptr[-i]. But ptr[-i]. But
what
what is is ptr[-i]?
ptr[-i]? Nothing
Nothing but
but *(
*( ptr
ptr ..i).
- i). A
And since iis
nd since i is 0,
0, *(
*( ptr
ptr
--ii ))evaluates
evaluates to to *(
*( 6012
6012 -- 00 )),, i.e.
i.e. 4.
4. Then
Then the
the control
control reaches
reaches
i++
i++ where
where ii is
is incremented
incremented to to 1.1. Next,
Next, the
the condition
condition is checked
is checked
and since it evaluates to true, the printf() prints out
and since it evaluates to true, the printf( ) prints out the value the value
A
A Tryst
Tryst with
withArrays
Arrays 301
301

of ptr[-i].
ptrj-I], Since
Since thisthis time iiisis 1, ptr[-i]
ptr[-i] becomes
becomes *( ptrptr - 11)),,
i.e. *( 6012 - 1 ) , i.e *( 6010). Thus the value 3 gets printed.
i.e. *( 6012 - 1 ), i.e *( 6010 ). Thus the value 3 gets printed.
Likewise,
Likewise, 2,1 2, 1 and
and 00 also
also get
get printed
printed subsequent
subsequent times
times through
through
the
the for loop.
loop.

(25) Output
Output

443210
321 0

Explanation
Explanation

A
A picture
picture is
is worth
worth aa thousand
thousand words.
words. Going
Going by
by this
this dictum,
dictum, the
the,
following
following figure
figure should
should add
add clarity
clarity to
to your
your understanding
understanding ofof
the
the program.
program.

arr[0]
arr[O] arr[l]
arr[l] arr[2]
arr[2] arr[3]
arr[3] arr[4]
arr[4]

0o

6004
6004
11

6006
6006
22

6008
33

6010
6010
«1
6012
6012

Figure 8.15
Figure 8.15

Now
Now things
things areare getting
getting really
really complicated,
complicated, as as the printf())
the prlntfl'
would
would justify.
justify. Let us us begin
begin with
with the
the for loop.
loop. Firstly
Firstly ptr ptr is
is
assigned
assigned thethe address
address 6012,
6012, thethe address
address ofof the
the fourth
fourth integer
integer
from
from the
the base
base address.
address. Since
Since this
this address
address is is greater
greater than than the
the
base
base address,
address, thethe condition
condition isis satisfied
satisfied and
and the
the control reaches
control reaches
printf().
printr( ). What
What does
does arr
arr [[ptr
ptr -.. arr
arr ]] evaluate
evaluate to? to? ptr
ptr -- arr
arr
means
means 6012
6012 -- 6004,
6004, which
which yields
yields 4,
4, and
and hence
hence arr[4}
arr[41 prints
prints outout
the
the fourth
fourth element
element of of the
the array. Then ptr--
area y. Then ptr-- reduces
reduces pt pt ,.'to 6010.
to 6010.
Since
Since 6010
6010 isis greater
greater than
than the
the base
base address
address 6004,
6004, the condition
the condition
is satisfied
,is satisfied and
and once
once again
again the
the control
control reaches
reaches the the printf(
printr( ). ).
This
This time
time ptr
ptr -- arr
arr becomes
becomes 60106010 -- 6004,
6004, i.e.
i.e. 3.
3. Thu. arrp]
Thuc arr[3]

l
302
302 Exploring
Exploring C
C

prints
prints out
out 3. This
This process
process is repeated
repeated till
tilt all the
the integers
integers in the
the
array
array have
have been
been printed
printed out.
out.

Possibly
Possibly an easier way of understanding
easier way understanding the the expression
expression ptr ptr -•
aan
r r would
would be as follows.
follows. Suppose
Suppose ptr ptr contains
contains 6012
6012 and and anarr
contains
contains 6004.
6004. We
We can
can then
then view
view thethe subtraction
subtraction asas (( aanrr +
+ 44 -•
aanr r )),
, since
since ptr
ptr is
is nothing
nothing but
but alIT.
r r ++ 4.
4. Now
Now II suppose
suppose its its quite
quite
logical
logical to to expect
expect the
the result
result of
of the
the subtraction
subtraction asas 4.
4.

(26) Output.
Output

60040
60040
901660040
901660040
901660040
901660040

Explanation
r/Explanation

Look
Look at the initialisation
at the initialisation of thethe amy
array p[ J During
p[J. initialisation,
During initialisation,
the
the addresses
addiesses of of various
various elements
elements of of the
the array
amy a[ a[]] are
are stored
stored inin
the
the array
array p[ p[ ]].. Since
Since thethe array
array p[p[ ]) contains
contains addresses
addresses of of
integers,
integers, it
it has been declared
has been declared asas an
an array
array ofof pointers
pointers to tointegers.
integers.
Figure
Figure 8.16
8.16 shows
shows the the contents
contents of of arrays
arrays a[
a[] ] and
and p[ p[ ].
]. In
In the
the
variable
variable ptr,
ptr, the
the base
base address
address of of the
the array
array p[p[ ],
], i.e.
l.e. 9016
9016 is is
stored.
stored. Since
Since this
this address
address is is the
the address
address ofof p[0],
prO), which
which itself
itself is
is
. aa pointer,
pointer, ptr
ptr has
has been
been declared
declared as as pointer
pointer toto an
aninteger
integerpointer.
pointer.

Let
Let us understand the
us understand the printf()s
printf( )s now.
now. The
The first
first printf(
printf()) is
is quite
quite
simple.
simple.

printf C%d%d\n\
( I%d %~nl I a, *a);
*8) ;

It prints
prints out
out the
the base
base address
address of the
the array
array a[
a[ ] and
and the
the value
value at
this
this base
base address.
address.
A Tryst
Tryst with
with Arrays
Arrays 303
303

a[0] all] a[2] a[3] a[4]

6004
1

6006
2
6008
3

6010
* 1
6012
P[0] rfl] p[2] P[3] P[4]

6004 6006 6008 6010 6012 1


9016 9018 9020 9022 9024
ptr

9016

7888
I
Figure 8.16

Looking at
Looking at the
the figure,
figure, this
this would
would turn
tum out
out to
to be
be 6004
6004 and
and_O.0.
When you
When you execute
execute the
the program,
program, the
the address may tum
address may turn out
out to
to be
be
something other
something other than
than 6004,
6004, but
but the
the value
value at
at the
the address would
address would
be surely
surely O.
0. .

Now look at
Now look at the
the second
second printl(
printf().
).

("%d%d%d\n",p,*p,**p);
printf ("%d %d %d\n", p, *p, **P) ;

Here pp would
Here would give
give the
the base
base address
address of
of the
the array
array r[],
p[ ], i.e.
i.e. 9016;
9016;
*p would
would give
give the
the value
value at
at this
this address,
address, i.e.
i.e. 6004;
6004; **p wouldwould
give the
give the value
value at
at the
the address
address given
given by
by *p'
*p, i.e.
i.e. value
value at
at address
address
6004, which
6004, is o.
which is 0.

Now on to
Now on to the
the last
last printl(
printf().
).

printf (("%d %d %d\n",


"%d %d ptr, *ptr,
%d\n", ptr, *ptr, **ptr)
**ptr);;

L
304
304 Exploring C
Exploring C

Here ptr contains


Here contains the
the base
base address
address of
of the
the array
array p[],
p[ ], i.e.
i.e. 9016;
9016;
wouid give
*ptr would give the value at
the value at this
this address,
address, i.e.
i.e. 6004; **ptr
6004; ··ptr
would give
would give the
the value
value at
at the
the address
address given
given by
by *ptr,
·ptr, i.e.
i.e. value
value at
at
address 6004,
address 6004, which
which isis O.
0.

(27) Output
(27) Output

11 1
111
•. 222
222
333
333
344
344

Explanation
Explanation

Figure 8.17
Figure 8.17 would
would go
go aa long
long way
way in
in helping
helping to
to understand
understand this
this
program.
program.

Here ptr has


Here been declared
has been declared as
as aa pointer
pointer toto an
an integer
integer pointer
pointer
and assigned
and assigned the
the base
base address
address ofof the
the array
array p[],
p[ ], which
which has
has been
been
declared as
declared as an
an array
array of
of pointers.
pointers. What
What happens
happens when ptr++
when ptr++
gets executed?
gets executed? ptr points to the
points to the next
next integer
integer pointer
pointer in
in the array
the array
p[ ]. In
p[]. In other
other words, now ptr contains
words, now contains the
the address
address 9018.
9018. Now
Now
let us
let us analyse
analyse the
the meaning
meaning of of ptr
ptr -• p,
p. *ptr
·ptr. - aa and **ptr.
and ··ptr.

ptr-p
ptr - p

Since ptr is
Since is containing
containing the the address
address 9018,
9018, we
we can
can as
as well
well say
say
that ptr is
that is containing
containing the address given
the address given by
by p +
+ 1.
1. Then
Then ptr -• p
is reduced
is reduced toto (( pp + 11 •- pp )),, which
which yields
yields 1.
1.

**ptr
p t r-- aa

mean.,.. value
*ptr mean value at
at the
the address
address contained
contained in
in ptr. Since
Since ptr
contains 9018,
contains 9018, the
the value
value atat this
this address
address would
would bebe 6006. Now
6006. Now
6006 can
6006 can be be imagined
imagined as
as ((aa + 11 )).. Thus
Thus the
the expression
expression becomes
becomes
(( aa + 11 •- aa ),
), which
which is
is nothing
nothing but but 1. 1.
A Tryst with Arrays
TrystwithArrays 305
305

a[0]
a(0] a[l]
a(1] a[2]
a(2] a[3]
a[3] a[4]
a[4]
00 11 22 33 44 II
6004
6004 6006
6006 6008
6008 6010
6010 6012
6012

P[0]
p[O] P[l]
p[l] P[2] P[3]
P[3] P[4]
p[4]
6004
6004 6006
6006 6008
6008 6010
6010 I 6012
6012 1
9016
9016 9018
9018 9020
9020 9022
9022 9024
9024
ptr
ptr ptr
ptr
9016 ~1 ptr++ ..1 9018 ~I
D t r + +
9016 9018
7888
7888
1 7888
7888
1
ptr
ptr ptr
ptr
1 *ptr++
*ptr++ 1
9018
9018
| 9020
9020 I1|
7888
7888 7888
7888
ptr
ptr ptr
ptr
b *++ptr
9020
9020 1~++ptr'l 9022
9022 I11
7888
7888 7888
7888
ptr
ptr ptr
ptr
Ii ++*ptr'l
++*ptr b p[3]is
P[3] is
9022
9022 9022
9022 ~| changed
changed
to 6012
7888
7888 7888
7888

Figure 8.17
Figure 8.17

**ptr
**ptr

ptr contains
ptr contains 9018,
9018, so
so *ptr
*ptr yields
yields 6006,
6006, and
and hence **ptr
hence **ptr
becomes *(
becomes *( 6006), which yields
6006 ), which yields 1.
1.

Thus the output


Thus the output of
of the
the first
first printf(
printf()) becomes
becomes 1111 11..
306
306 Exploring
Exploring C

Take aa deep
Take breath and
deep breath and then
then begin
begin with
with the
the analysis of .,tr++
analysis of *ptr++...
Here'"* and
Here and ++
++ both
both are
are unary
unary operators.
operators. Unary
Unary operators have
operators have
an associativity
an associativity of right to
of right to left,
left, hence
hence ++++ is
is performed
performed before
*. ++ increments
•. ++ increments ptrptr such
such that
that ptr
ptr now contains 9020.
now contains 9020. Then
Then •.
•(9020) is performed,
• ( 9020) is performed, which
which gives
gives the
the value
value atat 9020.
9020. But since .
But since
this value is
this value is not
not assigned
assigned to to any variable, it
any variable, just gets
it just gets ignored.
ignored.
Now
Now withwith ptr
ptr containing
containing 9020,
9020, let
let us
us once
once again
again analyse the
analyse the
expressions ptr - p, *ptr - a and
expressions ptr - p, .,tr - a and .·ptr. **ptr.

ptr-p
ptr-p

Since ptr
ptr contains
contains 9020, it can be visualised as ( p + 2 )).. Thus
ptr •• pwould
ptr p would become
become (( pp +
+ 22 -- p
p )),, which
which gives 2.
gives 2.

*ptr-a
*ptr-a

•ptr would
.,tr would give
give value
value at at address
address 9020, i.e.
Le, 6008,
6008, which
which is
nothing but
nothing but the
the address
address givengiven by
by aa ++ 2.
2. ThuS
Thus the
the expression
expression
becomes (( aa +
becomes + 22 -• aa )),, which
which gives 2.
gives 2.

**ptr
**ptr

.,tr gives the value at address


•ptr address 9020, i.e. 6008,
6008, and .(
•( 6008
6008))
gives the value at 6008,
6008, i.e. 2.

I hope your.confidence
your confidence is building
building and you are ready to meet
head on
head on the
the expression
expression •++ptr.
.++ptr. Here,
Here, since
since ++
++ precedes ptr,
precedes ptr,
firstly ptr is incremented
firstly ptris incremented such
such that
that it
it contains
contains the
the address
address 9022,
9022,
and then
and then the
the value
value at
at this
this address is obtained.
address is obtained. Since
Since the value
the value
is not collected
is not collected in in any
any variable,
variable, it
it gets
gets ignored.
ignored. Now having
Now having
cooked enough pointer
cooked enough pointer stew
stew you
you can
can easily
easily imagine
imagine that the
that the
output
output ofof the
the third printf()) would
third printf( would be be 33 33 3.
3.

Finally, let U3 us understand


understand the expression ++*ptr.
++*ptr. Here ob-
viously,
viously, the priority goes to the •. •.' Thus, this expression
increments
increments the the value
value given
given by
by •ptr.
·ptr. Since
Since ptr
ptr contains 9022,
contains 9022,
•·ptr
p t r gives
gives value
value at
at 9022,
9022, i.e.
i.e. 6010.
6010. This
This value
value is incremented
is incremented
A Tryst
Tryst with
with Arrays
Arrays 307
307

to 6012.
to 6012. So p[3] now now contains
contains 6012, whereas
whereas value
value of
of ptr
ptr
remains stationary
remains stationary atat 9022. Let
Let us now
now analyse
analyse the
the expressions
expressions
ptr
ptr -- p,
p, *ptr
*ptr -- aa and
and ·.ptr.
**ptr.

ptr-p
ptr-p

ptr contains 9022,


ptr contains 9022, therefore
therefore ptr
ptr can
can be
be imagined
imagined asas (( p + 3 ).
Thus (ptr
Thus ( ptr -- p
P )) becomes
becomes (( p
p++3-p p ),
), which
which yields
yields 3.
3.

*ptr-a
*ptr - a

*ptr yields 6012 which


·ptr yields which can
can bebe thought
thought of
of as
as (( a + 4).
4 ) . Thus the
the
expression is
expression is reduced
reduced to
to (( a + 4 - a), which
which yields
yields 4.

**ptr

*ptr yields
·ptr yields 6012,
6012, therefore
therefore **ptr
··ptr would
would yield
yield the
the value
value at
at *ptr,
·ptr,
or the
or the value
value at
at 6012, which is
6012, which is 4.
4.

(28) Output
(28) Output

1 11
11
1122
22
112323

Explanation
Explanation

To begin
To begin with, the array
with, the array a[]
a[ ] is
is initialised
initialised and
and the
the array
array p[]
p[ ] is
is
set up
set up such
such that
that it
it contains
contains the addressses of
the addressses of elements
elements of of array
array
a'[ ]. Thus
a[]. Thus array
array p[]p[ ] becomes
becomes an an array
array of
of pointers.
pointers. The
The base
base
address of
address of this
this array
array of pointers is
of pointers is then
then assigned
assigned to
to ptr,
ptr, which
which
is rightly
is rightly called
called aa pointer
pointer to
to aa pointer.
pointer. The
The possible
possible arrange-
arrange-
ment of
ment the array
of the array elements
elements in in memory
memory is shown in
is shown in the
the
following figure.
following figure.

l
308
308 Exploring
Exploring C
C

a[0]
a(0] a[l]
a(1] a[2]
a[2] a[3]
a[3] a[4]
a(4]
00 11 22 33 44 ~ I
6004
6004 6006
6006 6008
6008 6010
6010 6012
6012

P[0]
p[O] P[l]
p[l] P[2]
p[2] P[3] P[4]
p[4]
6004 6006
6006 6008
6008 6010
6010 6012
6012 1~
9016
9016 9018
<XH8 9020
9020 9022
9022 9024
9024
ptr
ptr ptr
9016
9016
I **ptr++
1 **ptr++1
9018 1
9018 ~
1
7888
7888 7888
7888
ptr
ptr ptr
ptr
p[l]is
p[l] is
*++*ptr
*++*ptr
9018 I .
9018 I 9018
9018 changed
| to
changed
| to 6008
6008
7888
7888 7888
7888
ptr
ptr ptr
ptr
++**ptr
++**ptr a[2]is
a(2] is
9018
9018 I I 9018
9018 |
I changed
changed
t033
to

Figure 8.18
Figure 8.18

Let
Let usus now
now analyse
analyse the the expression
expression **ptr++. Since Since the
the unary
unary
operators
operators areare associated
associated from from right
right to
to left,
left, the
the above expression
above expression
would
would evaluate
evaluate in in the
the order:
order: *(
*( *(
*( ptr++
ptr++ ) ). ptr ptr contains
contains the the
address
address 9016,
9016, therefore
therefore incrementing
incrementing ptr ptr would
would store
store the
the
address
address 9018
9018 in in ptr.
ptr. *ptr
·ptr would
would give the value
give"the value at at this
this address.
address.
This
This value
value turns
turns out out to
to be
be 6006,
6006, and
and *(*( 6006)
6006 ) would
would give
give the
the
value at 6006, i.e. 1. However, this value is not
value at 6006, i.e. 1. However, this value is not assigned to any assigned to any
variable
variable while
while evaluating
evaluating **ptr++.
**ptr++. OnceOnce you you are
are sure
sure that ptr
that ptr
contains
contains 9018,
9018, let let us
us now
now proceed
proceed to to find
find outout what
what the output
the output
of
of printf()
printf() is.is. Let
tet us us take
take one
one expression
expression at at aa time
time and analyse
and analyse
it
it step
step by
by careful
careful step.step.

ptr-p
ptr - p
A Tryst
Tryst with Arrays
withArrays 309
309

Since ptr
ptr is containing
containing the address 9018, we can as well say
that ptr
ptr is containing the address given by p + 1. Thus ptr
containing th~ ptr •- p
is reduced to ( p + 1 •- p )),, which yields 1.
1.

*ptr - 8a
*ptr-

*ptr
*ptr means value at the address contained in ptr. ptr. Since ptr
ptr
contains 9018,
contains 9018, thethe value
value at
at this address would
this address would be
be 6006. Now
6006. Now
6006
6006 can can bebe imagined
imagined as
as (a
(a +
+ 11)).. Thus
Thus the
the expression becomes
expression becomes
(( aa +
+ 11 •- aa )),, which
which is
is nothing
nothing but
but 1.1.

**ptr

ptr contains 9018,


ptr contains 9018, so
so *ptr
*ptr would
would yield
yield 6006,
6006, and
and hence
hence **ptr
**ptr
becomes *( 6006 ), which would yield 1.
becomes 1.

Thus the output


Thus the output of
of the
the first
first printf(
printf()) turns
turns out
out to
to be
be 11
1 1 1.
1.

The next statement


statement needs a closer look. In *++*ptr,
*++*ptr, the order
of evaluation would be *( ++(*ptr)).
++( *ptr». Since ptr contains 9018,
ptrcontains
*( ptr)
ptr ) would yield the value at 9018, i.e. 6006. Then ++ goes
goes
to work on 6006 and increments it such that it is now 6008.
Thus p[1]
p[l] would now contain 6008. And finally *( 6008 )
would give 2, which is ignored since it is not assigned to any
variable.
variable.

Now, with
Now, with ptr
ptr containing
containing 9018,
9018, let
let us
us once
once again
again analyse
analyse the
the
expressions ptr
expressions ptr -• p, ptr
ptr -• a and **ptr.
**ptr.

Ptr-
ptr - p

Since ptr
ptr contains
contains 9018, it can be visualised
visuahsed as ( p + 1),
1 ), thus
ptr -• p
ptr p would
would become
become (( pp +
+ 11 -• P
p ),
), which
which would
would be
be 1.
1.

*ptr -8
-a
310
310 Exploring C
ExploringC

•ptr would give value


*ptr would value at address 9018, i.e. 6008, which is
nothing but
nothing but the
tbe address
address given by aa +
given by 2. Thus
+ 2. Thus the expression
the expression
becomes (( aa +
becomes + 22 -- aa ),
), which
which gives
gives 2.
2.

**ptr

*ptr gives the value at address


•ptr 9018, i.e. 6008, and *( 6008
address 9018, 6008))
gives the value
value at 6008,
6008, i.e.
i.e, 2.

Thus the output


Thus the output of
of the
the second
second printf(
printf()) would be 11 22 22..
would be

Finally, we
Finally, we reach
reach the
the third expression ++**ptr.
third expression ++**ptr. As As the unary
the unary
operators are evaluated
operators are evaluated from
from right
right to
to left,
left, the
the order
order of
of evalua-
evalua-
tion of the
tion of the above
above expression
expression becomes:
becomes: (( +++ + ((*(
* ( *ptr»).
*ptr))). Since
Snce
ptr
ptr contains
contains 9018,
9018, *ptr
*ptr yields
yields 6008.
6008. *( *( 6008)
6008 ) results
results into 2.
into 2.
This value at
This value at the address 6008
the address 6008 isis then
then incremented
incremented from from 22 to
to
3.
3.

ptr-p
ptr - p

Since ptr
Since ptr contains
contains 9018,
9018, it
it can
can bebe visualised
visualised as
as (( p
p++ 1), thus
1 ), thus
ptr -- p
ptr p would become (( pp +
would become + 11 -- pp )),, which
which would
would be be 1.
1.

*ptr -8
-a

*ptr would
*ptr would give value at address 9018, i.e. 6008, which is
nothing but
nothing but the
the address
address givengiven by + 2.
by aa + 2. Thus
Thus the expression
the expression
+ 22 -- aa )),, which
becomes (( aa +
becomes which gives
gives 2.
2.

**ptr

*ptr gives the value at address 9018, i.e. 6008, and *( 6008
*ptr 6008))
gives the value
value at 6008, i.e. 3.

Thus the output of the third printf(


printf()) is 1 2 3.

(29) Output
(29) Output
A Tryst
Tryst with
with Arrays
Arrilys 311

4044161
404 4161

Explanation
Explanation

n[ ][ ], to begin with, is declared as a two-dimensional array.


n[][],
Whenever
Whenever we we mention
mention the name of
the name of the
the array,
array, we
we get
get its
its base
base
address. Therefore in
address. Therefore in printf(
printf(),), the
the first output would
first output would be be the
the
base
base adddress
adddress of the array.
of the array. In our case
In our it turned
case it turned out
out to
to be
be 404.
404.
The array elements
The array elements are
are arranged
arranged in in the
the following
following manner
manner inin
memory.
memory. Remember
Remember thatthat there
there are
are no
no rows
rows and
and columns
columns in in
memory.
memory.

1
r---_+ • n[0][0]
N[0][0]
|
....---+• n[1
N[L][0]
][0]
| • N[2][0]

2 4 3 6 8 5 3 5

404
404 406
406 408
408 410
410 412
412 414
414 416
416 418'* 420
418 420

Figure 8.19

A two-dimensional
two-dimensional array is nothing but an array of several
one-dimensional arrays. The
one-dimensional arrays. The 2-D
2-D array
array contains
contains addresses
addresses of
of
these 1-D arrays.
these 1-D arrays. Thus n[0], n[l]
Thus n[O], n[1] and n[2] contain
and n[2] contain the
the addres-
addres-
ses 404, 410 and
ses 404,410 and 416
416 respectively.
respectively. Hence
Hence thethe second
second output
output of
of
printf(
printf( ).
). The
The third
third output
output isis quite
quite straight
straight forward. n[2][2]
forward. n[2][2]
prints out the
prints out the element
element inin the
the second
second row
row and second column
and second column of
of
the array.
the array.

(30) Output
(30) Output

41633
41633

Explanation
Explanation

l
312
312 Exploring C
Exploring C

ptr
ptr has been declared as an integer pointer, and to begin with,
assigned the base address
address of the array, which is 404.

121421316 41'815 3 6 8 5 33 5

404
404 406
406 408
408 410
410 412
412 414
414 416
416 418
418 420
420

Figure 8.20

n[2] gives the base address


address of the second one-dimensional
one-dimensional
array, that is 416. Next comes the expression ptr[2]. ptr[2]. Can we
use such an
use such an expression?
expression? Yes,Yes, because
because ultimately
ultimately ptr[2]
ptr[2] isis
nothing but *(
nothing but *( ptr
ptr ++ 22 ).
). Thus,
Thus, even
even though
though ptrptr has
has not
not been
been
declared as
declared as an
an array,
array, we
we are
are perfectly
perfectly justified
justified in
in using the
using the
expression ptr[2]. ptr
expression ptr[2]. ptr stores
stores the
the address 404, so
address 404, so *(
*( ptr
ptr +
+ 22 ))
gives the value
gives the value ofof the
the second
second integer
integer from
from 404,
404, which
which in
in this
this
program happens to be
program happens to be .3. 3.

(31) Output
(31) Output

1 11
55
55
33
33
55
55
88
88
66
66
33
33
44
44
22
22

Explanation
Explanation

The output of n[i]ij]


n[i]|j] is as per the expectations,
expectations, I believe. All
that is done is, using the forloop,
for loop, rows and columns are varied,
ii controlling
controlling the row and jj controlling
controlling the column. What is
A Tryst
Tryst with
with Arrays
Arrays 313
313

definitely difficult
definitely difficult to
to comprehend
comprehend is is the
the second
second expression
expression in
in
printf( )),, **(( **(
PRINTF( ( n
N+ i I )+
) + jJ ).
). Let
Let us
us try
try to understand it.
it. The
The
following figure should
following figure should prove
prove helpful
helpful in
in doing
doing so.
so.

22436853511
4 3 6 8 5 3 5

404
404 406
406 408
408 410
410 412
412 414
414 416
416 418
418 420
420

Figure 8.21
8.21

Imagine
Imagine a 2-0 2-D array as a collection of several 1-D L-D arrays. The
only thing that the compiler needs to remember about a 1-0 1-D
array
array isis its
its base
base address.
address. TheThe compiler
compiler doesn't
doesn't eveneven havehave to to
remember
remember the the number
number of elements present
of elements present in in the array, since
the array, since
bounds checking
bounds checking is is not
not the
the compiler's
compiler's responsibility.
responsibility. Thus, Thus, if if
three 1-0
1-D arrays
arrays are to be remembered, the compiler should
store somewhere
somewhere the base addresses of these arrays. These base base
addresses
addresses are stored in n[O], N[0], n[l]
N[L] and n[2].
N[2]. Now if n[l] N[L] gives
gives
the base
the address of
base address of the
the first
first array,
array, then
then N[L]
n[1] + + 22 would
would give give thethe
address
address of of the
the second
second integer
integer fromfrom this
this base
base address.
address. In In this
this
case it turns
case it turns out
out to
to be
be 414.
414. TheThe value
value at
at this
this address,
address, that that is 5,
is 5,
can be obtained
obtained through the expression *( n[1] N[L] + 22).). We know
all too well
all too well that
that NIL] can also
n[1] can also be
be expressed
expressed as as *(
*( nN + + 11 )).. Thus,
Thus,
the expression *(
the expression *( NIL]
n[l] ++ 22.)) is
is same
same asas *(
*( *(*( N
n ++ 11 )) + 22 ),
), which
which
is same
1S same as N[L] [2].
as n[l] [2]. Therefore
Therefore in in general,
general, wewe can
can say
say that
that n[i]N[I][i]
[J]
is same as
is same as *(
*( *(
*( nN + i)
I) ++ jJ ).
). With
With that
that II suppose
suppose the the output
output of of
the above program
the above program is is quite
quite simple.
simple.

(32) Output
(32) Output

147
147
147
147
147
147

Explanation
Explanation
314
314 Exploring C
ExploringC

ptr[ ] has been declared


declared as an array of pointers containing
containing the
base addresses
addresses of the three 1-D
1-D arrays as shown in Figure 8.22.
Once past the declarations,
declarations, the control reaches the first for
loop. In this loop the printf(
printf()) prints the values at addresses
addresses
stored in ptr[0], ptr[l] and ptr[2],
ptr[O],ptr[1] ptr[2], which turn
tum out to be 1,
1,44
and 7.
and 7.

In the next for


for loop, the values
values at base addresses stored in the
array a[
a[]] are printed, which once again tum
turn out to be 1, 4 and
7. The third for
7. for loop is also simple.
simple. Since ptrl
ptrl has been
initialised to the base address of the array ptr[],
initialised ptr[ ], it contains the
address 822.
822.

112345 2 3 4 5 6 7 8 »
9 1
404
404 406
406 408
408 410
410 412
412 414
414 416
416 418
418 420
420
ptr[0] ptr(2]
ptr[ll ptr(2J·
ptr(O] ptr(1J
I 404
404 I 410
410 I 416
416 I|
822
822 824
824 826
826

ptrl
ptr1 ptrl
ptrl++
1 822
822 lI ~" ' I 824
824 |I
Ptrl
t +

Figure 8.22
8.22

Therefore *ptrl
·ptrl would give the value at address 822, i.e 404,
and
and **ptrl
··ptrl would
would give
give the
the value
value at
at address
address given
given by *ptrl,
by ·ptrl,
i,e. value
value at 404, which is 1. 1. On incerementing ptrl ptrl it points
to the next
to the next location
location after
after 822,
822, i.e
i.e 824.
824. Therefore
Therefore next time
next time
through
through thethe for loop,
loop, **ptrl
*·ptrl gives
gives value
value at
at 410
410 (( which is
which is
obtained
obtained through
through *ptrl
·ptrl ), i.e.
i.e. 4.
4. Similarly,
Similarly, last
last time through
time through
the
the loop,
loop, the
the value
value 77 gets printed.
gets printed.

(33) Output
(33) Output
rr A Tryst
Tryst with
with Arrays
Arrays 315

555
5

Explanation
Explanation

In memory
In memory the
the 3-D array elements
3-D array elements are arranged as
are arranged as shown
shown in
in
the following
the figure.
following figure.

2 44 33 611
12 6 | l 66 7
7 918
9|8 22 11 112
1J2 33 7
7 311
3 l l 66 22 410
4J0 7
7 99 5'
5l
200
200 208
208 216
216 224
224 232
232 240
240

Figure 8.23
Figure 8.23

Here t[][][]
Here t[ ][ ][ ] has
has been
been declared
declared as as aa three-dimensional
three-dimensional array.
array.
A 3-D array
A 3-D array can
can be
be considered
considered as as aa collection
collection of of aa number
number ofof
2-D arrays. Thus,
2-D arrays. Thus, the
the first
first expression
expression in in the
the printf(),
printf(), t[2] [1]
[1] [3]
[3]
refers to the
refers to the element
element in in 11st row,
row, 33~'column
st
..'column of
ri
of the 200 2-D
the 2 array.
n d
2-D array.
This turns out to be 5, which is printed through
This turns out to be 5, which is printed through printf( ).. printf().

The next
The next expression
expression in in printf()
printf() is is aa little
little complicated.
complicated. SinceSince
the only
the only thing
thing that
that the compiler needs
the compiler needs to to remember
remember about about the the
three 2-D
three 2-D arrays
arrays is is' their
their base
base addresses,
addresses, these these addresses
addresses are are
stored in
stored in t[O],
t[0], t[1]
t[l] and
and t[2].
t[2]. Therefore,
Therefore, the the expression
expression t[2][l]
t[2][l]
would give
would give the
the address
address of of the
the first
first row
row ofof the
the second
second 2-D2-D array.
array.
Referring to the figure, this address turns out
Referring to the figure, this address turns out to be 240. To this to be 240. To this
address if
address if we
we addadd 3, 3, wewe would
would get get the
the address
address of the third
of the third
integer from
integer from this
this address.
address. This This address
address would
would be be 246. Natural-
246. Natural-
ly, the
ly, the value
value at at this address (Le,
this address (i.e. 55 )) can
can be be obtained
obtained through
through
the
the expression *( ([2][1] + 3 ). But t[2][l] itself can be
expression *( t[2][l] + 3 ). But t[2][l] itself can be ex-
ex-
pressed as *( t[2] + 1 ). And in this expression
pressed as *( t[2] + 1 ). And in this expression t[2] can be t[2] can be
expressed as
expressed as *(
*( tt ++ 22 ).
). Thus
Thus thethe expression
expression *( *( t[2][l]
t[2] [1] ++ 33 )) can
can
be expressed
be expressed as as *(*( *(
*( *(*( tt +
+ 22 )) +
+ 11 )) +
+ 33 ).).

Solutions to [B]
Solutions to [B]

(1)
(1) Program
Program
316
316 Exploring
Exploring C

mainQ)
lllain(
{{
int a[25],
a(25], d1[24], d2[23], d3[22], ii;;

printf (("Enter elements\n");


"Enter 25 elements\n" );
for ( ii = 00 ;; i <= 2244 ;; iff
i++))
scanf (("%d",
scant &a[Q);;
"%d", &a[ij)

printf (("\nA:");
"\nA: • ) ;
for ( ii = 00 ;; i <= 24
2 4 ; iffi++))
printf ("%d", ap]);
( ·%d ., a(ij)

printf ("\n\n1st, are:\n");;


("\n\n1st, 2nd and 3rd differences are:\n")
("\nD1:");
printf ("\n01: .) ;
for ( ii = 00 ;-i <= 2233 ;; iff
(or i++))
{{
d1[i] = ap+1]-a[0;
d1[ij =ap+1]-a(ij;
printf ("%d",d1[0);
( "%d ", d1[ij ) ;
}}

printf (("\nD2:");
"\n02: .) ;
for ( ii = 00 ;; ii<=
<= 2222 ;; iff
i++))
{{
d2[i] = d1[if 1] - d1[ij ;
d1[i+1]-d1[i];
printf ("%d
( "%d ",",d2[Q);
d2[ij ) ;
}}

printf (( *"\n03:
\ n D 3 :")" ) ;
for ( ii = 00 ;; i <= 2211 ;; iff
i++))
{{
d3[i] =
d3[i] = d2[i+ 1] - d2[i] ;
d2[i+1]-d2[i];
printf
printf ( " % d d~[i]
( "%d ., 3 p j )) ;;
}}
}
AA Tryst
Trystwith
withArrays
Arrays 317
317

Sample run
Sample run

Enter 25
Enter elements
25elements
124711162224567891012345626789
1 24711 162224567891012345626789
A: 1 247111622 2 4 5 6 7 8 91012345626789
A: 1 2 4 711 1 6 2 2 2 4 5 6 7 8 9 1 0 1 2 3 4 5 6 2 6 7 8 9
1st, 2nd and 3rd differences are:
1 st, 2nd and 3rd differences are:
01: 1 23456 -20 21 1 1 11 1 2 -911 1 -441 1 1
D1:1 2 3 4 5 6 - 2 0 2 1 1 1 1 1 1 2 - 9 1 1 1 - 4 4 1 1 1
02: 1 1 1 1 1 -26 22 -1 0 0 0 0 0 1 -11 10 0 0 -5 8 -3 0 0
D2:1 1 1 1 1 - 2 6 2 2 - 1 0 0 0 0 0 1 -11 10 0 0 - 5 8 - 3 0 0
03: 000 0000- -27
D3:0 2 7 448
8 - 2-23
3 110000000011-1221
-12 21 --10
1 0 00 --55 113
3 --11
1 1 33 00

Explanation
Explanation

Firstly,
Firstly, the
the 25
25 array
array elements
elements areare read
read through
through the
the keyboard
keyboard
into
into an
an array
array a[
a[].]. Then
Then through
through the for loops
the for loops their
their first,
first, second
second
and
and third
third differences
differences areare calculated
calculated and
and then
then printed
printed out.
out.

(2)
(2) Program
Program

main( )
main()
{{
int data[50],
int data{SO],ii;;
static il'lt freq(26] ;
static intfreq[26];

( "Enter data\n");
printf ("Enter data\n" ) ;
for(i=O;i<50;i++}
for ( i = 0 ; i < 5 0 ; i++)
{{
scant ("%d",&data[i]);
scant ( "%d", &data{ij ) ; „•
ifif (data[i]
(data{ij == 11 &&
&& dataJJ]
data[i] <=
<= 225)
5)
freqjdataJjD freq[data[iTJ + 1 ;;
freq[data[i]] = freq[data{i]]
}}

printf ("\nFrequency
( "\nFrequency of occurrence:\n'
occurrence:^"););
318
318 Exploring C
Exploring

for ( i = 1 ;;i<26;i++)
for(i=1 i < 2 6 ; i++)
{{
ifif(freq[i]!=0)
(freq[i] != 0 )
printf (("%d
"%d - %d\n", i, freq[i])
freq[i]);;
}
}
Sample run
Sample run
Enter data
Enter data
111222333444444444545454522222222
1 1 1 2 2 2 3 3 3 4 4 4 4 4 4 4 4 45 45 45 45 2 2 243
666666666622222221717171717 2 43
2 2 43
22
666666666622222221717171717434343
occurrence:
Frequency of occurrence:
11-3
-3
22 --10 10
33-3 -3
44-8 -8
66 --10
10
117-
7 - 55
222-4 2-4
443-3 3-3
445-45-4

Explanation
Explanation

To begin
To with, the
begin with, the data
data isis read
read into
into the
the array
array datal
data[ ]] through
through
the first for
the first for loop
loop.. .As
As each
each datadata item
item isis read,
read, it
it is
is tested
tested for
for
validity
validity andand then
then the
the appropriate
appropriate element
element in in the
the array freq[ ]
array freq[]
is incremented by
is incremented by 1.To
1. To ensure
ensure that
that to
to begin with each
begin with each element
element
of
of the
the array
array freq[
freq[] ] is
is 0, it has
0, it has been
been declared
declared asas static.
static. By the
By the
time
time thethe entire
entire data
data has
has been
been read,
read, the freq[ ] array
the freq[] array has also
has also
been
been setset up.
up. Through
Through the the second
second for loop, the
for loop, the frequency
frequency of the
of the
data items has
data items has been
been printed
printed out.
out. For
For want
want ofof space, frequencies
space, frequencies
of
of only
only those
those data
data items
items have been printed
have been printed out
out which
which occur
occur atat
least once.
least once,
A
A Tryst
Trystwith Arrays
withArrays 319
319

(3) Program
Program

main()
main()
{{
int mat[10][10],
mat[10][1OJ,n,
n, r,r, c, lowertri == 0,
0, uppertri
uppertri == 0 ;;

printf ("\nEnter
( "\nEnter no.
110. of rows of matrix (1
( 1 to 10)
1 0 ) " ) ;;
scant
scanf ("%d",&n)
( "%d", &n) ;;
printf ("Enter
( "Enter elements of matrix\n");
matrix\n" ) ;
for (r
( r = 0 ;; r < n; r++)
n ; rtf )
r
{'
for(c=O;c<n;c++)
for ( c = 0 ; c < n; C++)
scant (("%d",&mat[r][c]);
scanf "%d", &mat[r][c]) ;
}}

/*
1* check for lower triangular matrix */

for (r
( r = 0 ;; r < n -- 11; ; rtf
r++))
{{
for(c=r+1 ;c<n;c++)
for ( c = r + 1 ; c < n; C++)
{
{
i1( mat[r][c] )
if(mat[r][c])
break ;
} break;
}if ( mat[r][c] )
if(mat[r][c])
break;
break;
}
}
i1(r==n-1)
if (r == n - 1 )
lowertri = 1 ;
lowertri = 1 ;

I* checkfor
1* check forupper
uppertriangular
triangularmatrix
matrix*/*/

for (r
( r = 1 ;; r < n; rtf
r++))
{{
for ( c = 0 ; c < r ; c++ )
for ( c = 0 ; c < r; C++)
{
{
320
320 Exploring
Exploring C

ifif(mat[r][c])
( mat[r][c] )
break;;
break
}}
ifif(mat[r][c])
( mat[r][c] )
break ;
break;
}}
if(r==n)
if(r==n)
uppertri == 11 ;;
uppertri

if (lowertri
( lowertri && uppertri
uppertri))
printf ("\nDiagonal Matrix');
( ",nDiagonai Matrix" );
else
{{
if ((lowertri)
lowertri ) .
("\nl_ower Triangular Matrix")
printf ("\nLowerTriangular Matrix"), I

else
{{
ifif ((uppertri)
uppertri )
printf ("\nUpper
printf ("'nUpperTriangular
Triangular Matrix")
Matrix");;
else
else
printf
printf (( "·'nNot
W o t aa special type of
special type of matrix·)
matrix") ;
}}
}}
}

Sample run
Sample run

Enter ro.
no. of rows of matrix ( 11 to 10) 5
Enter elements of matrix
110000
0000
001000
1000
000100
000010
0100 .
0 0 i'o
000001
0001

Diagonal matrix
r A Tryst
A Tryst with
with Arrays
Arrays 321
321

Explanation
Explanation

The program
The program works
works for for any
any square
square matrix
matrix whose
whose number
number of of
rows and
rows and columns
columns are are less
less than
than oror equal
equal to 10. The
to 10. program
The program
first
first asks
asks forfor the. size of
the. size of the
the matrix,
matrix, followed
followed by by matrix
matrix ele-
ele-
ments. Once these
ments. Once these have
have been
been entered,
entered, through
through aa pair
pair ofof for
for
loops
loops itit checks
checks for
for any
any non-zero
non-zero elements
elements in in the upper triangle
the upper triangle
of the matrix.
of the matrix. IfIf it
it finds
finds aa non-zero
non-zero element,
element, it it breaks
breaks out
out ofof the
the
for loops. Once
for Ioops. Once outside
outside thethe loops,
loops, itit checks
checks whether
whether the
the control
control
came
came out of the
out of the loops
loops due
due toto execution
execution of of break
break oror aa normal
normal
exit from the loops. If there is a normal exit it means
exit from the loops. If there is a normal exit it means that the that the
upper triangle of
upper triangle of the
the matrix
matrix contains
contains all all zeros,
zeros, Hence
Hence the the
variable
variable lowertri
lowertri is is set
set up
up with
with 1.1.

Similarly, through the next set of for loops, the lower triangle
Similarly,
of the
of the matrix
matrix is
is checked
checked for
for non-zero
non-zero elements.
elements. IfIf there
there is
is aa
normal exit from
normal exit from these
these for
for loops,
loops, then uppertri is
then uppertri is set up with
set up with
1.
1.

Finally, through a series of ifs depending upon the value set up


in lowertri
lowertri and uppertri,
uppertri, it is decided whether the matrix is
lower triangular, upper triangular or a diagonal matrix.

((4)
4) Program
Program

mainQ
main( )
{{
int
int sales[5][10][7];
saJes[5][10][7];
float wk_chip,
wkchip, wk_city, avg_dsales == 00 ;;
wkcity, avg_dsales
int i,i, j,j, kk;;
int

for ( i = 0 ; i < 5 ; i++)


for(i=0;i<5;i++)
{.
{.
printf (("\nChip
"\nChip no: %d", ii ) ;
wkchip = 0,
wk_chip =
0,
fori = 0;0 ; ij<<10;
for (ij = 10; i++ )
j++)
322
322 Exploring C
Exploring C

{{
printf (("\nCity % d " ,i)j ) ;
"\nCity no: %d",
printf (("\nEnter
"\nEnter weekly sale day by day\n");
day\n") ;
( k = 0 ;; k < 7 ;; k++
for (k k++) )
{{
scanf (("%d\
scant &sales[i][fl[k]);
"%d", &sales[ij[j][k] );
wk_chlp
wk_chip += sales[ij[j][k]
sales[i][j][k] ;
}}
}}
( " W h i p no. %d sales = %1
printf ("\nChip %f, i, wk_chip)
wk_chip);;
U
,

avg_dsales
aV9_dsales += wkchip;
wk_chip;
}}
avg_dsales/=7;
aV9_dsales /= 7 ;
printf ("\nAverage
("\nAverage daily sales = %f,
%f', avg_dsales)
avg_dsales) ;

=
for (i( j = 0;0 ; ij << 10;
1 0 ; i++
j++))
{{
wk_city = 00;;
for ( ii = 0 ;; i << 55;; itt
i++))
{{
=
for (k ( k = 0 ;; k < 7 ;; k++
k++))
sales[i][j][k];
wk_city += sales[i]U1[k];
}}
printf (("\nCity
n\nCity no. %d sales = %f, wk_city) ;
%f, j, wk_city)
}}
}}

Explanation
Explanation

For want
For want of space it
of space it is
is not
not possible
possible toto give
give aa sample
sample run
run of
of this
this
program. However,
program. However, the the program
program is is quite
quite straightforward. Note
straightforward. Note
that the
that the variable
variable wk_chip
wk_chip represents
represents thethe total
total weekly
weekly salesale
chipwise, whereas
chipwise, whereas wk_city
wk_city represents
represents totaltotal weekly
weekly salesale
citywise. You
citywise. You can
can imagine
imagine thethe 3-D
3-D array
array as
as aa collection
collection of five
of five
2-D arrays.
2-D arrays. Each 2-D array
Each 2-D array contains
contains day
day byby day sale in
day sale in each
each
city for
city for aa particular
particular chip.
chip. Behind
Behind this
this there
there isis data
data of another
of another
A
A Tryst
Trystwith Arrays
withArrays 323
323

chip,
chip, behind
behind that
that data
data of
of another
another chip
chip and
and so
so on.
on. Once
Once this
this is
is
understood
understood well,
well, the
the rest
rest of
of the
the program
program is
is simple.
simple.

In
In the
the first
first set
set of for loops
offor loops thethe outermost
outermost loop
loop controls
controls thethe chip,
chip, .
the middle loop controls the city, and the innermost loop
the middle loop controls the city, and the innermost loop
controls
controls the the daily
daily sale.
sale. Through
Through thesp
these loops
loops thethe daily
daily sale
sale inin
each
each city
city for
for each
each chip
chip isis entered.
entered. AsAs each
each daily
daily sale
sale figure
figure is is
entered,
entered, aa running
running sum sum is is made
made using
using wk_chip.
wk_chip. When When the the
control
control comes
comes out out of
of the
the middle
middle loop,
loop, wk_chip
wk_chip contains
contains thethe
total
total week's
week's sale sale for
for aa particular
particular chip,
chip, which
which is is printed
printed outout
before
before receiving
receiving the the sales
sales figures
figures for
for the
the next
next chip.
chip. Since
Since
wk_chip
wk_chip at at this
this stage
stage contains
contains the the total
total sale
sale ofof aa chip
chip inin all
all
cities,
cities, this value is stored in avg_dsales. This variable is
this value is stored in avg_dsales. This variable is
incremented
incremented every every time
time byby anan amount
amount equal
equal to to the
the sale
sale of
of aa chip
chip
in
in aa week
week as as given
given byby wk_chip.
wk_chip. Once.the
Once.the control
control comes
comes outout ofof
all the three loops, avg_dsales contains the
all the three loops, avg_dsales contains the total sale of all total sale of all
chips
chips inin all
all cities
cities during
during thethe week.
week. This
This is
is therefore
therefore divided
divided by by
77 to
to get
get the
the average
average daily
daily sale
sale of
of the
the company
company in in that week.
that week.

The
The next
next set
set of
of for
for loops
loops calculate
calculate the
the total
total sale
sale of
of all
all chips
chips in
in
each
each city.
city. II suppose
suppose you
you can
can now
now figure
figure out
out how
how these
these loops
loops
work.
work. Good
Good luck!
luck!

(5) Program
Program

include
#include "math.h"
"math.h'
#include "stdio.h"
"stdio. h"

int sex[50], sum[50], mcode[50][3],


rt:Jcode[50][3], fcode[50][3];
fcode[50][3] ;
float cosin[3];
cosin[3] ;

main()
main( )
{{
int i,i, j,j, ans,
int ans, k,
k,t_code,
tcode, tt ;;
c, t_
float c, tcosin, factor;
float cosin, factor;
324
324 Exploring
Exploring C
C

for ( i = 0 ; i < 5 0 ; i++)


for(i=O;i<50;i++)
{{
printf ("\nEnter
( ·'nEnter sex ((MIF)
M / F )•" ) ;;
fflush (stdin);
( stdin ) ;.
scanf ("%c",
( ·%C·, &sex[il);
&sex[i] ) ;

printf ("\nCode
( ·'nCode no. %d\n",
%d\n., ii++ 1 ) ;;
printf ("Enter
( ·Enter 88 responses (1 - 5 ) •" ) ;;
(1-5)
ffor(j=O;j<8;j++)
or(j = 0 ; j < 8 ; j + + )
{{
scant (("%d",&ans);
scanf ·%d·, &ans ) ;
sump] +=
sump] ans ;
+= ans;
}}
}}
for(i=O;i<50;i++)
for ( i = 0 ; i < 5 0 ; i++)
{
{
if ( sex[ij == 'M' )
if(sexp]==
{ 'M')
{ =
for ( k 0; k < 3; kH )
f o r ( kcosin[k) =
= 0 ; k < 03 ;; k + + )
cosinfk] = 0 ;
I* findthree
1* find threemost
mostcompatible
compatiblefemales
females*/*/
for ( j = 0 ; j < 5 0 ; j++)
for(j=O;j<50;j++)
{{
iiff (( ssexOl
e x O ]==
= ='F'
F ))
{
{
factor = 3.14/180;
factor = 3 . 1 4 / 1 8 0 ;
c = cos ( ( sum [i) - ~umm ) * factor) ;
c = cos ((sump] - sump] ) * factor);
=
t j+ 1;
t =j+1;
ffor
a (k
( k = 0 ;; k << 3 ;; kH
k++))
{{
ifif (( cc >> cosin[k]
cosin[k]))
{
{
f* swap cosine values */
I* swap cosine values */
t_cosin = c;
t_cosin = c;
c = cosin[k) ;
c = cosin[k];
A Tryst with Arrays
Tryst with Arrays 325
325

cosin[k] == t_cosin;
t_cosin ;

1* swap codes*/
I*swap codes */
tt_code
c o d e ==1;
t;
mcode[i][k} ;
tt = mcode[i][k];
mcode[i][k) = t_code;
mcode[i][k] t_code ;
}
}
}
}}
}}
else
else
{
{
for ( k == 0 ;;kk <<33; k; k++
for(k + + ))
cosin[k) == 00;;
cosin[k]

1* find
I* findthree
three most
mostcompatible males*/*/
compatible males
for ( j == 00 ;;jj<<550
for(j 0 ; j; +j+++ ))
{{
if ( sexlil == 'M' )
rf{sex{fl=='lv1')
{
{
factor =~; 14 J 180;
factor = 3 : 1 4 / 1 8 0 ;
cc == cos
cOS((sump] - sum[j}))**factor);
( ( sum[i] -sumfl factor) .;
tl=jt1
= j + U;
for(k( k== 00;;kk<<33; k; kH
for + + ))
{
{
if ( c > cosin[k) )
if ( c > cosin[k])
{
{ 1* swap cosine valueS */
_
I* swap ecosine
1 cosn c:, values */
t_cosin = c;
c = cosin[k) ;
ccosin[k]
= cosin[k];
= 1 eosin;
cosin[k] = t_cosin;
1* swap codes
I* codes*/ */
-
1 code=t'
t_code = t; ,
t = fcode(i][k] ;
f=fcode[i][k];
fcode[ij[k)==t_code;
fcode[i][k] I_code ;
326
326 Exploring C
Exploring C

}}
}}
}}
}}
}}
}}
printf ("\nMost
printf ( "\nMost compatible
compatible female
female mates
mates forfor males:");
males:" ) ;
printf ( "\n 0 means
printf ("\n 0 means no mate"); no mate" ) ;
for(i=0;i<50;itt)
for ( i = 0 ; i < 5 0 ; i++)
{
{
if ( sex[i) == 'M' )
if (8ax[0== 'M')
{
{
printf ( "\nMale code no.: %d", i + 1 ) ;
printf ("\nMalecode no.: %d", i + 1 ) ;
printf ( "\nFemale code nos.: " ) ;
printf ("\nFemale code nos.:");
printf ( "%d %d %d", mcode[ij[O), mcode[ij[1), mcode[ij(2)) ;
printf ("%d %d %d", mcode[i][0], mcode[i][1], mcode[i][2])
}
}
}}
printf ("\nMost
printf ( "\nMost compatible
compatible male
male mates
mates forfor females:");
females:" ) ;
printf ( "\n 0 means
printf ("\n 0 means no mate") ; no mate" ) ;
for ((ii == 00 ;; ii << 5500 ;; i++)
for itt )
{{
if ( sex[i] == 'F')
if(sex[i]== 'F' )
{
{
printf ("\nFemale code no.: %d", i + 1 ) ;
printf
printf ("\nFemale
( "\nMale code code no.:" %d",
nos.: ) ; i+ 1);
printf
printf ("\nMale
( "%d %dcode %d", nos.:");
fcode[ij[O), fcode[ij[11, fcode[ij[2] ) ;
}
printf ("%d %d %d", fcode[0[O], fcode[i][1], fcode[i][2]);
}
}
}
}
}

Explanation
Explanation

In
In the
the first
first for
for loop
loop the
the sex
sex of
of each
each applicant
applicant and
and their
their responses
responses
to
to the
the 88 questions
questions areare received
received through
through the
the keyboard
keyboard andand stored
stored
in arrays sex[ ] and.sum[ ]. The next for loop is the most
in arrays sex[ ] and, sum[ ]. The next for loop is the most
important
important part part of
of this
this program.
program. ItIt finds
finds out
out three
three most
most com-
com-
, A Tryst
Tryst with Arrays
withArrays 327
327

patible females for each male and stores their code numbers in
the array mcode[ ][ ][].]. Similarly, it finds the three most com-
patible males for each female and stores their code numbers in
the array fcode[
fcodef ][].
][ ]. While calculating the most compatible
males for aa female
males for female (( or or vice
vice versa
versa )) the
the difference
difference of
of the
the
responses are used,
responses are used, with
with aa basis
basis that
that larger
larger the
the cosine
cosine value
value
more compatible is
more compatible is the
the couple.
couple. Finally,
Finally, through
through aa set
set of
of for
for
loops the three
loops the three most
most compatible
compatible females
females forfor each
each male
male (( and
and
vice
vice versa
versa)) are
are printed
printed out.
out.

(6)
(6) Program
Program

#include "conio.h"
#include "conio.h"
a[81];;
int a(81]
main(
main())
{{
=
int sr = 5, sc =
SC = 30, er, ec
ec;;
int n, num, row, col, i, j, I, k, sum == 00 ;

printf ("Enter
( "Enter the size of odd square matrix
matrix"); U ) ;

scant ("%d", &n);


("%d", &n)
printf ("Enter
( "Enter initial series");
in~ial number of the series" );
scant ("%d",
scant &num);;
("%d", &num)

clrscr();;
clrscr()
g o t o x y(35,
gotoxy ( 3 5 ,11 ) ;;

er == sr + n * 2;
2 ; 1*
/* ending row */
ec = sc + n * 3;3 ; 1*,
/* ending column */

drawbox ((sr,
drawbox sr, sc, er, ec)
ec);

i == 1 ; / 1** top
top row */
jj == 1 + nn // 22;; /*
1* middle of top row
row*/
*/

for ((kk =
= 0 ;; k << n * nn;; ktt
k++))
328
328 Exploring
Exploriffg C
C

{
I* findrow,&
1* find row &colcolwhere
wherenumber
numberisistotobe
beplaced
placedon
onscreen
screen*/*/
row
row == (sr
( sr ++ 1)
1 ) ++ ( i - 1 ) * 22 ;;
col = (sc + 1 ) + (j - 1 ) * 3 ;
col=(sc+1)+(j-1)*3;

gotoxy (col,
( col, row);
row) ;
printf
printf ("%d",
( "%d", nnum
u m) ;;

calculatepos~ion
1* calculate
I* positionwhere
wherenumber
numberisistotobe
beplaced
placedininarray
array*/*/
1=(i-1 )*n+(j-1);
l= (i-1)*0 + (j-1);
a[l]
a(1] == num;
num;
num++;
num++ ;

1* go one row
I*go row up*/
up */
i-- ;
i~;

I* goone
1* go onecolumn
columntotoright
right*/*/
j++ ;

checkififwe
1* check
I* wereach
reachoutside
outsidethe
thesquare
square*/*/

if (i
( i ==
== 0)0)
ii = nn ;

iiff (i( i ==== nn+ 11))


i = 1;

if (j == 0)
0)
j = n;

if (j
(j == n ++ 11 ))
j = 1i ;;

l1=(i-1)*n+(j-1);
= (i-1)*n + (j-1);

1* ififsquare
I* squarealready
alreadyfilled
filled*/*/
if ((a|l] 1=0)
a(O != 0) .
A Tryst
Tryst with
with Arrays
Arrays 329

incrementrow
1* increment
I* rowbyby2,2,decrement
decrementcol
colbyby11*/*/
ii ++=2;
=2;
jj--- ; ;

adjustr(1ll
1* adjust
I* rowand
andcol
colififoutside
outsidethe
thebox
box*/*/

iif(i>n)
f(i>n)
=
ii = i-n;
i- n;

iiff (j
( j ==== 00))
=
j = n;
n;
}}
}}

<= ( n * ( n - 1 ) ) ;; ii +=
for ( ii = 0 ;; i <= += nn))
sum =
sum = sum sum ++ a[i];
ali] ;

gotoxy
gotoxy (sc,
( sc, er ++ 22)) ;;
printf
printf ("Horizontal,
( "Horizontal, Vertical
Vertical & Diagonal
Diagonal sum
sum = %d", sum)
sum)
}}

/*
f* draw
draw squares
squares into whichwhich numbers
numbers are to be
be displayed
displayed */
drawbox
drawbox (sr, ( sr, sc, er, ec
ec))
int sr, sc,
SC, er, ec ec;;
{{
int i, jj; ;

for
for ((jj == sr;
sr ; jj <=
<= er;
er ; j ++=
= 22 ))
{
{
=
for ( i sc + 1 ; i < ec ; iff )
for ( i = sc + 1 ; i < ec; i++)
{
{
gotoxy ( i, j ) ;
gotoxy ( i , j ) ;
printf ( "%c', 196) ;
printf ("%c", 1 9 6 ) ;
}
}
}}
for ((ii == sc;
for sc ; ii <=
<= ec;
ec ; ii +=
+= 33 ))
330
330 Exploring C
Exploring C

for (j =
( j = sr + 11 ;;jj << eerr ;; jjtt
+ + ))
{{
gataxy
gotoxy (( ii,, jj )) ;;
printf (("%c".
"%c", 179) 1 7 9 ) ;;
}}
}

for ((ii = sc + 3
far 3 ;; i << ec
ec;: ii +=
+= 33 )
{{
gataxy
gotoxy ((i,i, sr)
s r ) ;;
printf ( "%c",
printf ("%c", 194) 1 9 4 ) ;;
gataxy
gotoxy ( i , e r ) ;;
( i, er )
printf (("%c",
"%c", 193)
1 9 3 ) ;;
}

far (j = sr + 22 ;; jI<< er;


for (j er ; j += 2)
2)
{{
gataxy
gotoxy (( sc,
s c ,j)j ) ;;
printf (("%c",195);
printf "%c", 195 ) ;
gataxy (( ec,
gotoxy e c ,j)j ) ;;
printf ( "%c·,
printf ("%c", 180)1 8 0 ) ;;
}

for (j
far ( j = sr + 22 ;; j << er
er;; j += 22 ))
{{
far sc ++ 33;; ii << ec
for (( ii == sc ec;; ii +=
+= 33 ))
{
{
gataxy (i, i) ;
gotoxy ( i , j ) ;
printf ( "%c", 197) ;
printf ("%c", 1 9 7 ) ;
}
}
}}
"

gotoxy (sc,
gataxy sr);
( sc, sr)
printf (("%c", 218);
"%c", 218)
gotoxy ((ec,
gataxy er);
ec, er)
printf (("%c", 2 1 7 ) ;;
"%c", 217)
· A Tryst
Tryst with
with Arrays
Arrays 331
331

gotoxy (ec,
gotoxy sr);
( ec, sr)
printf ("%c", 191
printf ("%c", 1 9 1)) ;;
gotoxy
gQtoxy (sc, e r ) ;;
( sc, er)
printf (("%c",192);
printf "%c·, 192) ;
}}

Explanation
Explanation

Even though
Even though this
this appears
appears toto aa be
be problem
problem of
of 2-D
2-0 array,
array, aa 1-0
1-D
array has been used. This is just to accomodate all problems
beginning from a 3 x 3 square to a 9 x 9 square. The 1-D
beginning 1-0 array
a[ ]] has
a[ has been
been declared
declared asas external
external array
array so
so that
that to
to begin with
begin with
its elements
elements are initialised
initialised to O.0.

Once into the main(


main( ), the size of the matrix and the starting
number of the series is received ihrough
through the pair of scanf( )s.
Depending upon the size of the square the ending row and
Depending
ending column are calculated, and using these and the starting
row and starting column, the box is constructed by calling the
drawbox() function.
drawbox( ) function.

Since there
Since there areare nn * nn squares
squares toto be
be filled
filled we
we use
use aa for
for loop
loop to to
do so. Within
do so. Within the the for
for loop,
loop, first
first we
we calculate
calculate the
the rowrow andand
column
column wherewhere the the number
number is is to
to be
be placed,
placed, reach
reach there using
there using
gotoxy(),
gotoxy(), and then print
and then print out
out the
the number.
number. Next Next wewe calculate
calculate the the
position
position where
where the the number
number should
should be be placed
placed inin the
the array and
array and
then we place
then we place thethe number
number inlhe
in 1he array.
array. With
With this
this over,
over, we we gogo
one
one row
row up up and
and oneone column
column to to the right by
the right by decrementing
decrementing and and
incrementing
incrementing ii andj and j respectively.
respectively. On On doing
doing this
this it
it is
is checked
checked
whether
whether we reach outside
we reach outside the
the box.
box. If so, the
If so, the values
values of of ii andj
and j
are
are appropriately
appropriately adjusted.
adjusted. If
If there
there is
is already
already aa number
number present
present
at this location,
at this location, then then once
once again
again ii and
and jj are
are readjusted
readjusted SG so (hat
(hat
the number is placed immediately below
the number is placed immediately below the number last the number last
placed
placed in in the square. This
the square. This whole operation is
whole operation is carried
carried through
through
the loop till
the loop till all
all the
the squares
squares have
have been
been filled up.
filled up.
9
Pulling
Pulling the
the Strings

L
T
T he way
he way aa group
group of
likewise aa group
likewise
array. Character
array.
of integers

arrays are
arrays are used by programming
can be
integers can
group of.
of characters
be stored
stored in
can be
characters can
Character arrays
in an
be stored
often called
are often
programming languages
an integer
stored in
integer array,
array,
in aa character
called 'strings'.
character
'strings'. Character
languages to manipulate
Character
manipulate text such
as words and sentences.
sentences. A string in C is always terminated by a null
character ( '\0'
'\0' ). The ascii value of '\0'
'\0' is O.The
0. The following figure
illustrates how a string is stored and accessed.
accessed.

N
N

4001
4001
aa

4002
4002
gg
4003
4003
P
p

4004
4004
uu

4005
4005
rr

4006
4006
» 1I
\0
4007
4007

main()
main()
{
static char
static namefj =
char name[] "Nagpur";;
= "Nagpur"
int ii ==0;0;
int
whiie(name[i]!='\0')
while ( name[ij 1='\0' )
{
* printf
printf (("%c", namep]);
"%c", name[i] );
i++;;
itt
}
}

Figure 9.1 Usage of string

Now aa few
Now few tips about the
tips about the usage
usage of
of strings
strings in
in C programs:
C programs:
Pulling the
Pulling Strings
the Strings 335
335

(a)
(a) A
A string can also
string can also be initialised as,
be initialised as,
static "Nagpur";
char[] = "Nag
static charl] pur" ;
Here '\0' is not necessary. C inserts it automatically.
Here '\0' is not necessary. C inserts it automatically.
(b) String elements can also be accessed using pointers as shown.
(b) String elements can also be accessed using pointers as shown.

K
K
1 i nn s
1 m a n

4001 4002 4003 4004 4005 4006 4007 4008 4009* i


4001 4002 4003 4004 4005 4006 4007 4008 4009

ptr
ptr

1
4001
I
main()
main()
{
static char
static name[] = "Klinsman";
char name[] "Klinsman" ;
char*ptr;
char*ptr'
while *ptr!='\0')
while ( *~r != '\0' )
{{
printf (("%c",*ptr);
printf "%c', *ptr) ;
ptr++;
ptr++ ;
}}
}}

Figure 9.2 Pointers


Figure 9.2 Pointers and
and Strings
Strings

(c)
(c) scanf() and
seanf() and printf()
printf() offer
offer aa simple
simple way
way of
of doing
doing string
string II
1/ O.
O.

main()
main( )
{{
char name[25];;
char name[25]
scanf ("%s",
scant n a m e ) ;;
( "%s", name)
printf (("%s",
printf n a m e ) ;;
"%s", name)
}

l The %s is
The %s is aa format
format specification
specification for
for handling
handling aa string.
string.
336
336 Exploring C
Exploring C

Standard Library
Standard String Functions
Library String Functions
Inspite of
Inspite of the
the awesome
awesome power power thatthat CC puts
puts inin your
your hands,
hands, itsits
vocabulary is
vocabulary is limited
limited to to aa mere
mere 32 32 odd
odd words.
words. These
These words
words areare
supplemented by
supplemented by aa set
set of
of library
library functions.
functions. Though
Though these functions
these functions
are not
are not aa part
part of
of C's
C's formal
formal definition,
definition, they
they have become aa part
have become part and
and
parcel of
parcel of C,
C, and
and have
have been
been imitated
imitated more
more oror less
less faithfully
faithfully by
by every
every
designer of
designer of the
the CC compiler. Whichever C
compiler. Whichever C compiler
compiler you you are
are using its
using its
almost certain
almost certain that
that you
you would
would have
have access
access to to aa library
library ofof standard
standard
functions. There
functions. There isis aa large
large set
set of
of such
such library
library functions
functions for string
for string
handling and
handling manipulation. The
and manipulation. The following
following figure
figure gives
gives aa list
list of
of
commonly used string functions.
commonly used string functions.

Function
Function Purpose
Purpose

strlen
strlen Finds length
Finds length of of aa string
string
strcpy
strcpy Copies one
Copies string into
one string into another
another
strncpy
stmcpy Copies first
Copies first n n characters
characters of of aa string
string at at the
the end
end of
of
another
another
strlwr
strlwr Converts aa string
Converts string toto lower
lower case
case
strupr
strupr Converts aa string
Converts string toto upper
upper case
case .
strcmp
strcmp Compares two
Compares strings
two strings
strncmp
stmcmp Compares first
Compares first nn characters
characters of of two strings
two strings
strcat
strcat Appends one
Appends one string
string at the end
at the end ofof another
another
strncat
stmcat Appends first
A~pends first n n characters
characters of of aa string at the
string at the end
end
oof another
another
strstr
strstr Finds first
Finds occurrence of
first ~ccurrence of aa given
given string
string inin
another stnng
another string
strrev
strrev Reverses aa string
Reverses string
strset
strset Sets all
Sets characters of
all characters of string
string toto aa given character
given character

Figure 9.3 Standard


Figure 9.3 Standard library
library string functions
string functions
Pulling the Strings
Pulling Strings 337
337

Array Pointers to Strings


Array of Pointers Strings
A pointer
A pointer can
can point
point to
to aa string.
string. Ifwe
If we collect
collect aa number
number ofof such
such pointers
pointers
pointing to
pointing to different
different strings
strings inin an array we
an array get an
we get array of
an array of pointers
pointers to
to
strings. The
strings. The following figure shows
following figure shows array
array of
of pointers
pointers to
to strings
strings at
at
work.
work.

Strings stored
Strings stored in memory
in memory

1001
10.01 N
N aa gg pP uu rr \01 I
1008
1008 A
A gg rr aa • Ir
\0
•••• •

1012
1012 D
D ee 1I hh ii \0 Ii
1017
1017 c
C aa 1I cc uu tt ttlal\ola

Array of
Array of pointers namesfj
pointers names[]

1001 1 1008
1 1001 1012 i0171
10081 10121 1017

Figure 9.4 Array


Figure 9.4 Array of
of pointers to strings
pointers to strings

As can
As can be observed from
DCobserved the figure
from the figure the
the strings
strings themselves
themselves are stored
are stored
at different locations but their base addresses are stored in adjacent
at different locations but their base' addresses are stored in adjacent
locations in
locations in the
the array
array ofof pointers
pointers names[
names[ ]. ]. These
These strings
strings can be
can be
accessed through
accessed through thethe array
array ofof pointers
pointers asas shown
shown in in the
the following
following
program.
program.

main()
main( )
338
338 Exploring
Exploring C
C

{{
static char
static *names[] == {{
char *names[]
"Nagpur",
"Nagpur",
"Agra",
"Agra",
"Delhi·,
"Delhi",
"Calcutta"
"Calcutta"
}}; ;
int i;
i;

for ( ii = 00 ;; i <= 33 ;; iff


i++))
printf ("%s\n",
( "%s\n", names[i]);
names[ij ) ;
}}
Pulling
Pulling the
theStrings
Strings 339
339

Exercise
Exercise
[A]
[A] What
What will
will be
be the
the output
output of
of the
the following
following programs:
programs:

((1)
1) main()
main()
{{
static char
static char s[s[]] == "Rendezvous!";
"Rendezvou'J '" ;
printf ("%d", *( s ++strlen
printf ("%d", *( s strlen ((s)
s ) )) )) ; ;
}}

((2)
2) main()
main()
{{
char ch[2v] ;
charch[20];
int i;i;
int
for =
f o r ((i i= 00 ;;ii<<119;
9 ; i +itt
+ ))
*( ch + i ) =
*( ch + i) = 6 7 ;67 ;
*(ch ++ i)i)== \0';
*( ch ,\0' ;
I

printf ("%s", cchh )) ;;


printf ( "%s",
}

(3)
(3) main()
main()
{
{
char str[20];
char str[20] ;
int i;
int i;
for(i( i == 0;
for = 118
0 ; ii<<= 8 ;;i iff
+ + ))
i[str] = 'C'
i[str] = ' C ; ;
i[str] == \0';
i[str] '\0' ;
printf ("%s",
( "%s", sstr) t r ) ;;
}

(4)
(4) main()
main()
{{
char str[20];
str(20) ;
static
static int int ii;;
for (( ;; ;; ))
for
340
340 Exploring
Exploring C
C

{{
i++[str] == 'A' + 2 ,,
i++[str]
iiff ( ii ===
= 119)
9)
break;
}}
i[str] == '\0';
i[str] '\0' ;
printf ("%s",
printf ( "%5", sstr)
t r ) ;;
}

((5)
5) main()
main()
{{
static char
static str[ ]] == {{ 48,
char str[ 4 8 , 48,
4 8 , 48,
4 8 , 48,
4 8 , 48,
4 8 , 48,
4 8 , 48,
4 8 , 48,
4 8 ,48,
4 8 ,48
4 8 }} ;;
char*s;
char*s;
int i;
inti;
=
ss = str;
str;

{
( °;
for ( ii == 0 ; ii <=
for <= 99;; iffi++))
{
if ( *s )
if(*s)
printf ( "%c ., *s) ;
printf ("%c " , * s ) ;
SH;
s++;
}
}
}}

(6)
(6) main(}
main(J
{
{
static char
static char str[10]
str[1 0] == {{ 0,
0 , 0,
0 , 0,
0 , 0,
0 , 0,
0 , 0,
0 , 0,
0 , 0,
0 ,0,
0 , o}
0 } ;;
char*s;
char*s;
int ii;;
int
s == str
str;;
for ( °;
for (ii == 0 ; ii <=
{
< = 99 ;; iH
i++))
{
if (*s)
if(*s)
printf ( "%c", *s ) ;
printf ("%c",*s);
SH;
s++;
}}
}
Pulling
Pulling the
theStrings
Strings 341
341

( (7)
7) main()
main()
{{
chars[s(]]=="C
static char
static "esmart!!";
smart !!" ;
int
inti;i;
for ((i i== 00; ;s[i];
for itt )
s(i] ;i++)
printf ("%C
printf ("%c %c %c%c %c%c\n",
%c\n",s[i],
s[ij, *(*(ss++i i)) , ,i[s],
irs],*(*( i i++ ss)) ; ;
}}

(8)
(8) main()
main()
{{
static char s[s(]]== "Oinks
static char "Oinks Grunts
Grunts and
andGuffaws";
Guffaws· ;
printf ("%c\n",*(&s[2]));
printf ( "%c\n", *( &S[2] ) ) ;
printf ( "%s\n", s ++ 55 ));;
printf ("%s\n",s
printf ( "%s\n", s ) :
printf ("%s\n",s):
printf ("%c\n",*(s
printf ( "%c\n", *( s ++ 22 )) )) ;;
printf ("%d\n",s);
printf ( "%d\n", s) ;
}}

((9)
9) main()
main()
{{
static char
static s[251== T"The
char s[251 cocaine man";
h e cocaine man" ;
=
int ii = 00;;
int
charch;
char c h ;
ch == s[++i];
ch s[ttij;
printf ("%c%d\n",
printf ( "%c %d\n", cch,h , ii )) ;;
ch = s[itt];
ch = s[i++];
printf ("%c
printf ( "%c %d\n",
%d\n", cch,
h , i)i ) ;;
ch = itt[s]
ch = i++[s]; ;
printf ("%c%d\n",
printf ("%c %d\n", ch, ch, ii)) ;;
ch = ++i[s]
ttils]; ;
printf ("%c%d\n",
( "%c %d\n", ch, c h .i)i ) ;;
}}

((to)
10) main(
main())
{
{
arr[]] = "Pickpocketing my peace of mind.."
static char arr[ mind.."
342
342 Exploring
Exploring C
C

inti;
int i;
printf (("%c\n",*arr);
"%c\nH,*arr) ;
. arr++;
arr++ ;
printf
printf (("%c\n",*arr);
"%c\n", *arr) ;
}

((11)
11) main()
main()
{
{
static char
static str[]] == "Limericks";
char str[ 'Limericks' ;
char*s;
char*s;
=
ss = &str[6]
&str[6] -- 66 ;;
while (*s)
while (*s)
printf ("%c",
printf ( "%c", *s++
* s + +)) ;;
}

,(12)
12) main()
main()
{
{
static char
static *s[] == {{
char*sl]
"ice",
"ice",
"green",
"green",
·cone",
"cone",
"please"
"please"
}};;
staic char **ptr[ ] = {{ss ++ 33 ,,ss ++ 22 ,, ss ++ 11 ,, ss }} ;;
staic char **ptr[] =
char ***p == ptr
ptr;;
printf ( "%s\n" ,.**++p) ;
printf("%s\n",.**++p);
printf ( "%s\n" , *--*++p ++ 3)
printf("%s\n",*-*++p 3) ;
printf ("%s\n", *p[-2] + 3 ) ;;
printf ( "%5\n" , *p[-2] + 3 )
printf ( "%s\n" , p[-1](-1] ++ 11 )) ;;
printf("%s\n",p[-1][-1]
}}

((13)
13) main()
main()
{{
He itn for yourself'
static char s[ ]J = "C yourself;;
int i = 0;
0;
while
while ((sp])
sri] )
Pulling
Pulling the
the Strings
Strings 343
343

{{
f ( ss[i]
iif( [ i ] !=
! = "" ))
s[i]=s[ij+1;
sfjl = s(0 + 1 ;
itt ;
i++;
}}
printf ( ""%s",
% s " ,ss)) ;;
}

((14)
14) main()
main()
{
{
staticchar
static str[ ]1 == "For
char str[ "For youryour eyes
eyes only",
only" ,
int i;
int i;
char*p;
char*p;
for ((pp == str,
for str, ii == 00;; pp ++ ii <=
<= str
str ++ strlen
strlen ((sstr)
t r ) ;; p++,
ptt, i++)
itt )
printf ( "%c", *( P +
printf ("%c", *( p + i ) ) ; . i ) ) ;
}

((15)
15) main()
main()
{{
static char
static str[ ]1 == "MalayalaM";
char str[ "MaiayalaM" ;
char
char*s;ss :
ss=str+8;
= str + 8 ;
while ((ss >=
while >= str)
str )
{{
printf ("%c",*s);
printf ( "%c", *s ) ;
s--
s~;,
.
}
}
}}

((16)
16) main()
main()
{{
static char a[a[ ]1,:
static char "Ablewas
- "Able was IIere
ere IIsaw
saw elbA";
elbA" ;
char *t, *s,
char*t, *s, * b ;*b ;
ss == aa;;
bb == aa ++ strlen
strlen ((aa)) -- 11 ;;
tt == b;
b;
344
344 Exploring
Exploring C
C

while ((ss !=
!= t ))
{
{
printf (("%c",*s);
printf "%c·, *s ) ;
s++ ;
s++;
printf ( "%c", *t) ;
printf ("%c",*t);
t- ;
t-;
}
1

(17) main()
{{
static char
static char str[ =
str[ ]] = "Shall
"Shall we
we tell
tell the Deputy Director?";
the Deputy Director?" ;
printf ( "%s\n%s\n%s·, str, str + 6, str +
printf ("%s\n%s\n%s", str, str + 6, str + 9 ) ; 9) ;
}}

(18) main()
{
{
static char
static char s[ sf ]] =~ "C"e is;s aa philosophy
philosophy of
of life";
life· ;
chart[40]
chart[40]; ;
char *ss, *tt
char*ss, *tt;;
ss =e s:
ss s;
ttt u=tt; ;.
while (*ss)
while (*ss)
*tt++ =
*tt++ = *ss++
*ss++;;
*tt = '\0'
*tt = "\0'; ;
printf (( ""%s·,
printf % s " ,t t)) ;;
}

(19)
(19) main()
main()
{{
static char
static char s(s[ [=
}'= "Lumps,
"Lumps, bumps,
blimps, swollen
swollen veins,
veins, new
new pains";
pains· ;
chart[40]
chart[40]; ;
char ·ss, *tt ;
char*ss,*tt;
=
tttu tt; ;
ss =
ss es ;
s;
while (*tt++=
(*tt++ = *ss++ );
*ss+±);
Pulling
Pulling the
the Strings
Strings 345
345

printf ( "·%s"",
printf % s Mt )) ;;
}}

((20)
2 0 ) main()
main()
{{
char str1[]
static char
static = "dins" ;
slrl (J ='dills";
static char str2[20];; .•
static char str2[20]
static char str3[20]
static char str3(20] == "Daffo";
"Daffo· ;
iet I;
inti;
II == strcmp
strcmp (strcat ( str3, strcpy
( strcat (str3, strcpy (str2,
( str2, sstr1 ·Daffocills·)
t r l )) )),, "Daffodills")
( "I== %
printf ("I
printf %d·,
d " ,I)
l ) ;;
}

((21)
21) main()
mainO
{{
static int
static int arr[12];
arr(12) ;
printf ("%(T, sizeof
printf ( .%d", sizeof ((ar
a r r ))))- .;;
}}

((22)
22) main()
main()
{{
static char
static char *mess[]
*mess[] == {{ .
·Some love
"Some love one",
one·,
·Some love
"Some love two",
two·,
"I love one·,
"I love one",
·That is
"That you.
is you"
}};;
printf (·%d %d",
printf ("%d %d·, sizeof
sizeof (mess),
(mess), sizeof
sizeof (mess
(mess [1])
[ 1 ] ))) ;;
}}

((23)
23) main()
main()
{{
char names[3][20];
char names[3][20] ;
int i;
inti;
for ( i = 0 ; i <= 2 ; itt )
for ( i = 0 ; i <= 2 ; i++)
{
{
...~
346
346 Exploring
Exploring C
C

printf ("\nENTER
( "\nENTER N A M E :"" ) ;;
NAME:
scanf
scant ("%s", namesfj]);
( "%s", names[ij );
printf ("\nYou
( "\nYou entered %s",
%s", names[i]);
names[ij ) ;
}}
}}

(24)
(24) main()
{
{
static char
static char names[5][20]
names(5)[20] == {{
"Roshni',
"Roshni",
"Manish·,
"Manish",
"Mona",
"Mona",
"Baiju·,
"Baiju",
"Ritu·
"Ritu"
}};;
int i;i;
char*t ;
char*t;
=
ii = r;ames[3]
r,ames[3];;
= names[4) ;
names[3] = names[4];
names[4] = t ;;
for ( ii = 0 ;; i <= 4 ;; iff
i++))
( "%s\n", names[i])
printf ("%s\n", namesp]);;
}}

(25) main()
main()
{
{
static char
static char mess[6][30]
mess[6)[30] == {{
"Don't walk
"Don't walk in
in front
front of of me
me ...",
"I may
"I may not
not follow
follow;", ;",
"Don't walk behind
"Don't walk behind me..."me ....,
"I may not lead
"I may not lead;",;',
"Just walk
"Just walk beside
beside me...",
me ..' ,
"And be
"And be my
my friend."
friend.·
}} ;;
printf ("%c
( "%c %c", *( mess[2]
mess[2) + 99),) , *( *( mess + 22)) + 9)
9)) ;
}
Pulling the Strings
Pulling the Strings 347
347

(26)
(26) main()
main()
{{
static char mess[2][2][20]
mess[2}[2][20] == {{
{{
"A chink
"A chink in
in your
your armour",
armour",
"A voice
"A voice in
in your
your mailbox"
mailbox"
},
}.
{{
in your
"A foot in
"Afoot tooth",
your tooth",
"A hole
"A hole in
in your
your pocket"
pocket"
}}
}
}; ;
printf ("%s\n%s",
( "%s\n%s", mess[1][0],
mess[1][O], mess[0][1]);
mess[O][1] ) ;
}}

DB]
[B] Attempt the following:
following:

(1) Write a function xstrstr()


xstrstr( ) that will return the position where
one string is present within
within another string. If
If the second
second string
doesn't
doesn't occur in the first string xstrstr()
xstrstr( ) should return o.
return a 0.

For example, in the string "somewhere over the rainbow",


"over" is present at position 11.
11.

(2) Write a program to encode the following string such that


that it gets
converted into an unrecognizable
uurecognizable form.
form. Also write a decode
function
function to get back the original string.

"Man's reach must always exceed his grasp....


grasp .... or
or what
what is the
the
heaven for?"

(3) Write a program to count the number of of capital letters in


in the
the
following array of
of pointers to strings:

char *str[ ] = {{
static char*str[]
"AFRiendls...",
"A FRiend Is...",
"SomEOne Loving AtrUE...",
& trUE ...'.
348
348 Exploring
Exploring C
C

"fOr
·fOr insTance
insTance somEONE....",
somEONE. ...",
•exactlY
"exactlY likE yoU!!"
likE'yoU !I"
};
};

(4)
(4) Write
Write aa program
program to to print
print those
those strings
strings which
which are
are palindromes
palindromes
from a set of strings stored in the following array of
from a set of strings stored in the following array of pointers
pointers
to
to' strings.
strings.

static
static char*s[]
char *s[] = {
"MalayalaM",
"MaIayaIaM",
"To really mess
mess things
things up...",
up...",
"One
"One needs
needs to know
know CH"
C !!"
"able was IIere
ere IIsaw
saw elba"
elba"
}} ;;

(5)
(5) Write
Write aa program
program to to compress
compress the
the following
following string
string such
such that
that the
the
the
the multiple
multiple blanks
blanks are
are eliminated. Store the
eliminated. Store the compressed
compressed mes-
mes-
sage
sage in
in another
another string. Also write
string. 'Also write aa decompressant
decompressant program
program to to
get
get back
back the
the original
original string
string with
with all
all its
its spaces restored.
spaces restored.

"Imperial
"Imperial Palace.
Palace. Rome.
Rome. Attention
Attention Julius
Julius Caesar.
Caesar.
Dear
Dear Caesar,
Caesar, we we have
have the
the clarification
clarification you requested.
you requested
Details
Details to
to follow
follow byby courier.
courier. Meanwhile
Meanwhile stay
stay clear
clear of
of
Brutus.'
Brutus." 1
Pulling
Pulling the
the Strings
Strings 349

Answers
Answers

Answers
Answers to
to [A]
[AJ

(1)
(1) Output
Output

o
0

Explanation
Explanation

No
No 'Rendezvous
'Rendezvous !', !', but
but aa zero
zero isis printed
printed out.out. Mentioning
Mentioning the the
name
name of of the
the string
string gives
gives the
the base
base address
address of of the
the string.
string. The
The
function
function strlen(
strlen( ss )) returns
returns the
the length
length of of the
the string
string s[s[ ],
], which
which
in
in this
this case
case isis 12.
12. In
In printf(),
printf(), using
using the the 'contents
'contents of of' operator
operator
((often
often called
called 'value
'value at at address'
address' operator),
operator), we we are
are trying
trying to print
to print
out
out the contents of the 1ih address from the base address of
the contents of the 12 th
address from the base address of
the
the string.
string. AtAt this
this address
address there
there is
is aa ''\0',
\ 0 \ which
which is automatically
is automatically
stored
stored to to mark
mark the the end
end ofof the
the string.
string. The The ascii
ascii value
value ofof '\0'
'\0' is
is
0,
0, which
which is is what
what is is being
being printed
printed by by the printf().
the printf().

(2) Output
Output

ccccccccccccccccccc
CCCCCCCCCCCCCCCCCCC

Explanation
Explanation

Mentioning
Mentioning the the name
name of the the array
array always
always gives
gives its base address.
its base address.
Therefore ( ch i ) would give the address of the i element
Therefore ( ch + j ) would give the address of the jlh element
th

from
from the
the base
base address,
address, and and *(*( ch
ch + ij )) would
would give
give the
the value
value atat
this
this address,
address, i.e.
i.e. the
the value
value of of the
the ijlh element.
,h
element. Through
Through the for
the for
loop
loop wewe store
store 67,
67, which
which is is the
the ascii
ascii value
value of
of upper
upper case
case ''C',
C , in
in
all the locations of the string. Once the control reaches outside
all the locations of the string. Once the control reaches outside
the
the for
for loop
loop the
the value
value of of ij would
would bebe 19,
19, and
andinin the 19th location
the 19 location
th

from the
from the base
base address
address we store aa '\0'
we store '\0' to
to mark
mark thethe end
end of
of the
the

l
350
·350 Exploring C
Exploring C

string. This
string. This is
is essential,
essential, as the compiler
as the compiler has
has no
no other
other way
way ofof
knowing where the
knowing where the string
string is
is terminated.
terminated. In In the
the printf(
printf( )) that
that
follows,
follows, %s %s isis the
the format
format specification
specification forfor printing
printing aa string,
string,
and ch gives
and ch gives the base address
the base address ofof the
the string.
string. Hence
Hence starting
starting from
from
the first element, the complete string is printed
the first element, the complete string is printed out. out.

(3)
(3) Output
Output

ccccccccccccccccccc
CCCCCCCCCCCCCCCCCCC

Explanation
Explanation

If your
If your concept
concept of of arrays
arrays isis fool-proof,
fool-proof, you
you should
should find
find the
the
above output only natural.natural. If
If not, here's
here's your chance to make
it so. C makes no secret of the fact that it uses pointers internally
Cmakesno internally
to access array elements.
elements. With the knowledge of how array
elements are accessed using pointers,
elements pointers, we can think of str[i]
str[i] as
*( str
*( str + ii )).. Basic
Basic maths
maths tells
tells us
us that
that *(
*( str
str + ii )) would
would be same
be same
as *(
*( i + str
str).). And if str[i]
str[i] is same as *(*( str
str + i),
i). then naturally
*( i + str)
*( str ) would be same as i[str]. i[str].

Thus, we
Thus, we can
can conclude
conclude that
that all
all the
the following
following expresssions
expresssions are
are
different ways of referring the ith
i element of the string:
th
string:

str[ij
str[U
*( str + i)
*( i + str)
str)
i[str]

Hence, through
Hence, through the
the for
for loop
loop upper
upper case
case C
C is
is stored
stored in all the
in all the
elements of the string. A '\0'
elements '\0' is stored to mark the end of the
string, and
string, and then
then the
the string is printed
string is printed out
out using
using printf(
printf().).

(4)
(4) Output
Output

ccccccccccccccccccc
CCCCCCCCCCCCCCCCCCC
f
Pulling the Strings
Pulling Strings 351
351

Explanation
Explanation

Here, the
Here, the structure
structure of,the
ofthe for
for loop
loop has
has been
been reduced
reduced to to only
only 22
semi-colons.
semi-colons. We We can
can afford
afford to
to do
do so
so because
because all all the
the three
three tasks
tasks
(initialisation, testing and
(in~ti;rtis~tion,testing and incrementation
incrementation )) of of the
the for
for are
are being
being
accomplished
accomplished by by three
three different
different statements
statements in in the
the program:
program:
declaring ii as
iIecI~ng as aa static int ensures
static int ensures that
that ii is
is initialised
initialised toto 0,
0, the
the if
if
condition
condition tests when to
tests when to get
get out of the
out of the loop,
loop, and
and i++ takes care
i++ takes care
of the incrementation
of the incrementation part. part.

As the ++ operator
operator succeeds i, first the value of ji gets used in
the expression i++[str]
i++[str] and only then it gets incremented. incremented.
Since we know that str[i] str[i] is same as i[str],
i[str], i[str]
i[str] denotes the
i element of the string. Starting from 0, ji takes values upto
th
jth
18,
18, and
and each
each time
time 'A' + + 22 is
is stored
stored in
in the
the string
string elements. Can
elements. Can
we
we add add aa character
character and and anan integer?
integer? Yes,
Yes, as as any
any character
character is is
stored
stored as as its
its corresponding
corresponding ascii ascii value.
value. The
The ascii
ascii value
value of'
of 'A'
A'
is 65, and
is 65, and onon adding
adding 22 toto this
this we
we get
get 67,
67, which
which happens
happens to be
to be
the ascii value
the ascii value of of 'C'.
' C . Thus,
Thus, uppercase
upper case 'C'' C isis stored
stored inin elements
elements
o0 toto 18
18 of
of the
the string.
string. When
When ji becomes
becomes 19, 19, break
break takes
takes the
the
control
control out
out ofof the
the for
for loop,
loop, where
where aa '\0'
'\0' is
is inserted
inserted in in the string
the string
to mark its
to mark its end.
end. The
The string
string isis then
then printed
printed outout using
using printf().
printf().

(5)
(5) Output
Output

00000000000
000000000

Explanation
Explanation

In all
In all 10
10 elements
elements of of str[
str[],], an
an integer,
integer, 48
48 is
is stored. Wondering
stored. Wondering
whether aa char
whether char string
string can
can hold
hold ints?
ints? The
The answer
answer is is yes,
yes, as
as 48
48
does
does not get stored
not get stored literally
literally inin the
the elements.
elements. 48 48 is
is interpreted
interpreted
as
as the
the ascii
ascii value
value of
of the
the character
character to to be
be stored
stored inin the
the string. The
string. The
character corresponding to
character corresponding to ascii
ascii 48
48 happens
happens to to be
be 0,
0, which is
which is
assigned
assigned toto all the locations
all the locations of of the
the string.
string.
352
352 Exploring
Exploring C

s, aa character
s, character pointer,
pointer, is assigned the
is assigned the base
base address
address of of the string
the string
str[ ].
str[ J. Next,
Next, inin the
the if
if condition,
condition, thethe value
value atat address contained
address contained
in
in ss is checked for
is checked for truth/falsity.
truth/falsity. As As 00 represents
represents asciiascii 48,
48, the
the
condition evaluates
condition evaluates to to true
true everytime, until the
every time, until end of
the end of the
the string
string
is reached.
is reached. At At thethe end
end ofof the
the string
string aa '\0',
' \ 0 \ i.e.
i.e. ascii
ascii 00 isis
encountered, and
encountered, and thethe if
if condi
condition fails. Irrespective
tion fails. Irrespective of of whether
whether
the condition is
the condition is satisfied
satisfied oror not,
not, ss is
is incremented
incremented so so that
that each
each
time it
time it points
points to
to the
the subsequent
subsequent arr!ly
array element.
element. ThisThis entire logic
entire logic
is repeated
is repeated in the for
in the for loop,
loop, printing
printing outout 10
10 zeroes
zeroes in in the
the process.
process.

(6)
(6) Output
Output

No output
No output

Explanation
Explanation

Though you
Though you may
may not
not have
have expected
expected zeroes
zeroes to
to be
be outputted this
outputted this
time, you
time, you surely
surely did
did expect some output!
expect some output! We stored the
We stored the char-
char-
acter corresponding
acter corresponding to to ascii
ascii 0
0 in all 10
in all 10 elements
elements of of the
the string.
string.
Next, we
Next, we assign
assign s,
s, aa char
char pointer,
pointer, the base address
the base address ofof the
the string.
string.
Through the
Through the for
for loop,
loop, wewe are
are attempting
attempting to to print
print out all ele-
out all ele-
ments one
ments by one,
one by one, but
but not
not before
before imposing
imposing thethe if
if condition.
condition.

The if
The irisis made
made to to test
test the
the value
value atat address
address contained
contained in in ss before
before
the execution
the execution of of the
the printf().
printf( ). The
The first
first time,
time, *s
*s yields ascii o.
yields ascii 0.
Therefore the
Therefore the if
if statement reduces to
statement reduces to if(O),
if(0), and
and as
as 0 0 stands for
stands for
falsity, the
falsity, the condition
condition fails.
fails. Hence,
Hence, ss is
is incremented
incremented and and control
control
loops back
loops back to to for
for without
without executing
executing thethe printf(
printf(). The same
). The same
thing happens the next time around, and the
thing happens the next time around, and the next, and so on, next, and so on,
till the
till the for
for loop
loop ends,
ends, resulting
resulting inin no
no output
output at at all.
all.

(7)
(7) Output
Output

ecce
CCCC
Pulling the Strings
Pulling the Strings 353
353

ssss
ssss
mmmm
mmmm
aaaa
aaaa
rrrrr
rrr
tt tttt tt

!!!!
!!! !

Explanation
Explanation

The above
The above program
program rubs rubs inin the
the point
point that
that s[i], i[s], *(
s[i), irs], *( ss + ii )) and
and
*( ii + ss )) are
*( are various
various waysways of of referring
referring to to the
the same
same element,
element, that that
is the ii th element
is the th
element of of the
the string
string s.s. Each
Each element
element of of the
the string
string is is
printed
printed-out out four
four times,
times, till
till the
the end
end of
of the
the string
string isis encountered.
encountered.
Note
Note thatthat in in the
the for
for loop
loop there
there is an expression
is an expression s[i) s[i] inin thethe
condition
condition part. part. This
This means
means the the loop
loop would
would continue
continue to to getget
executed
executed till till s[i]
s[i) is
is not
not equal
equal toto zero.
zero. We
We can can afford
afford toto say
say thisthis
because
because aa string
string always
always ends
ends with ' \ 0 ' , whose
with aa '\0', whose asciiascii value
value is is
0. Thus the
O.Thus the for
for loop
loop will
will bebe terminated
terminated when when the the expression
expression
s[i] '\0'.
yields aa '\0'.
s[i) yields

(8)
(8) Output
Output

n
Grunts
Grunts and
and Guffaws
Guffaws
Oinks Grunts and Guffaws
Oinks Grunts and Guffaws
nn
404
404

Explanation
Explanation

In the first printf( ) the 'address


'address of
of' operator, &, gives the
address of the second element of the string. Value at this
address is 'n',
' n \ which is printed out by the printf()
printf() using %c.
%c.
354
354 Exploring C
Exploring

Since s gives the base address of the array, ( s + 5 ) would give


the address
address of the fifth element from
from the base 'address.
address. This
address is passed
address is passed to the second
to the second printf(
printf( ).
). Using
Using the
the format
format
specification
sv,ecification %s, the contents
%s, the contents of
of the
the string
string are
are printed
printed out
out the
the
55 h element
h
element onwards.
onwards.

The third printf()


printf( ) prints the entire string, as the base address
of the string is being passed to it.

The fourth printf(


printf( ) is made to print the second character of
the string, as
the string, as *( 2 ) is
*( ss + 2) is nothing
nothing but
but s[2]. Thus V
s[2]. Thus 'n' gets printed.
gets printed.

Does the
Does output of
the output of the
the final printf()) surprise
final printf( surprise you
you by printing
by printing
out
out aa number,
number, 404?
404? Note
Note that
that the
the format
format specification
specification %d%d is is
used
used with s, which gives the base address of the string. It
with s, which gives the base address of the string. It
happened
happened to be 404
to be when we
404 when we executed
executed the
the program,
program, which got
which got
printed out. On
printed out. On executing
executing the
the same
same yourself,
yourself, you
you may
may get any
get any
other
other address,
address, depending
depending on on what
what address
address is
is allotted
allotted toto the
the
string by the compiler.
string by the compiler.

(9)
(9) Output
Output

hh1i
h2
h2
ee3 3
! 3
!3

Explanation
Explanation

At first,
At first, ch
ch is
is set
set up
up with
with thethe value
value ofof the
the expression
expression s[++i].
s[++i]. AsAs
++ precedes
precedes i, i, first
first ii is
is incremented
incremented to to 1,
1, and
and then
then s[1]
s[l] is
is
assigned to
assigned ch. S[1]h
to ch. s[l], the
the first
first element
element of of the
the string
string s[
s[ ],
], is 'h'.
is 'h'.
So the first
So the first priritf() prints out
priIitf() prints out 'h'
'h' for
for ch
ch and
and 11 for
for i.
i.
Pulling the
Pulling Strings
the Strings 355
355

Next, ch
Next, ch is
is assigned
assigned the value given
the value given by
by the
the expression
expression s[i++].
s[i++].
This time,
This time, first
first the
the value
value of of ii is
is used
used and
and then
then ii is
is incremented
incremented
to 2.
to 2. Therefore
Therefore ch ch still
still remains
remains s[l],
s[1], i.e. ' h \ while
i.e. 'h', while ii is
is now
now 2.
2.

The third
The third time,
time, i++[s]
i++[s] is is assigned
assigned to to ch.
ch. This
This is
is evaluated
evaluated just
just
as s[i++]
as s[i++] was,was, assaying
as saying i[s]
i[s]isissame
sameas assaying
sayings[ij.
s[f].Firstly,
Firstly,value
value
of i,
of i, i.e. .2, is
i.e ..2, is used
used to
to give
give 2[s]
2[s] i.e.
i.e. 'e',
'e', the
the second
second element
element ofof
the string.
the string. After this, ii is
After this, is incremented
incremented to to 3.
J.

Finally, ch
Finally, ch is
is assigned
assigned thethe value
value ofof the
the expression
expression ++i[s]. This
++i[s]. This
time it
time it is
is not
not ii that
that is
is getting
getting incremented,
incremented, but but the
the value
value i[s].
i[s].
Firstly i[s]
Firstly i[s] isis evaluated,
evaluated, which
which gives
gives the
the 3rd
3 element
element of
r d
of the
the
string, since
string, since ii isis presently
presently 3. 3. This
This happens
happens to to be
be the blank
the blank
following the
following the word
word 'the'
'the' in
in the
the string.
string. Ascii
Ascii value
value of
of the
the blank
blank
character is 32, which is incremented by the ++
character is 32, which is incremented by the ++ operator, and operator, and
thus 33
thus 33 isis assigned
assigned to to ch.
ch. 33
33 is
is the
the ascii
ascii value
value ofof the character
the character
'!',
'!', which
which the the printf()
printf() displays,
displays. ii remains
remains stationary
stationary atat 3.
3.

(10) Output
(10) Output

Error message: Lvalue


Error message: Lvalue required
required in
in function
function main
main

Explanation
Explanation

Though everything
Though everything seemsseems toto be
be in
in order
order atat first glance, there
first glance, there
lies aa fundamental
lies fundamental error error in
in our
our program.
program. WhenWhen we we say
say arr,
arr, we
we
are referring
are referring to to the
the base
base address
address of of the
the string.
string. This
This is is the only
the only
information that
information that helps
helps the
the CC compiler
compiler keep
keep track
track of of the string
the string
arr[ ]. If this information is lost, there is no way
arr[]. If this information is lost, there is no way the compiler the compiler
can access
can access the the string.
string. So,
So, this
this particular
particular address
address is is given
given aa
favoured status,
favoured status, that
that of
of aa constant.
constant. TheThe statement
statement arr++ arr++ is is
essentially wrong
essentially wrong because
because aa constant
constant can't
can't be incremented and
be incremented and
hence
hence the the compiler
compiler asksasks for
for an
an lvalue,
Ivalue, which
which is is aa value
value that can
that can
be changed.
be changed.
356
356 Exploring C
Exploring C

(11) Output
(11) Output

Limericks
Umericks

Explanation
Explanation

The following figure should help in analyzing this program.


should,help program.

strf]
str[ ]

L
L i , m
m" e
e I, rr 1 ii 1 cc 'I k
k 1 ss 'I .\0 1 I
4001 4002 4003
4001 4002 4003 4004 4005 4006
4004 4005 4007 4008
4006 4007 4008 4009
4009 4010
4010

s s

Figure, 9.5

ss has been declared char, whereas


declared as a pointer to a char, s t r [ ] has
whereas str[]
been
been declared
declared asas aa character string. Let
character string. Let us
us now
now evaluate
evaluate the the
expression &str[6]
expression &str[6] -• 6. Here &str[6]
6. Here &str[6] gives
gives the
the address
address of the
of the
sixth
sixth element
element of
of the
the string.
string. This
This address
address can
can also
also be obtained
be obtained
by
by the expression str
the expression str ++ 6.
6. On subtracting 66 from
On subtracting from this,
this, we
we end end
up with good
up with old str,
good old str, the address of
the address of the
the zeroth
zeroth element,
element, which
which
is
is assigned to s.
assigned to s.

In the ppriotf(
r i n t f ( )),, the value at address s is printed,
address contained in sis printed,
and then ss gets incrementedincremented so that it points to the next
character
character in in thethe string.
string. The while loop
The while loop continues till ss doesn't
continues till doesn't
point to ' \ 0 ' , which marks the end of the string. When
point to '\0', which marks the end of the string. When s points s points
Pulling the Strings
Pulling Strings 357
357

to '\0',
to '\0', the
the value
value of
of *s
*5 would
would be
be 0,
0, aa falsity. Hence the
falsity. Hence whfle
the while
loop will be
loop will be terminated.
terminated.

(12) Output
(12) Output

cone

ase
reen

Explanation
Explanation

This time we seem to be faced with a galaxy of stars! stars! We


We would
would
do well to take the help of a figure in crossing them one by one. one.
At the outset,
At the outset, s[ s[ ]] has
has been
been declared
declared and
and initialised
initialised as
as an
an array
array
of
of pointers.
pointers, Simply saying 5s gives
Simply saying gives us
us the
the base
base address
address ofof this
this
array,
array, 4006
4006 as can be
as can be seen
seen from
from Figure
Figure 9.6.
9.6. ptr[]
ptr[ ] stores
stores the
the
addresses
addresses of of the
the locations
locations where
where the base addresses
the base addresses of strings
of strings
comprising
comprising s[ s[ ]] have
have been
been stored,
stored, starting
starting with
with the
the last
last string.
string.
To
To put it more
put it more clearly,
clearly, ptr[0]
ptr[O] stores
stores the
the address
address 4012, which
4012, which
is the address
is the address at at which
which base
base address
address ofof the
the string
string "please"
"please" is is
stored. Similarly, ptr[l] stores the address
stored. Similarly, ptr[l] stores the address 4010, which is4010, which is
where
where the the base
base address
address ofof the
the string "cone" is
string "cone" stored, and
is stored, and soso
on. Since ptr[
on. Since ptr[ 1] essentially
essentially stores
stores addresses
addresses ofof addresses,
addresses, it is
it is
aa pointer
pointer to to aa pointer,
pointer, and
and has
has been
been declared
declared as
as such
such using
using ****

Finally, the base address of ptr[


ptr[]] is asssigned to a pointer to a
pointer to a pointer, p. Reeling?! Going through
pointer to a pointer, p. Reeling?! Going through the
the figure
figure
would
would decidedly aid you
decidedly aid you to
to get
get disentangled.
disentangled. Thus,
Thus, pp is
is as-
as-
signed the address
signed the address 6020.
6020.
358
358 Exploring
Exploring C
C

Ii Ie Ie I\Oli Ir Ie Ie In I\Ole 1 0 In Ie 1\01211 Ie la Is Ie 1\01


1000 1004 1010 1015
s[O] s[l] s[2] s[3]

I 1000 1004 1010 1015


I
4006 4008 4010 4012

ptr[O] ptr[l] ptr[2] ptr[3]

4012 4010 4008 4006


I
6020 6022 6024 6026

P
6020
I
Figure 9.6
Figure 9.6

Having
Having sorted
sorted out
out what
what isis present
present where,
where, we
we now
now proceed
proceed to
to
the
the printf( )s.
)s. Let
Let us
us tackle
tackle the
the expressions
expressions one
one by
by one.
one.

*++p
**++p

The
The first
first one
one prints
prints out out the
the string
string starting from the
starting from address
the address
**++p. TheThe ++ goesgoes to to work
work first
first and
and increments
increments p p not
not to 6021,
to 6021,
but
but to
to 6022.
6022. The
The C compiler
compiler hashas been
been made
made to to understand
understand that
that
on
on incrementing
incrementing aa pointer pointer variable,
variable, it it is
is to
to point
point toto the
the next
next
location
location of of its iype. The
its type. The words
words 'of'of its
its type'
type' hold significance
hold significance
here.
here. AA pointer
pointer to to aa char
char onon incrementing
incrementing goes goes one
one byte
byte further,
further,
since
sinee aa char isis aa 1-byte entity. A
l-byte entity. A pointer
pointer toto an
an int points
points 22 bytes
bytes
further,
further, asas an
an int is is aa 2-byte
2-byte entity.
entity. Also,
Also, aa pointer
pointer by itself is
by itself is
Pulling the Strings
Pulling Strings 359
359

always aa 2-byte
always 2-byte entity,
entity, so
so incrementing
incrementing aa pointer
pointer to
to aa pointer
pointer
would advance
would advance you by 22 bytes.
you by bytes.

Having convinced ourselves


Having convinced ourselves that p now stores 6022, we go on
to evaluate
to the expression
evaluate the expression further,
further. *p signifies
signifies contents
contents ofof
6022,
6022, i.e.
i.e. 4010.
4010. **p
**p means
means value
value at
at this
this address,
address, i.e.
i.e. value
value at
at
4010,
4010, which
which isis the
the address
address 1010.
1010. The
The printf()
printf() prints
prints the
the string
string
at
at this address, which
this address, which is
is "cone".
"cone".

*--*++p + 33
*-*++p

p, presently
p, containing 6022,
presently containing which on
6022, which on incrementing
incrementing becomes
becomes
6024. Value at
6024. Value at this
this address
address is the address
is the address 4008,
4008, or
or in
in terms
terms of of
s, ss +
5, + 1.
1. On this the
On this the decrement
decrement operator
operator -—works
workstotogive
give4006,
4006,
i.e. s. Value at 4006, or *( *( s ) is 1000. Thus the expression is
now reduced
now reduced to to (( 1000
1000 + 33 ),), and
and what
what finally
finally gets
gets passed
passed to to
printf() is
printf() is the
the address
address 1003.
1003. Value
Value atat this
this address
address is
is aa '\0',
' \ 0 \ as
as
at
at the
the end
end ofof every string aa '\0'
every string '\0' is
is inserted
inserted automatically.
automatically. ThisThis
'\0' is
'\0' printed out
is printed out as
as aa blank
blank by
by printf(
printf().
).

*p[-2] ++33
*p[-2]

The current
The address in
current address in pp is
is 6024.
6024. *p[-2]
*P[-2] can
can be
be thought
thought of as
of as
*( *(
*( *( pp -- 22 )) )),, as
as num[i]
num[i] is is same
same as as *(
*( num
num + + ij )).. This
This in turn
in tum
evaluates
evaluates as as *(*( *(
*( 6024
6024 -- 22 )))),, i.e.
i.e. *(
*( *(6020)),
*( 6020) ), as
as p p is
is aa pointer
pointer
to aa pointer.
to pointer. This This is is equal
equal to to *(*( 4012 ), asas at
at 6020
6020 the address
the address
4012
4012 is is present.
present. Value Value a!at 4012
4012 is is 1015,
1015, i.e.
i.e. the
the base
base address
address of of
the fourth
the fourth string,
string, "please". Having reached
"please". Having reached the
the address
address ofletter
of letter
''p',
p \ 33 is added, which
is added, yields the
which yields the address
address 1018.
1018. The string
The string
starting from
starting from 1018 1018 isis printed
printed out,out, which
which comprises
comprises of of the last
the last
three letters
three letters of of "please",
"please", i.e. 'ase\
i.e. 'ase'.

PM1M1 ++ 11
p[-1][-1]

The above
The above expression
expression can
can be
be thought
thought ofof as
as *(
*( p[-l]
pl-I] -- 11)) + 1,
1,
as num[i]
num[i] and *(
*( num
num + i)amounts
i) amounts to the same thing. Further,
Further,
pj-I] can
p[-l] can itself
itself be
be simplified
simplified to *( pp -- 11 ).
to *( ). Hence
Hence we we can
can
360
360 Exploring
Exploring C

interpret the
interpret the given
given expression
expression as
as *(
*( *(
*( p
p -- 11 )) -- 11 )) + 1. Now let
1. Now let
us evaluate this expression.
expression.

Mter the execution of the ·third


After third printf(
printf( ), p still holds the
address 6024. *( *( 6024 - 1 ) gives *( tI( 6022),
6(22), i.e. address 4010.
Therefore the
Therefore expression now
the expression now becomes
becomes *( *( 4010
4010 •- 11 )) +
+ 1.1.
Looking
Looking at at the
the figure
figure youyou would
would agreeagree that
that 4010
4010 cancan bebe
expressed
expressed as as ss +
+ 2.
2. So
So now
now the
the expression
expression becomes
becomes *(*( ss +
+ 22 -•
l1)) + l1oorr **(( ss + l1)) + l1 Once
Once again
again thethe figure
figure would confirm
would confirm
that
that *( *( s5 + 11)) evaluates
evaluates to to *(
*( 4008
4008)) andand *(*( 4008)
4008 ) yields
yields 1004,
1004,
which
which is the base address of the second string "green". To this,
is the base address of the second string "green". To this,
11 is
is added
added to to yield
yield the
the address
address of of the
the first
first element,
element, 'r'.
V . With
With
this
this asas the
the starting
starting address, printf()) prints
address, printf( prints out
out what
what is remain-
is remain-
ing
ing of the string
of the string "green".
"green".

(13) Output
(13) Output

o juju gps zpvstfmg


D zpvstfmg

Explanation
Explanation

No, your
No, your computer
computer h~n'thasn't caught
caught aa virus!
virus! ItIt has
has done
done just what
just what
you
you instructed
instructed it it to.
to. The
t~e while
while loop
loop tests
tests the
the value
value of of the I
the jtht h

element
element of of the string. Since
the string. Since ihas
i has been
been initialised
initialised toto 0,
0, the
the first
first
time
time s[0],
5[0], i.e.
i.e. CC is used. Since
i.Sus,d. Since ''C'C hashas aa non-zero
non-zero ascii value,
ascii value,
the condition evaluates to true, and control
the condition evalua~es to true, and control passes to the passes to the ifif
statement.
statement. The The co'idiltion
condition to to be
be satisfied
satisfied here here isis that
that the
the ijth
element
element is is not
not aa blankspace.
blank space. s[0] s[O] satisfies
satisfies thisthis condition hence
condition hence
the contents of
the contents the oth
of the 0 element
th
element are are incremented
incremented by by 1.
1. Thus
Thus s[O],
s[0],
i.e. ' C having ascii value 67, is incremented
i.e. 'C' having ascii v~lue 67, is incremented to 68, which is to 68, which is
the
the ascii
ascii value
value of of upper
~p~r case ' D ' . The
case '0'. The newnew value
value of s[0] is
of s[O] is
therefore
therefore ''0'.
D ' . Next
Next iiisis ~ncremented
incremented to to 1,
1, and
and the
the while
while repeats
repeats
for s[l]. However,
for s[1]. However, the the'if condition fails
!·if condition fails this
this time,
time, as
as s[l]
s[l1 is
is aa
blank
blank space, so this eleJbent remains unchanged. Similarly, all
space, so this element remains unchanged. Similarly, all
non-blank elements are
non-blank elements are incremented,
incremented, and and the
the while
while ends
ends when
when
Pulling the Strings 361

the '\0' is
the reached. Lastly,
is reached. Lastly, the printf( )) outputs
the printf( outputs the
the changed
changed
string.
string.

(14) Output
(14) Output

FryuysoJ<space>
Fryu ysokspace>

Explanation
Explanation

strTl
str[ ~
F o r y o u r e y e s o n 1 y \0J
4001

P
p

4001
4001 l
|

Figure 9.7
Figure 9.7

The for
The for loop
loop here
here hosts
hosts two
two initialisations
initialisations and
and two incremen-
two incremen-
tations, which
tations, which isis perfectly
perfectly acceptable.
acceptable. However,
However, there
there must
must
always be
always be aa unique
unique test
test condition.
condition.

In the
In the initialisation
initialisation part,
part, pp is assigned the
is assigned the base address of
base address the
of the
string, and
string, and ii is
is set
set to
to O.
0. Next
Next the
the condition
condition is
is tested.
tested. Let
Let us
us
isolate this
isolate this condition
condition forfor closer
closer examination.
examination.

p + ii <=
<= str + strlen ((str)
str) ,

Since length
Since length of
of str[
str[]] is
is 18,·
18, str
str + strlen
strlen ((str
str )) would
would give
give the
the
address of
address of '\0' present
present at at the
the end
end of
of the
the string.
string. IfIf we'
we assume
assume
that the
that base address
the base address of of the
the string
string is
is 4001,
4001, then
then the
the address
address of
of
'\0' would
'\0' would bebe 4019.
4019. Since
Since pp has
has been
been assigned
assigned the
the base
base address
address
of the
of the string,
string, in
in the
the first
first go,
go, pp +0 0 would
would yield
yield 4001.
4001. Since this
Since this
362
362 Exploring
Exploring C

is less than 4019, the condition


condition holds good, and the character character
present at the address ( p + 0 )),, i.e. ''F',
F ' , is printed out. This can
be understood
understood better
better with the aid
with the aid of
of the
the Figure 9.7.
Figure 9.7.

After this,
After this, both
both pp andand iiare
are incremented,
incremented, soso that
that pp contains
contains 4002
4002
and ii contains
and contains 1, 1, and
and once
once again
again the
the condition
condition in in the
the for
for loop
loop
is tested. This
is tested. This time
time (( pp + i)yields
i ) yields 4003,
4003, whereas
whereas the the expressi
expression on
str+strlen
str + strleD((str) continues to
str ) continues to yield
yield 4019.
4019. Therefore
Therefore againagain the
the
condition
condition is satisfied and
is satisfied the character
and the character atat address
address 4003,
4003, i.e,
i.e. 'r'
'r'
gets
gets printed.
printed. Likewise, alternate elements
Likewise, alternate elements of of the
the string are
string are
outputted till iiis
outputted till is 8,
8, corresponding
corresponding to to which
which '1'
T is
is printed.
printed. Now,
Now,
when p and i are incremented one more time, the
when p and j are incremented one more time, the test condition test condition
evaluates
evaluates to:to:

<= str + strlen


p + i <= strlen ((str)
str )
4019 <= 4019
<= 4019

The 18th element of str str is of course the '\0',


' \ 0 \ which is also
printed out as
printed out as aa blank.
blank. On
On further
further incrementation
incrementation of of p and i,i,
p and
control snaps
control snaps out
out of the for
of the for and
and the program execution
the program execution is
is
terminated.
terminated.

(15) Output
(15) Output

MalayalaM
MalayaJaM

Explanation
Explanation

s, aa pointer
s, pointer to
to aa char, is assigned an
is assigned address 88 locations
an address ahead
locations ahead
of the base
of the base address
address of of the
the string.
string. That
That means
means 5s isis currently
currently
pointing
pointing to to the
the last
last element M ' of
4
element 'M' of the
the string.
string. IfIfwe
we assume
assume thethe
base address
. base to be
address to be 4001,
4001, then
then ss would
would contain
contain the
the address
address 4009.
4009.
Since
Since this
this address
address is is greater than the
greater than the base
base address,
address, first
first time
time
through
through thethe loop
loop the
the condition
condition isis satisfied.
satisfied. Next
Next the
the value
value ofof
the
the expression
expression *s is printed.
*5 is printed. Since
Since 5s contains
contains the
the address
address 4009,
4009,
the value at
the value at this
this address,
address, i.e.
i.e. 'M',
'M', gets
gets printed.
printed. Then
Then 5s is is
Pulling
Pulling the
the Strings
Strings 363
363'

decremented
decremented to
to point
point to
to the
the preceding
preceding element,
element, i.e.
i.e. the
the element
element
at
at address
address 4008.
4008.

This
This way
way one
one by
by one,
one, the
the elements
elements of of the
the string
string are
are printed
printed out
out
in
in the
the reverse
reverse order,
order, till
till ss equals
equals str,
str, the
the address
address of of the
the zeroth
zeroth
element.
element. That
That the
the output
output is is indeed
indeed thethe reverse
reverse of of the
the original
original
string
string can
can be verified ifif you
beverified you read
read""MalayalaM"
MalayalaM" backwards.
backwards. You You
have
have been
been presented
presented with
with aa string
string that
that reads
reads the
the same
same from
from
either
either end.
end. Such
Such strings,
strings, incidentally,
incidentally, go
go by
by the
the name
name
'Palindrome'.
'Palindrome' .

(16) Output
Output

AAbbllee
AAbbllee waass
waass IIII ee
ee

Explanation
Explanation

The
The char
char pointer
pointer ss is
is assigned
assigned the the base
base address
address of of string
string a[a[ ].
].
The
The char
char pointer
pointer bb is
is assigned
assigned the the address
address 24 24 elements
elements ahead
ahead
of
of the
the base
base address.
address. Why
Why 24? 24? Because
Because thethe function strlen(a)
function strleD(a)
yields
yields the
the length
length of
of the
the string
string a[ a[ ],
], which
which in in this
this case
case turns
turns out
out
to
to be
be 25.
25. Thu^b
Thus b points
points to
to 'A' present
present atat the
the end
end ofof the
the string.
string.
Another
Another character
character pointer,
pointer, t, is also
t, is also ini
initialised
tialised to to the
the same
same value
value
as
as b.
b. Assuming
Assuming the the base
base address
address of of the
the string
string toto be
be 5001*
5001~ ss
would
would be be assigned
assigned 5001
50tH andand bband and tt would
would be be assigned
assigned the the
address
address 5025.
5025.

Naturally,
Naturally, first
first time
time through
through thethe while
while looploop since
since ssand
and ttare
are
not equal, the condition is satisfied. Hence the printf() prints
not equal, the condition is satisfied. Hence the priDtf( ) prints
out
out the
the character
characterat at which
which ss is
is pointing.
pointing. ThusThus the
the character
character' 'A' A'
gets
gets printed.
printed. Now Now ss is is incremented,
incremented, so that it
so that it points
points to to the
the
character
character ''b'.
b ' . The
The next
next printf()
priDtf( ) prints
prints the
the value
value atat the address
the address
contained in Therefore another 'A' appears on the screen.
contained in t. Therefore another 'A' appears on the screen.
After
After printing,
printing, tt is is decremented
decremented so so that
that it
it starts
starts pointing
pointing to V.
to 'b'.
This
This goes
goes onon till
till ssand
and tt meet
meet each
each other,
other, whence
whence the the while
while

l
364
364 Exploring
Explonng C

ends. At
ends. At this instance, 5s and
this instance, and ttboth are pointing
both are pointing to
to 'r',
'r', the
the middle
middle
character of
character of the
the entire
entire string.
string.

(17) Output
(17) Output

Shall we tell
tell the Deputy Director?
Director?
we tell the Deputy
tell the Deputy Director?
Director?
tell the
tell the Deputy
Deputy Director?
Director?

Explanation
Explanation

Using %
Using s , the
%5, the format
format specification
specification for for aa string,
string, the p r i n t f ())
the priBtf(
prints three
prints three strings.
strings. The The addresses
addresses being
being passed
passed to printf( )) are
to priBtf( are
str, str +
str, str + (;
6 and
and str str +-
+ 9.
9. Since str is
Since str is the
the base
base address
address of of thethe
string, the
string, complete message
the complete message gets gets printed
printed out,
out, starting
starting from
from the the
zeroth element,
zeroth element. str str ++ 6(; is the address
is the address 66 elements
elements ahead
ahead of str,
of str,
i.e. address
i.e, address of of 'w'.
' w \ With
With thisthis as
as starting
starting address,
address, thethe second
second
output
output 'we ... ' is obtained Lastly, the part of the string 99th
'we ... ' is obtained. Lastly, the part of the string t h

element onwards
element onwards is is printed
printed out, as str
out, as + 99 denotes
str + denotes the the address
address
of the
of the 99th character
t h
character from from the the base
base address
address of of the
the string.
string.

(18) Output
(18) Output

C is a philosophy
philosophy of
of life

Explanation
Explanation

To begin
To with, ss
begin with, and tt are
ss and are assigned
assigned the the base
base addresses
addresses of of the
the
two strings
two strings s[ s[ ]] and
and t[t[ ].
]. In the while,
In the while, thethe value
value at address
at address
contained in
contained in ss
55 is
is tested
tested for
for operating
operating thethe loop.
loop. The
The first time
first time
through the
through loop ss
the loop 55 contains
contains the the base
base address
address of the string.
of the string.
Hence *ss
Hence *ss gives C \ whose
gives 'C',
4
whose ascii
ascii value
value is
is 67.
67. As
As any
any non-zero
non-zero
value is
value is aa truth
truth value, the condition
value, the evaluates to
condition evaluates true, and
to true, this
and this
value is
value is stored
stored at at the
the address
address contained
contained in in tt, i.e.
i.e. at
at the base
the base
address of
address of the
the string t[ ]. Note
string t[]. Note that
that the
the ++
++ operator
operator occurs
occurs after
after
Pulling the Strings
Pulling the Strings 365
365

the
the variables,
variables, so so after
after ''C'
C hashas been
been stored
stored inin the
the first location
first location
of
of the
the string
string t[ ], both both ss 55 and
and tt areare incremented,
incremented, so so that
that both
both
now
now point
point to to the
the first
first elements
elements of of s[
5[]] and
and t[
t[]] respectively.
respectively. In In
the second go, value at the address contained in ss is tested in
the second go, value at the address contained in ss is tested in
the
the while,
while, and and this
this time
time aa blank
blank is is encountered,
encountered, whose whose ascii ascii
value
value is is 32.
32. The
The condition
condition again
again holds
holds good,
good, therefore
therefore the blank
the blank
is
is stored
stored in in string
string t[ ], ], and
and ss55 and
and tt are
are incremented.
incremented. This goes
This goes
on till the end of the string is encountered. At the end of any
on till the end of the string is encountered. At the end of any
string,
string, aa '\0''\0' is is stored.
stored. Ascii
Ascii value
value of of '\0'
'\0' is
is 0,
0, which
which when when
tested
tested in in the
the while,
while, evaluates
evaluates to to falsity,
falsity, and
and the
the control
control comes
comes
out
out ofof the
the loop.
loop.

Note
Note that
that the
the '\0'
'\0' has
has not
not been
been stored
stored into
into string
string t[ ], hence
t[], hence the
the
compiler
compiler does
does not
not know
know where
where the
the string
string ends.
ends. WeWe dodo so
so by
by
inserting
inserting aa '\0'
'\0' on
on leaving
leaving the
the while.
while. Finally,
Finally, the
the contents
contents of
of
the
the string
string t[
t[]] are
are printed
printed out.
out.

(19) Output
(19) Output

Lumps, bumps, swollen veins, new pains

Explanation
Explanation

The
The program
program begins
begins by by assigning
assigning thethe base
base addresses
addresses of
of strings
strings
s[
s[]] and
and t[ ]] to
to the
the character
character pointers
pointers ss
ss and
and tt. The
The while
while loop
loop
that
that follows
follows next
next may
may raise
raise aa few
few eyebrows.
eyebrows. We We have
have made
made itit
compact
compact by by combining
combining the the assignment,
assignment, testtest condition
condition and
and the
the
incrementation
incrementation in in the
the while
while loop
loop itself.
itself. In
In effect,
effect. the
the while
whil'~ has
has
been
been reduced
reduced to:to:

while (*tt++
( *tt ++ == *ss++)
*55++ )

Here
Here the
the null
null statement
statement isis executed
executed soso long
long as
as the
the condition
condition
remains
remains true.
true. How
How the
the condition
condition is
is evaluated
evaluated is
is like
like this...
this ...
366
366 Exploring
Exploring C

In the while
whUe the value at the address stored in ss S5 replaces
replaces the
value at the address stored in tt. U..-After
After assignment
assignment the the test
test isis
carried out to
carried out to decide
decide whether
whether the the while
while loop loop shouldshould continue
continue
or not.
or not. This
This is is done
done by by testing
testing the the expression
expression *tt for for truth/fal-
truth/fal-
sity. Since currently
sity. Since currently tt U is pointing to
is pointing ' 1 ' of
to '1' of 'lumps',
'lumps', *tt *tt gives
gives
T which is
'1' which is aa truth
truth value.
value. Following
Following this this ss ss andand U tt both
both are are
incremented,
incremented, so so that
that they
they have have the the addresses
addresses of the first
of the first ele-
ele-
ments
ments of of strings
strings s[ 5[]] and
and t[ t[]] respectively.
respectively. Since Since the condition
the condition
has
has been satisfied the
been satisfied the null
null statement
statement is is executed.
executed. This goes on
This goes on
till
till the
the end
end of of the
the string
string s[ s[ ]] is
is encountered,
encountered, which which is is marked
marked
by
by thethe presence
presence of ' \ 0 ' , having
of aa '\0', having ascii
ascii valuevalue O. 0. When
When this this
character is stored in t[ ], *tt would give
character is stored in t[ ], *it would give '\0'. This time when ' \ 0 ' . This time when
the
the condition
condition is is tested,
tested, it it evaluates
evaluates to to false
false since since *tt yields aa 00
*tt yields
(( ascii
ascii value'
value of ' \ 0 ' ).-Thus,
of '\0' ).-Thus, all all elements
elements of of thethe first
first string
string are are
faithfully copied into the second one,
faithfully copied into the second one, including the '\0'_ On including the ' \ 0 ' . On
printing
printing outout string
string t[],t[ ], we
we get get the
the entire
entire string
string as as it
it was
was in in 5(].
s[ ].

(20) Output
(20) Output

11=0
=0

Explanation
Explanation

This example
example uses 3 string functions. If
If t[
t[ ]] is the target string
and s[ ] the source string, then the functions behave as mPQ- men-
tioned below.
tioned below.

strcpy (%
strcpy (t, s5 )):: Copies
Copies the
the contents
contents ofof s[]
s[ ] into
into t[]
t[ ] and
and returns
returns
address
the base address of the target string i[ ].
tt].

strcat ((t,
streat t, ss ):
): Concatenates
Concatenates oror appends
appends the
the source
source string at the
string at the
end of target string.
string. This also returns th,e
the base address of the
target string.
target string.
Pulling
Pulling the
the Strings
Strings 367
367

strcmp
stremp (t,
( t, ss ):
): Compares
Compares the
the two
two strings
strings and returns aa 00 if
and returns if they
they
are
are equal
equal and
and aa non-zero
non-zero value
value if
if they
they are
are unequal.
unequal.

Evaluating
Evaluating thethe parentheses
parentheses outwards
outwards from
from inside,
inside, let'slet's see
see
what
what strcpy()
strcpy() succeeds
succeeds in in doing.
doing. The
The string
string strl[
strl[], ], i.e.
i.e. "dills"
"dills"
gets
gets copied
copied into
into str2[
strl[ ],
], and
and the
the base
base address
address str2
strl isis returned.
returned.
The
The expression
expression now
now looks
looks like:
like:

I = strcmp (strcat
( strcat (str3,
( str3, str2),
str2l, "Dafodills");
vDafodills") ;

Next,
Next, strcat()
strcat() writes
writes the
the contents
contents ofof str2[
str2[],], i.e.
i.e. "dills"
"dills" at
at the
the
end of str3[ ], which has been initialised to "Daffo". After
end of str3[ ], which has been initialised to "Daffo". After
concatenation
concatenation strcat()
strcat( ) returns
returns the
the base
base address
address of of the
the target
target
string, str3. Once
string, ·str3. Once copying
copying and
and concatenation
concatenation is is over,
over, the
the string
string
comparison
comparison is is carried
carried out
out using
using the
the function
function strcmp(
strcmp( ). ). This
This
function
function hashas the
the arguments
arguments as as shown
shown below.
below.

I = strcmp (str3, "Daffodills");;


(str3, "Daffodills")

Since
Since str3[
str3[] ] does
does contain
contain "Daffodills"
"Daffodills" now,
now, the
the result
result of
of the
the
comparison
comparison is is aa 0,
0, which
which is
is assigned
assigned to
to 1. On printing
I. On printing out,
out, we
we
get
get the
the output
output 1 =
I = O.0.

(21)
(21) Output
Output

24
24

Explanation
Explanation

The
The sizeof()
sizeof( ) operator
operator gives
gives the
the size
size of
of its
its argument.
argument. As arr[arr[ ]]
is
is an
an integer
integer array of 12
array of 12 elements,
elements, saying
saying sizeof
sizeof (arr
( arr )) gives
gives
us
us the
the size
size of
of this
this array.
array. Each
Each integer is 22 bytes
integer is bytes long,
long, hence
hence the
the
array
array arr[
arr[ ]] engages
engages twice
twice the
the number
number of of elements,
elements, i.e. 24
i.e. 24
bytes.
bytes.

(22) Output
(22) Output
368
368 Exploring C
Exploring C

882
2

Explanation
Explanation

mess[ ]] has
mess[ has been
been declared
declared as as an
an array
array ofof pointers
pointers to strings.
to strings.
This signifies
This signifies that the array
thatthe mess[] stores
array mess[] stores the
the starting addresses
starting addresses
of
of the
the four strings initialised
four strings initialised inin the
the program.
program. mess[0]
mess[O] has the
has the
starting address of the string "Some love one",
starting address of the string "Some love one", mess[1] the mess[l] the
starting
starting address of the
address of the second
second string
string "Some
"Some love
love two"
two" and
and so
so
on. As each
on. As each address
address is is 22 bytes
bytes long,
long, four
four base
base addresses
addresses need
need
88 bytes,
bytes, hence
hence the
the array
array mess[]
mess[ ] is
is 88 bytes
bytes long.
long.

The sizeof(
The sizeof( )) operator
operator gives
gives the
the size
size of
of the
the datatype
datatype that
that is
is
supplied as its argument. Therefore,
Therefore. sizeof (mess
( mess)) is reported
as 8.
as 8.

messfl], the
mess[l], the first
first element
element of
of the
the array
array of
of pointers
pointers stores an
stores an
address, which
address, which is is invariably
invariably 22 bytes
bytes long.
long. Therefore printf())
Therefore printf(
reports sizeof
reports sizeof (mess[l]
( mess[1] )) as 2.
as 2.

(23) Output
(23) Output

ENTER NAME:
ENTER Parag
NAME: Parag
You entered Parag
ENTER NAME:
ENTER Veenu
NAME: Veenu
You entered Veenu
Veenu
ENTER
ENTER NAME: Jaina
NAME: Jaina
You entered Jaina
entered Jaina

Explanation
Explanation

names [5]
names [5] [20]
[20] has been declared as a two-dimensional array of
characters. We
characters. can think
We can think of
of it
it as
as an
an array
array of
of 55 elements, each
elements, each
element itself being
element itself being an
an array
array of
of 20 characters.
20 characters.
Pulling the Strings
Pulling the Strings 369
369

Let the base address of the 2-D array, i.e. names


names be 4001.
4001. In
the scanf(
scanf()) and printf(
printf()) statements,
statements, names[i]
names[i] refers to the
address of the jdii* string in the array. names[O]
names[0] refers to the
zeroth element of the 2-D array, or the base address of the string
of characters
characters starting
starting from 4001. names
names[1][1] denotes
denotes the address
address
of the first element of the 2-D array, which is 20 bytes ahead,
i.e. 4021,
4021, and
and so
so on.
on.

Assured names [i] stands for the base address of the jth
Assured that names[i] i th

string,
string, we proceed to
we proceed see what
to see what actually is going
actually is going on
on in this
in this
program.
program.

The first
The first time
time through
through the for loop,
the for loop, when
when you
you are prompted
are prompted
"ENTER
"ENTER NAME:",
NAME:", say say youyou entered
entered 'Parag'.
'Parag'. The
The scanf(
scanf( ))
accepts
accepts thisthis name
name and
and stores
stores itit at
at the
the address
address given
given by by
names[0].
names [0]. The printf( )) immediately
The printf( immediately reads
reads from
from the
the same
same
address
address namename[0],
[0], and prints the
and prints name starting
the name starting at
at this
this address
address
on
on to the screen.
to the screen. This
This is
is repeated
repeated by by incrementing
incrementing thethe value
value of
of
ji each
each time
time through
through the
the loop.
loop. When
When ji is
is incremented
incremented for for the
the
third
third time,
time, the
the process
process is terminated.
is terminated.

(24) Output
(24) Output

message: Lvalue required in function main


Error message:

Explanation
Explanation

Apparently,
Apparently, what the program attempts to do is interchange the
addresses
addresses stored
stored in
in names[3]
names[3] andand names[4]
names[4] usingusing an auxiliary
an auxiliary
variable
variable t. Sounds straight
t. Sounds straight forward,
forward, but
but is is essentially against
essentially against
the very concept
the very concept of how the
of how the C
C compiler
compiler deals
deals with
with strings.
strings. The
The
compiler
compiler keeps track of
keeps track any string
of any string by
by remembering
remembering only only the
the
base
base address of the string. So it has its reservations when itit
address of the string. So it has its reservations when
comes to changing
comes to changing this
this information,
information, as as it
it anticipates
anticipates that
that there
there
would
would be no one
be no one to
to' blame
blame but
but itself
itself once
once thisthis information
information is is
waylaid and we
waylaid and we demand
demand an an access
access toto the
the string
string later.
later. And
And this
this

l
370
370 Exploring C
Exploring C

is what
is what isis being
being attempted
attempted in in the
the statement
statement names[3]
names[3] = =
names
names[4].[4]. Here
Here we
we are
are trying
trying toto change
change the
the base
base address stored
address stored
in names[3].
in names[3]. As As said
said earlier,'
earlier, this
this will
will not
not be
be allowed.
allowed. Thus
Thus the
the
starting address of a string is an indelible entity, in no way an
starting address of a string is an indelible entity, in no wayan
lvalue, which
Ivalue, which isis aa value
value that
that cancan change.
change. Hence
Hence the error
the error
message.
message.

(25) Output
(25) Output

kk
kk

Explanation
Explanation

The two-dimensional
The two-dimensional arrayarray comprises
comprises of
of one-dimensional
one-dimensional ar-
ar-
rays, each
rays, each of
of which
which is
is 30
30 characters
characters long.
long. We
We know, mess [2][9]
know, mess [2] [9]
refers to
refers to the
the 99th element
element of
th
of the
the 2nd
2 1-0
1-D array.
array.
n d

Recall that
Recall that mess[2]
mess [2] would
would give
give the
the base
base address
address of of the
the second
second
string. If
string. If this
this address
address turns
turns out
out to
to be
be 4001,
4001, then
then the expression
the expression
mess [2] + 99 would
_}ness[2] would become
become (( 4001
4001 + 9 9),), which
which would
would give the
give the
address of
address of the
the ninth
ninth character
character fromfrom thethe address
address 4001.4001. ThisThis
address happens
address happens to to be the address
be the address of of the
the letter
letter 'k'
'k' inin the string
the string
"Don't walk
"Don't walk behind
behind me".
me". Hepce
Hence thisthis letter
letter 'k'
'k' can
can be accessed
be accessed
by the
by the expression
expression *( mess[2] +
*( mess[2] +9). But we
9 ). But we already
already know know that
that
whenever we use the notation mess[2], it
whenever we use the notation mess[2], it is internally con- is internally con-
verted to
verted to *(
*( mess
mess + + 22 )) by
by the
the compiler.
compiler. Therefore
Therefore *( *( mess[2]
mess[2]
+ 99 )) can
+ can also
also bebe expressed
expressed as as *(
*( *(*( mess
mess + + 22 )) ++ 99 ))..

Thus, mess[2][9],
Th:Js, *( mess[2]
mess[2][9], *( mess[2] + 9 )) and
and *(
*( *(
*( mess + 2 )) + 99 )
are one
are one and the same,
and the same, i.e. the 99th clement
i.e. the element of
lh
of the
the 2nd
2 string
string inn d

the array.
the array. The same array
The same array clement
element can
can thus
thus be
be accessed
accessed in
in any
any
of these
of these three
three ways.
ways. The printf()) on
The printf( on execution
execution outputs
outputs the
the
letter 'k'
letter twice. '
'k' twice.
Pulling
Pulling the
the Strings
Strings 371
371

(26) Output
(26) Output

A voice
A voice in
in your mailbox
your mailbox
A foot
foot in
in your tooth
your tooth

Explanation
Explanation

The array
The array mess[
mess[ ][ ][ ][
][ ]] is
is aa three-dimensional
three-dimensional array.
array. Taken
Taken
apart, we
apart, we can
can think
think of
of it
it as
as an
an array
array of two 22-D
of two - D arrays.
arrays. Each
Each of
of
these two
these 2 - D arrays
two 2-D arrays is is itself
itself comprised
comprised of of two 1-D arrays.
two 1-0 arrays.
Lastly, these
Lastly, 1-D
these 1:.. arrays are
0 arrays are each 2 0 elements
each 20 elements long.
long.

mess[0]
mess [1] refers
[0] [1] refers to
to the
the first
first element
element of of zeroth 2 - D array.
zeroth 2-D array. This
This
element happens
element happens to be the
to be base address
the base address of of the
the string
string "A voice
"A voice
... ". Since
Since mess[0][l]
mess [0] [1] is is an address, the
an address, printf()) prints
the printf( prints out the
out the
string starting
string starting here.
here. Similarly,
Similarly, mess[l][0]
mess[1][O] refers
refers toto the zeroth
the zeroth
element of
element the first
of the 2 - D array.
first 2-D array. This
This element
element is is the
the base
base address
address
of the
of string "A
the string "A foot
f o o ...
t H". eHence
n c e this
this string
string is
is outputted
outputted next.
next.

Solutions to
Solutions [B]
to [B)

(1)
(1) Program
Program

main())
main(
{{
static
static char str1 [[]] == "somewhere
char strl "somewhere over
over the
the rainbow"
rainbow";;
static char str2[] = ·over"
static char str2[ ] = "over"; ;

printf ("String
printf ( "String found
found at %d", xstrstr (str1,
%d", xstrstr (strl, str2)
s t r 2 ))) ;
}}

xstrstr (( st,
xstrstr s 1 , s2
s2)
char*s1,*s2;
char *s1, *s2 ;
{{
int i, a, Ien1, Ien2;;
len1, len2
372
372 Exploring C
Exploring C

len1 =
Ien1 = strlen
strlen (s1
( s 1 )) ;;
Ien2
len2 = strlen
strlen (( s2)
s 2 ) ;;

for ( ii = 0 ;; i <= ((Ien1


len1 - 1 ) ;; iff
i++))
{{
=
a = strncmp
strncmp ( ((s1 s 1 + i),
i), s2, len2)
Ien2);;

ifif (a ==
( a == 0)
0)
return (( ii + 11 )) ;;
return
}}
return (0);
return (0)
}}

Sample run
Sample run

String found
String found at 11
11

Explanation
Explanation

The two
The two strings
strings have
have been
been declared
declared as as strl[ and str2[
strl[] ] and str2[] ] in
in
main( ),
main( ), from
from where
where the the base
base addresses
addresses areare sent
sent toto the function
the function
xstrstr()) for
xstrstr( for searching
searching the second string
the second string inin the
the first
first one.
one. In
In
xstrstr(),
x$trstr( lenl and
), len1 Ien2 store
and lenZ store the
the lengths
lengths of the 22 strings
of the with
strings with
base addresses
base addresses sl si and
and s2 s2 respectively.
respectively. In In the
the for
for loop,
loop, ii is
is
incremented lenl
incremented lenl number
number of of times.
times. As As many
many times,
times, thethe stand-
stand-
ard library function
ardlibrary function strncmp
stmcmp (t, (t, s,
s, n)
n) gets
gets called.
called. This function
This-function
compares the
compares first n
the first n elements
elements of of strings
strings starting
starting from
from tt and
and ss
and returns 0 if
and returns if they
they are equal.
are equal.

The first
The first time
time through
through the
the for
for loop,
loop, ii is 0. Hence
is O. Hence stmcmp(
strncmp( ))
compares the
compares the first Ien2 (( here
first Jen2 len2 is
here len2 is equal
equal to to 44 )) elements
elements of of
strings starting
strings from (( ssli + 00 )) (( i.e.
starting from i.e. sl
si )) and
and s2.s2. aa collects
collects aa
non-zero value,
non-zero value, asas the first four
the first four elements
elements of of the
the two
two strings are
strings are
found to be different. The control therefore reverts
found to be different. The control therefore reverts back to the back to the
for where
for where iiisis incremented
incremented to 1 . So
to 1. So the
the second
second timetime through
through thethe
Pulling
Pulling the
the Strings
Strings 373
373

loop
loop strncmp(
strncmp( )) compares
compares first
first len2
len2 elements
elements of
of strings
strings start-
start-
ing
ing from
from sisl ++11 and
and s2.
s2.Literally, first 44 elements
Literally, first elements of
of""omewhere
omewhere
over
over the
the rainbow"
rainbow" andand "over"
"over" are are compared.
compared. Once
Once again
again aa
collects
collects aa non-zero
non-zero value
value and
and iiis
is incremented
incremented aa second
second time.
time.

This
This goes
goes onon similarly
similarly till
till ii is
is 10, when si
10,when s1 ++-1010 denotes
denotes the the
base
base address
address ofof the
the string
string "over
"over the
the rainbow".
rainbow". This This time
time aa is is
assigned
assigned aa 0,
0, as
as both
both the
the strings
strings have
have o,
0, v,
v, e,
e, and
and rr as
as the
the first
first
four
four elements,
elements, andand control
control returns
returns to
to main()
main() withwith ii ++11,, i.e.
i.e, 11.
11.
This
This is
is the
the position
position ofof the
the second
second string
string in
in the
the first
first one.
one.

Suppose
Suppose thethe second
second string
string is
is not
not present
present inin the
the first
first string
string at
at all,
all,
then
then at
at no
no time
time aa would
would contain
contain 0.o. Thus
Thus thethe return
return statement
statement
within
within the
the for
for loop
loop would
would never
never get
get executed.
executed. In In such
such cases
cases the
the
return
return statement
statement after
after the
the loop
loop would return 0,
would return 0, signifying
signifying that
that
the
the second
second string
string was
was not
not found
found inin the
the first
first one.
one.

(2)
(2) Program
Program

main()
main()
{{
static unsigned
static unsigned char
char s1
s1[][ ] ;=""Man's
"Man'sreach
reachmust
mustalways
always\ \
exceed his grasp.... or what is the heaven for?"
exceed his grasp.... or what is the heaven for?"; ;

unsigned char s2[80], s3[80];


s3[80] ;

printf ("%s", s 1 )) ;
( "%s·, st

codestr(s1, s2);
codestr (st, s2)
printf \n%s",s2);
printl ( "\n%s",
B
s2) ;

decodestr (s2, s 3)) ;


( s2, s3
printf (("\n%s",s3);
"\n%s·, s3) ;
}}

l codestr (s,
( s, t)t)
374
374 Exploring
Exploring C
C

unsigned char *s,


*s, *t*t ;;
{{
while (*s)
while (*s)
{
t
*t = *s + 127 ;
*t = * s + 1 2 7 ;
t++ ;
t++;
s++;
Sft ;
}}
*t
*t = 0;
0;
}}

decodestr (s, t)
( s, t)
unsigned char *s, *t
*t;
{{
while (*s)
while (*s)
{
{
=
*t *s -127;
*t = * s - 1 2 7 ;
t++
t++;
;
sSft
+ + ;;
}
*U0;
}

Sample
Sample run

Man's reach must always exceed his grasp.... or what is the heaven
for?

characters ]
[ graphic characters]

Man's reach must always exceed his grasp.... or what is the heaven
for?
Pulling the Strings
Pulling the Strings 375
375

Explanation
Explanation

The program
The program uses
uses two
two functions;
functions; codestr(
codestr()) for coding the
for coding the
string into
string into an
an illegible
illegible form,
form, and
and decodestr()
decodestr() for
for retrieving
retrieving the
the
original string.
original string.

In both
In both functions,
functions, the
the while
while loop
loop tests
tests for
for the
the end
end of
of the source
the source
string. In
string. In codestr(),
codestr(), each
each character
character ofof the
the source
source string
string is
is given
given
an offset
an of 127,
offset of 127, and
and then
then stored
stored in
in the
the target
target string.
string. If you
you refer
refer
to the
to the ascii
ascii chart
chart in
in the
the appendix,
appendix, you'll
you'll find that values
find that values 127
127
onwards correspond
onwards correspond to to graphic
graphic characters.
characters. By By adding
adding 127127 to
to
any character,
any character, we
we transform
transform the
the same
same intointo some
some graphic sym-
graphic sym-
bol . In
bol. In this
this manner,
manner, thethe whole
whole string
string isis transformed
transformed intointo aagroup
group
of graphic
of graphic characters,
characters, which
which you'll
you'II appreciate
appreciate would certainly
would certainly
be unreadable!
be unreadable!

In decodestr(
In decodestr( ), ), just
just the
the reverse
reverse is
is done.
done. From
From the
the contents
contents of
of
source string,
source string, 127
127 is subtracted and
is subtracted and then
then the
the resultant
resultant character,
character,
which is
which is invariably
invariably whatwhat the
the original
original one
one was,
was, is
is stored
stored in
in the
the
target string.
target string.

On printing
On printing out s l [ ] and
out s1[] s3[ ], we
and s3[], we get
get our
our familiar
familiar message,
message,
while s2[
while s2[ ]] prints
prints out
out nonsensical characters.
nonsensical characters.

(3)
(3) Program
Program

main()
main( )
{{
static *str[ 1 == {{
static char *str[]
"A FRiend is ...'',
"AFRiendiS...",
"SomEOne Loving
"SomEOne Loving & trUE.".",
&trUE...",
insTance somEONE
"fOr insTance ....",
somEONE....",
"exactlYHkEyoU!!"
"exactlY HkEyoU ""
};
};

printf ("No.
printf capitals = %d", capcount
( "No. of capnals capcount (s,
(s, 4)
4 )) ;
376
376 Exploring
Exploring C
C

}}

capcount (s, c)) .


( 5, C
char ***5;
*s;
int c :
intc;
{{
int i,i, cap == 0 ;;
char
char*t*t;;

for (i
( i = 00;; ii <.(c;
C ; i++)
itt )
{{
t == **(( s5 + i)
i ) ;;

while (*t)(*t)
{
{
iiff (( **tt >>=
= 665
5 &&&
& **tt <<=
= 90
90))
cap tt;
cap + + ;

ttt ;
t++;
}
}}
return ( ccap
a p ) ;;
}

Sample
Sample run

of
cap~al5 == 19
No. of capitals

Explanation
Explanation

The
The string
string str[
str[]] is
is an
an array
array ofof pointers.
pointers. This
This means
means it it stores
stores the
the
base
base addresses
addresses of the four
ofthe four strings
strings initialised
initialised in
in the declaration.
the declaration.
str[0]
str[O] has
has the
the starting
starting address
address of of "A
"A FRiend
FRiend iS...",
is ... '', str[l]
str[1] that
that
of
of "SomEOne
"SomEOne LovingLoving & & trUE...",
trUE ... ", and
and so
so on.
on. The
The base address
base address
of
of this
this array
array of
of pointers
pointers and
and thethe number
number of of strings
strings are passed
are passed
Pulling the
Pulling Strings
the Strings 377
377.

to the function capcount(),


capcount(), which we have written for count-
ing the number
number of capital letters in the four strings.

In capcount(
In capcount( ),), these
these are
are collected
collected in
in ssand
and c.c. Essentially,
Essentially, ss
contains the address
contains the of the
address of the location
location where
where str[O]
str[0] is
is stored.
stored. But
But
str[O) contains
str[0] contains the
the base
base address
address of
of the first string.
the first string. Hence
Hence ss is
is
declared as aa pointer
declared as pointer to
to aa pointer.
pointer.

In the
In the for
for loop
loop ii varies
varies from
from 00 toto 3,
3, each
each time
time assigning
assigning the
the
base address
address of the ithi string to t.
th
t. Once the base address of the
string is stored
string is stored in
in t,
t, the
the while
while loop
loop scans
scans the
the entire
entire string
string for
for aa
capital
capital letter until t reaches 'the end of string. Each time the
letter until t reaches the end of string. Each time the
condition evaluates to
condition evaluates to true
true the
the variable
variable cap,
cap, which
which counts
counts the
the
number
number of of capital
capital letters,
letters, isis mcremented.
incremented. Subsequently,
Subsequently, the the ++
++
operator
operator increments
increments t, t, so
so that
that it
it points
points to
to the
the next
next character
character in
in
the string.
the string.

When the for loop terminates the value of cap, cap, which is
nothing but
nothing but the
the number
number ofof capital
capital letters
letters in
in the
the strings, is
strings, is
returned. The
returned. The same
same is then printed
is then printed out
out in
in main(
main().).

(4) Program
Program

main())
main(
{{
static char *s[]
static *s[] == {{
"MalayalaM"
"MalayalaM",,
"to really mess things
things up...",
"one needs to know CH",
C !I",
"able was I ere I saw elba"
};
};
char
char rev[30]
rev[30];;
int
int i,i, a;
a;

for ( ii == 0 ;; i <=
<= 33 ; itti++))
{{
378
378 Exploring C
Exploring

slrcpy (rev,
strCJ7j( s[i]);
rev, s[ij );
strrev(rev);
strrev ( rev) ;
=
a = strcmp
strcmp ((s[i], rev);
s[ij, rev)

==
ifif (a
( a == 0)0)
printf (("%s\n",s[i));
"%s\n", s[ij ) ;
}}
}
}
Sample run
Sample run
MalayalaM
MalayalaM
able was I ere I saw elba

able was I ere I saw elba


Explanation

Explanation
A string is said to be a 'palindrome' if on reversing it you again
end up with
Astring thetooriginal
is said string. For ifinstance,
be a 'palindrome' 'MalayalaM'
on reversing on
it you again
reversing
end up withgives
the 'MalayalaM' itself.
original string. For instance, 'MalayalaM' on
reversing gives 'MalayalaM' itself.
Our program makes
Our program makes use
use of
of the
the following
following standard
standard library
library string
string
functions:
functions:
If ssand
and t are the base addresses
addresses of source and target strings
respectively, then the functions work as follows:
respectively, follows:

strcpy ( tt,, s ): Copies


Copies the
the source
source string
string into
into the
the target string.
target string.

strrev (( Ss ):): Reverses


strrev Reverses the
the source
source string.
string.

strcmp ( tt,, ss ):
): Compares
Compares the
the two
two strings
strings and
and returns
returns 00 if they
if they
are equal, and
are equal, and aa non-zer-ovalue
non-zero value if
if unequal.
unequal.

Since there
Since there are
are four
four strings
strings to
to be
be dealt
dealt with
with in
in the
the array
array of
of
pointers s[ ],
pointers s[ we set
1, we set up
up aa for
for loop
loop with
with itaking
i taking values
values from
from 00
Pulling
Pulling the
the Strings
Strings 379

to 3.
3. The first
first time, s[0] provides the base address of
s[O]provides of the
the first
first
string, "MalayalaM",
"MalayalaM", and rev, rev, that
that of
of the target
target string. After
copying
copying "MalayalaM"
"MalayalaM" into into rev[ ], rev[ ]] isis reversed
reversed using
using
strrev().
strrev( ). Now
Now rev[ ]] contains
contains the
the reversed
reversed string
string while
while the
the
original
original string
string is is intact
intact at
at s[Q.
s[i]. We
We compare
compare thethe two
two strings
strings
making use of strcmp( ),), and and receive the returned value
value in
in the
the
variable a. a is assigned a value 00 ifif the string is indeedindeed aa
Palindrome.
Palindrome. If If so,
so, the
the corresponding
corresponding string
string is
is printed
printed out.
out.

(5) Program
Program

main()
main( )
{{
static unsigned
static unsigned char
char strl
str1 [] =
[] = "Imperial
~Imperial Palace.
Palace. Rome.
Rome.
Attention
Attention Julius
Julius Caesar. Dear Caesar,
Ga~ar, we have the clarifica-
non you requested.
tion requested. Details
Details to follow
follow by courier. Meanwhile
Meanwhile stay
clear of Brutus.";
Brutus." ;

unsigned
unsigned char str2[500],
str2[SOO], str3[500];
str3[SOO];

printf
printf ("%s\n", s t r l)) ;
( "%s\n", str1

compress
compress (str1,str2)
( strt, str2) ;
printf
printf (("%s\n",str2);
"%s\n", str2) ;

decompress
decompress (str2, str3);
( str2, str3 );
printf
printf (("%s",str3);
"%s", str3 ) ;
}}

compress
compress (s,( s, tt )
unsigned
unsigned char
char *s, *t ;
{{
int ~pcount
int spcount;;

while (*s)
while (*s)
{{
380
380 Exploring
Exploring C
C

iiff ((*s ==
* s = = "tI))
{{
spcount = 11 ;;
spcount =
Stt ;
s++;
while ( *s tI )
while ( * s = = " )
==
{
{
spcounttt ;
spcount++;
Stt ;
s++;
if ( spcount == 10)
if{ (spcount = = 1 0 )
{ =
*t 23;
*tt++= 2; 3 ;
t++;
spcount 0; =
} spcount = 0 ;
}. }
}-
if ( spcount )
if{ (spcount)
{ if ( spcount ==1)
{
if (spcount == 1)
*t = *s + 127;
{
Stt ;
*t = * s + 127;
elses++;
} *t = 13 + spcount ;
else
*t = 13 + spcount;
ttt ;
t++;
}
}
}
}
else
else
{
{ *t = *s;
*t
t++= *; s ;
t++;
Stt; -.
} s++; -
} }
}*t 0;
=
} *t = 0 ;
Pulling
Pulling the
the Strings
Strings 381
381

decompress
decompress (s,
( s, tt ))
unsigned
unsigned char *s, **tt ;;
{{
int i ;
inti;
while ((*s)
while *s)
{
{
if ( *s >= 127 )
if{ (*s >= 127)
{ *t-'"- ,
*t
t++= ;" ;
t++;
*t = *s -127;
*t = * s - 1 2 7 ;
t++ ;
t++;
}
}
else
else
{
{ if ( *s > 13 && *s < 24 )
{if ( * s > 1 3 & & * s < 2 4 )
{ for ( i = 0 ; i < ( *s - 13) ; iff )
{
for ( i = 0 ; i< ( * s - 1 3 ) ;i++)
*t-'"- ,
{ t++; .
*t = " ;
t++;
}
}
else
}
{
else *t = *s ;
{ t++ ;
} *t = * s ;
} t++;
s++ };
} }
*t = s++;
0;
}. }
*t = 0 ;
}
Explanation
Explanation
382
382 Exploring C
Exploring C

The logic used


The logic used for
for the
the compression
compression is
is like
like this:
this:

Each character
Each character isis copied into the
copied into the string
string str2[]
str2[ ] as
as it
it is,
is, pJlovided
provided
it
it is not aa blank
is not blank space.
space. IfIf aa single
single blank
blank occurs
occurs between
between twotwo
words,
words, then
then aa graphic
graphic character
character is is stored
stored inin str2[
str2[ ],], which
which is
is
derived
derived by adding 127
by adding 127 to to the
the ascii
ascii value
value of of the character
the character
immediately
imm ediately after
after the blank. Following
the blank. Following this,
this, the
the characters
characters are
are
again
again copied
copied asas they come, till
they come, till another blank comes
another blank comes across.
across. '"'
Thus, when str2[
Thus, when str2[] ] is sent for
is sent for decompression,
decompression, the presence of
the presence of
aa graphic
graphic character
character indicates
indicates that
that the
the original
original string
string had
had aa
character
character having
having an an an
an ascii
ascii value
value which
which isis 127
127 less
less than that
than that
of
of the
the graphic character, and
graphic character, and that
that one
one blank
blank space preceded it.
space preceded it.

In case
In case of
of multiple
multiple blanks,
blanks, aa variable
variable spcount
spcount is is used
used to
to count
count
their number.
their numbe For instance,
r, For instance, if
if there
there are
are 88 blank spaces before
blank spaces before
'Rome', then spcount
'Rome', .then spcount gets
gets incremented
incremented 88 times
times through
through thethe
while loop. Again,
while loop. Again, nono spaces
spaces areare copied
copied into
into str2[].
str2[ ]. Instead
Instead aa
character corresponding
character corresponding to to ascii
ascii value spcount + 13
value spcount 13 is
is written
written
into str2[].
str2[]. In the ascii table, values from 14 to 23 are reserved
reserved
for special control characters.
characters. Thus,
Thus, for spcount
spcount equal to 8,
ascii 21 is written into str2[
str2[].]. Next, 'Rome'
'Rome' is copied as it is.
In decompress(
decompress(), ), when a control character having an ascii
value between 13 and 24 is encountered,
encountered, it signifies tha: tha- the
original string had multiple
multiple spaces in its place. The number of
spaces is calculated
calculated by subtracting
subtracting 13 fromfrom the ascii value of
the control character.
character.

Further, multiple
multiple spaces are kept track of in units of 10. This
is done by inserting
inserting ascii 10 + 13, i.e. 23 in str2[
str2[] ] whenever
whenever
spcount becomes
spcount becomes 10, and then
10, and then resetting
resetting it
it to
to O.0. What
What that
that
means
means is,is, if
if there
there are
are 14
14 spaces,
spaces, then
then two
two control
control characters
characters are
are
stored: one corresponding
stored: one corresponding to to the
the first
first 10
10 spaces,
spaces, i.e.
i.e. 23,
23, and
and the
the
second
second forfor the
the remaining
remaining 44 spaces,
spaces, having
having ascii
ascii value
value 44 ++113,3,
i.e.
i.e. 17. Finally, in
17. Finally, in case
case of
of just
just one
one space
space after
after aa unit
unit of
of 10,
10, it is
it is
treated with the
treated with the same
same logic
logic as
as for
for aa single
single isolated space.
isolated space.
10
Structures Unions
Structures and Unions
W
hile handling
handling real real world
world data,
da.ta, we
we usually
usually deal with aa collec-

W
hile dealwith collec-
tion
tion ofof integers,
integers, chars and and floats
floats rather
rather than
than isolated
isolated en-
en-
tities.
tities. For
For example,
example, an an entity
entity we
we call
call aa 'book'
'book' isis aa collection
collection
of
of things
things like
like aa title,
title, an
an author,
author, aa call
call no.,
no., aa publisher,
publisher, number
number of of pages,
pages,
date
date of
of publication,
publication, priceprice etc.
etc. As
As you
you cancan see,
see, all
all this
this data
data is
is dis-
dis-
similar;
similar; author
author is is aa string,
string, price
price is
is aa float,
float, whereas
whereas number
number of of pages
pages
is
is an
an int.
into For
For dealing
dealing with
with such
such collections,
collections, C C provides
provides aa datatype
datatype
called
called 'structure'.
'structure'. A A structure
structure gathers
gathers together
together different
different atoms
atoms of of
information
information that that form
form aa given
given entity.
entity.

Look
Look atat the
the following
following program
program that
that combines
combines dissimilar datatypes
dissimilar datatypes
into
into an
an entity
entity called
called structure.
structure.

main()
main( )
{
{
struct account
struct account
{
{
int no;
int no;
char ace _name[15J ;
char acc_name[15];
float bal ;
float bal;
}~
}r
struct account ~1, a2, a3 ;
struct account a1, a2, a 3 ;

printf
printf ("Enter
( "Enter acc
ace nos.,
nos., names,
names, and
and balances
balances \\n")
n");
scant ("%d
scant ("%d %s %f",
%f', &a1.no, a1.acc_name, &a1.bal);
a1.acc_name, &a1.bal);
Structures
Structures and
and Unions
Unions 385
385

scant ("%d
(n%d %s %f,
%f', &a2.no, a2.acc_name, &a2.bal)
&a2.bal);;
scant ("%d
(n%d %s %f,
%f', &a3.no, a3.acc_name, &a3.bal)
&a3.bal);;

printf-f n\n%d
pAntf-f "\n%d %s %f, a1 .no, a1.acc_name,
%f', a1.no, a1 .acc_name, a1.bal)
a1 .bal);
;
("\n%d %s %f',
printf (n\n%d %f, a2.no, a2.acc_name, a2.bal)
a2.bal);;
("\n%d %s %f',
printf ("\n%d %f, a3.no, a3.acc_name, a3.bal)
a3.bal);;
}

Now aa few
Now tips about
few tips about the program:
the program:

(a)
(a) The
The declaration
declaration at at the
the beginning
beginning of of the program combines
the program combines
dissimilar datatypes
dissimilar datatypes intointo aa single
single entity
entity called
called struct account.
struct account.
Here struct
Here struct is
is aa keyword,
keyword, account
account is is the
the structure
structure name,
name, and
and
the entities
the entities are
are structure
structure elements.
elements.
(b)
(b) al, a2
ai, a2 and
and a3 are
are structure
structure variables
variables of of the
the type
type struct
struct account.
account.
(c)
(c) The structure
The structure elements
elements are are accessed
accessed using
using aa '.''.' operator.
operator. So to
So to
refer no
refer no we use a1.no
we use al.no and and to to refer
refer to to acc_name
acc_name we we use
use
al.acc_name.
al.acc_name. Before Before the the dot there must
dot there must always
always be be aa structure
structure
variable and
variable and after the dot
after the dot there
there must
must always
always be be aa structure
structure
element.
element.
(d)
(d) Since al.acc_name
Since al.acc_name is is aa string,
string, its
its base
base address
address can can be
be obtained
obtained
just by
just by mentioning
mentioning al.acc_name.
al.acc_name. Hence Hence the 'address of'
the 'address of
operator &
operator & has
has been
been dropped
dropped while
while receiving
receiving the the account
account name
name
in scanC().
in scanf().
(e)
(e) The
The structure
structure elements
elements are are always
always arranged
arranged in contiguous
in contiguous
memory locations.
memory locations. This
This arrangement
arrangement is is shown
shown in in the following
the following
figure.
figure.

al.no
a1.no al.name
a1.name al.bal
a1.bal

.1 375
375 1 S a m ee ee rr \0
Sam \0 1234.55
11234.55 I|
4001
4001 4003
4003 4018
4018

Figure 10.1 Structure


Figure 10.1 Structure elements in memory
elements in memory
386
386 Exploring
Exglorin8 C
C

An Array
Array of Structures
Structures

In
In the
the above
above example
example if if we
we were
were toto store
store data
data of
of 100
100 accounts,
accounts, we
we
would
would be
be required
required to to use
use 100
100 different
different structure
structure variables
variables from
from aal
l to
to
alOO,
al00, which
which is is definitely
definitely notnot very
very convenient.
convenient. A A better
better approach
approach
would
would be
be to
to use
use an
an array
array ofof structures.
structures. The
The following
following program
program shows
shows
how
how to
to use
use an
an array
array of
of structures.
structures.

main()
main()
{{
struct employee
struct employee
{
{
int no;
int
floatno;
baJ ;
} ; float bal;
};
struct
struct employee a[10];
employee a[1 0] ;
int i;i;

for ( ii = 00 ;; i<=
i <= 99 ;; i++)
itt )
{{
printf ("Enter
printf ( "Enter account
account number
number and
and balance" );
balance");
scanf ( "%d %f", &a[i].no, &a[i].bal)
scanf ("%d %f", &a[i].no, &a[i].bal); ;
}}

for
for ( ii = 00 ;; ii <=
<= 99 ;; itt
i++))
printf
printf ("%d%f\n",
( "%d %1\n", a[0.no,
a[ij.no, a[i].bal);
a[ij.bal) ;
}}

The
The arrangement
arrangement ofof the
the array
array of
of structures
structures in
in memory
memory is
is shown
shown in
in the
the
following figure.
following figure, " :'
Structures and Unions
Structuresand Unions 387
387

a[0].no
a[O].no a[0].bal
a[O].bal a[l].no
a[1].no a[l].bal
a[1].bal a[9].no
a[9].no a[9].bal
a[9].bal

I 007
007 134
I 2000.55
134 I 4892.30
2000.55 122 I 6432.90
4892.30 1::::::::::::::::::::::::1122
I
~4000---4002---4006"'-"4008--_.J. 4054
6432.90
4056
I
|
4000 4002 4006 4008 4054 4056

Figure 10.2 Array


Figure 10.2 Array of
of structures
structures in
in memory
memory

Structures
More about Structures

Let us
Let us now
now explore
explore the
the intricacies
intricacies of
of structures
structures with
with aa view
view of
of
programming convenience.
programming convenience.

(a)
(a) The
The declaration
declaration of
of structure
structure type
type and the structure
and the structure variable
variable can
can
be combined in one statement. For example,
be combined in one statement. For example,

struct player
{{
char
char name[20]
name[20];;
int age;
int age;
}} ;;
struct player pt = { "Nick Yates", 3O} ;
struct player p1 = {"Nick Yates", 3 0 } ;
is same as ...
is same as...
struct
struct player
player
{
{
char name[20] ;
char name[20];
int age;
int age;
} p1 ={ "Nick Yates", 30} ;
}p1 = { "Nick Yates", 3 0 } ;

or even...
or even ...

struct
{{
388
388 Exploring C
Exploring C

name[20];;
char name[20]
age;
int age;
} p1 = { "Nick Yates", 30}
}p1 30};

(b)
(b) The values of
The values of aa structure
structure variable
variable can
can be
be assigned
assigned to another
to another
structure variable
structure variable of the same
of the same type
type using
using the
the assignment
assignment
operator. It
operator. It is not necessary
is not necessary to copy the
to copy the structure elements
structure elements
piece-meal. For
piece-meal. example,
For example,

struct player
{{
char
char name[20]
name[20];;
int age;
int age;
};
};
struct player p2, pt "Nick Yates", 30}
p1 = {{"Nick 30};
p2
P
=pt
2 = p1 ;

(c)
(c) One structure
One structure can
can be
be nested
nested within
within another
another structure
structure as shown
as shown
below.
below.

struct part
{{
char
char type
type;;
int qty;
intqty;
}} ;;
struct
struct vehicle
vehicle
{
{
char maruti[20] ;
char maruti[20];
struct part bo~ ;
struct part bolt;
};
};
struct vehicle v ;
struct vehicle v ;
v.bolt.qty = 300 ;
v.bolt.qty = 3 0 0 ;
(d)
(d) Like
Like an ordinary variable,
an ordinary variable, aa structure
structure variable
variable can
can also
also be
be
passed to
passed to aa function.
function. We
We may
may either
either pass
pass individual
individual structure
structure
elements or
elements or the entire structure
the entire structure at one go.
at one go. If need be
If need be we can
we can
Structures and Unions
Structuresand Unions 389
389

also
also pass
pass addresses
addresses ofof structure
structure elements
elements or
or address
address of
of aa
structure variable as shown below.
structure variable as shown below.

struct
struct player
player
{{
char nam[20];
char nam[20] ;
int age;
int age;
}
}; ;
struct
struct player p1 == {"Nick
player p1 { "Nick Yates",
Yates", 330}
0 } ;;

display
display (p1 .nam, p1
( p1.nam, .age);
p1.age ) ; !*
/* passing individual elements */
. show
show ((p1p 1 )); ; /*!* passing
passing structure variable */*/
structure variable
dd (pl.nam,
(p1.nam, &p1.age);
&p1.age) ; /*!* passing
passing addresses
addresses of of structure
structure elements
elements */*/
print
print ((&&p1
p 1 )); ; /*!* passing
passing address
address of
of structure
structure variable
variable */*/

(e)
(e) To
To access
access structure
structure elements
elements through
through aa structure
structure variable
variable we
we
use
use the
the '.'
'.' operator.
operator. Whereas
Whereas to to access
access structure
structure elements
elements
through
through aa pointer
pointer to
to aa structure
structure we
we use
use the
the' '->'
->' operator.
operator. This
This
is
is shown
shown below.
below.

struct book
book
{{
char name[25];
char name[25] ;
int callno;
int callno;
}}; ;
struct book b1 b1 == {"let
{"let us C", "C.Iyer",
"C.lyer", 101 };
101};
. struct book *b2*b2; ;
printf ("%s%d\n",
("%s %d\n", bl.name,
b1.name, b1.callno);
b1.callno) ;
b2 == &&b1
b 1 ;;
printf ("%s
( "%s %d",
%d", b2->name, b2->callno);
b2->callno) ;

Unions

Unions,
Unions, like
like structures,
structures, are
are derived
derived datatypes
datatypes which
which group together
group together
aa number
number ofof variables.
variables. However,
However, the
the way
way the
the two
two treat
treat these
these variables
variables

L
390
390 Exploring C
Exploring C

is totally different. While the elements


elements of a structure enable us to
access different locations
locations in memory,
memory, the elements of a union serve
as different names by which the same portion of memory can be
accessed. Consider the following program.
accessed. Consider program.

main())
main(
{{
union demo
union demo
{
{
int i;
inti;
char ch[2] ;
char ch[2];
}} ;;
union
union demo
demo aa ;;
a.i = 512;
a.i = 5 1 2 ;
printf "a.i == %d\n",
printf (("a.i %d\n", al)
a i ) ;;
"a.ch[O] == %d\n",
printf (("a.ch[0] %~n", a.ch[O])
a.ch[0]);;
printf (·a.ch[1] =
("a.ch[1] = %d",a.ch[1]);;
%d", a.ch[1])
}}

The output of this program would be:

a i = 512
a.i
=
a.ch[0] = 0
a.ch[O]
a.ch[1] =
a.ch[11,= 22

Note that the declaration


declaration of the datatype union and the union variable
variable
a is just
a is just like
like the
the way
way it
it is
is done
done for
for structures.
structures. So
So is
is the
the accessing
accessing of
of
the
the elements
elements of the union
of the union using
using dot
dot operators.
operators. But
But the
the analogy ends
analogy ends
here, as the
here, as following figure
the following figure illustrates.
illustrates.

r---
« a.i -----j•
••—a.ch{0]—H
l-a.ch{O]-t- a.ch[l] —
a.ch[l]-i

OOOOOOOO 00000010 |

Figure 10.3
Structures
Structures and
and Unions
Unions 391
391

Where a structure
structure would have employed a total of four bytes for a.i
a.ch[ ], the union engages only two bytes. The same two bytes
and a.ch[],
which comprise
comprise a.l
a.i also comprise the array a.ch[].
a.ch[ ]. Hence, we can
access
access the
the two
two bytes together by
bytes together by mentioning
mentioning a.i,
a.i, or
or individually
individually by
by
mentioning a.ch[0]
mentioning a.ch[O] and
and a.ch[l].
a.ch[1].

On assigning
assigning 512 to a.i, the binary equivalent of 512, i.e. 0000 0010
0000 0000
0000 0000 is
is what
what isis actually
actually stored
stored in
in the
the two
two bytes
bytes of
of the
the int.
into Of
Of
the 16 bit
the 16 bit number,
number, first the lower
first the lower 88 bits
bits are
are stored
stored in
in ch[O],and
ch[0], and next
next
the higher 88 bits
the higher bits are
are assigned
assigned to
to ch[l].
ch[l]. Taken
Taken bytewise,
bytewise, a.ch[O]
a.ch[0]
contains
contains decimal
decimal 0,
0, and a.ch[l] contains
and a.ch[l] contains decimal
decimal 2.2.

datatype
This data type proves very useful while interacting with the hardware
of the computer,
computer, which lies beyond the scope of this book.
392
392 Exploring
Exploring CC

Exercise
.Exercise

[A]
[A] What
What will
will be
be the
the output
output of
of the
the following
following programs:
programs:

(1)
(1) main()
main()
{{
struct employee
struct employee
{
{ char name[25] ;
char name[25];
int age;
int age;
float bs;
} float bs;
}struct employee e ;
struct
e.name employee e; ;
= 'Hacker"
e.name
e.age 25;== "Hacker" ;
e.age = 2 5 ;
printf ("%s %d", e.name, e.age) ;
printf ("%s %d", e.name, e.age);

(2)
(2) main()
main()
{
{
struct
struct
{
{
char name[25] ;
char name[25];
char language[10] ,
charlanguage[10].
} a;
}a;
static struct a = { "Hacker", ·C" } ;
staticstructa = {"Hacker","C"};
printf ("%5 %s', a.name, a.language) ;
printf ("%s %s", aname, alanguage);
}

(3)
(3) struct virus
{{
char signature[25];
char signature[25] ;
int size;
int size;
} v[2];
}v[2];
main( )
main()
Structures and Unions
Structuresand Unions 393
393

{{
staticstruct
static v[o]=={"Yankee
structv[0] { "YankeeDoodle", 1813} ;
Doodle", 1813};
struct v[1] = {
static struct v[1] = {"Dark Avenger", 1795}; ;
static "Dark Avenger·, 1795}
int i;i;
int

for ((i i==00; ;i i<=


for <= 11; ; i++)
i++ )
printf ( "%s %d\n", v[i).signature,v[ij.size)
printf ("%s %d\n", v[i].signature, v[i].size) ; ;
}}

((4)
4) struct ss
struct
{{
char cch;
char h;
int i;i;
int
float aa;;
float
}}; ;
main( )
main()
{
{
static struct s var = { 'O', 100, 12.55}
static struct s var = { ' C , 100,12.55}
f(var);
f(var);
9 (&var) ;
g(&var);
}
} .

ff(v)
(v)
struct ss vv;;
struct
{
{
printf ("%c
printf ( "%c %d
%d %f,
%f', v->ch, v-si, vv->a)
v-sch v->i, - > a ) ;;
}}

9g(v)
(v)
struct s *v;
\;
{{
%d %f,
printf ("%c %d %f', v.ch,
v.ch, v.i,
v.i, vv.a)
. a ) ;;
}}

(5)
(5) main(
main())
{
{
str1[][ ] = "Ransacked"
static char strl "Ransacked";;
394
394 Exploring
Exploring C
C

char str2[20];
str2[20] ;

struct word
, {{
str[20] ;
char str[20];
};
};•

static
stati? struct word s1
struc,tword st = {{"Ransacked"};
"Ransacked" } ;
struCfword s2 ;

strcpy (str2, s t r l ) ;;
( str2, str1
s2 == ss11 ;;

printf ("%s
( "%s %s\n", s1.str.s2.str);
s1.str, s2.str) ;
printf (("%s%s\n",str1,str2);
"%s %s\n", str1 , str2) ;
}

(6) ,in()
main()
{{
struct
{{
int num;
int num ;
float f;f;
float
char mess[50];
char mess[50] ;
, j m:

m.num = 1 ;;
m.t:= 314;
m.f 314;
strcpy (m.mess,
(m.mess, "Everything looks rosy");
rosy") ;

printf ("%d
( "%d %d %d\n", &m.num, &m.f, m.mess)
m.mess);:
printf ("%d
( "%d %f %s\n", m.num, m.f, m.mess);;
m.f, m.mess)
}}

(7) main()
main()
{
static struct emp
,f,
',",'I',,:,',~
Structures
Structures and
and Unions
Unions 395
395

{{
char name[20];
char name[20] ;
int age;
int age;
struct address
struct address
{{
char city[20]
char city[20] ; ;
long int pin;
long int pin;
}
}a; a;
} e = {"abhijeet", 30, "nagpur", 440010} ;
} e = {"abhijeet", 30, "nagpur", 440010};
printf ( "%s %s·, e.name, e.acity ) ;
} printf ("%s %s", e.name, e.acity);
}
(8)
(8)
main()
main()
{
{
struct a
struct
{ a
{ char arr[1 0] ;
chararr[10];
int i;
int
floati; b;
} v[2] ; b;
float
}v[2];
/*1*assume
assume that
that first
first structure
structure begins
begins atat address
address 1004
1004 */*/
printf
printf ("%d
( "%d %d
%d %d\n",
%d\n", v[0].arr,
v[O].arr, &v[0}.i,
&v[Oli, &v[0].b);
&v[O].b) ;
printf
printf ("%d
( "%d %d
%d %d\n",
%d\n", v[1].arc
v(1].arr; &v[1].i,
&v[1].i, &v[1].b);
&v[1].b) ;
}

(9)
(9) main()
main()
{{
struct a
struct a
{
{
char ch[7];
char ch[7] ;
char*str;
} ; char*str;
};

static
static strucU st == {"Nagpur",
structa s1 "Bombay"};;
{"Nagpur", "Bombay·}
. 396
396 Exploring
Explo'ring C
C

printf ("%c
( "%C %c\n",
%c\n", s1 .ch[0], *s1.str)
s1.ch[O), *s1 .str);;
printf ("%s%s\n",
( "%S %s\n", sl.ch,
s1.ch, sl.str);
s1.str) ;
}}

(10)
(10) main()
main()
{
{
struct a
struct a
{
{
char ch[7] ;
char ch[7];
char *str; .
} ; char *str;
};
struct
struct b
{{
char*-c ;
char*-c;
struct aa sss1
struct s 1 ;;
}} ;;

static
static struct
struct b s2 = {"Raipur",
{"Raipur", "Kanpur",
"Kanpur", "Jaipur"};
"Jaipur" } ;

printf
printf ("%s
( "%S %s\n",
%s\n", s2.c,
s2.c, s2.ss1 .str);;
s2.ss1.str)
printf
printf ("%s
("%S %s\n",
%s\n", ++s2.c, ++s2.ss1.str);;
tts2.c, tts2.ss1.str)
}

(11) main()
main()
{{
struct s1
struct s1
{
{
char*z;
char*z;
int i ;
inti;
struct st *p ;
struct s1 * p ;
}};; ..'.
static struct st
static struct s1 a[]a[ 1 == {{
{"Nagpur", 1,
{"Nagpur", 1 ,at
a + 11},
},
{{"Raipur",
"Raipur", 2,
2, aat+ 2},
2},
{ "Kanpur·, 3,
{"Kanpur", 3, a}
a}
}} ;;
Structures and Unions
Structures and Unions 397
397

struct s1 *ptr
struct *ptr = aa ;
printf ("%s
printf ( "%s %s
%s %s\n", a[0].z, ptr-sz,
%s\n", a{O].z, ptr->z, a[2].p->z)
a[2].p->z);;
}}

((12)
12) main()
main()
{{
struct
struct s1
s1
{
{
char*str;
char*str;
int i;
int i;
struct s 1 *ptr ;
struct s1 *ptr;
};
};
static struct s1 a[ 1 = {
static struct s1 a[] = {
{ "Nagpur", 1, a + 1 },
{"Nagpur", 1 , a + 1 } ,
{ "Raipur", 2, a + 2},
{"Raipur",2,a + 2},
{ "Kanpur", 3, a}
{"Kanpur",3,a}
}} ;;
struct
struct st
s1 *p
*p == aa ;;
int j
intj; ;

for ((jj =
= 00 ;; jj <=
<= 22 ;; j++
j++))
{{
, printf
printf (( "%d
" % d "" ,, ---afi].i
a ( j ] . i)) ;;
printf("%s\n",++a[j].str);
printf ( "%s\n" , ++aUJ.str) ;
}}
}

((13)
13) main()
main()
{{
struct
struct s1
s1
{
{
char*z;
char * z ;
int i ;
int i;
struct s 1 *p ;
struct s1 * p ;
};
};
static stru~t s1
static struct a[]] == {{
s1 a[
{{"Nagpur", 1 ,aa ++ 11}},,
"Nagpur", 1,
398
398 Exploring
Exploring CC

{"Raipur",
{ Raipur" ,2,
II 2, aa++ 2},
2},
{"Kanpur",
{"Kanpur", 3,3, aa}}
};};
struct
struct s1 *ptr == a ;;
s1 *ptr

printf
printf ("%s\n",
("%s\n·, ++(ptr->z);
H( ptr-sz ) ;
printf
printf ("%s\n",a[(
( "%s\n", a[( ++ptr
Hptr )->i].z).;
)->O.z) ;
printf
printf ("%s\n",
( "%s\n", aa [--(ptr->p->i
[--( ptr->p->i ))).z)
] . z ) ;;

(14)
(14) main()
main()
{
{
struct s1
struct s1
{
{
char'str;
char-*str;
struct s1 *ptr ;
struct s1 *ptr;
};
};
static struct s1 arr[] = {
static struct s1 arr[] = {
{ "Nikhil", arr- 1 } ,
{"Nikhil", arr+1},
H
{ "Aditya arr+2},
{"Aditya", arr+2},
,

{ "Sudheer", arr}
{"Sudheer",arr}
}}; ;

struct s1 *p[3];
*p[3] ;
inti;
int i;

for (ii = 0 ;; i <= 2 ;; iH


i++))
p[i]
p[i} = arr[i].ptr;
arr[ij. ptr ;

printf
printf ("%s\n",
( "%s\n", p[0]->str);
p[O]->str) ;
printf
printf {"%s\n", (*p)->str);;
( "%s\n", (*p)->str)
printf
printf ("%s\n", (**p));;
( "%s\n", (**p))
}

((15)
15) struct
struct s1
{{
char *str
char *str;;
Structures
Structures and
and Unions
Unions 399
399

structs1
struct s1*next;
*next ;
}}; ;
main( )
main()
{
{
static struct 51 arr[] ={
static struct s1 arr[] = {
{ "Akhil", arr+1 } ,
{"Akhil", arr+1},
{ "Nikhil", arr+2},
{"Nikhil", arr+2},
{ •Anant", arr}
{"Anant", arr}
};
};
struct s1
struct s1 *p[3];
*p[3] ;
inti;
int i;

for tt ii==00; ;ii<<=


for = 22; ; i++)
iff )
p[i] = arr[i].next;;
p[i) = arr[ij, next

printf ("%s
printf ( "%s %s
%s %s",
%s·, p[0]->str,
p[O]->str,*p->str, =p.str) ;
*p->str, **p.str);

swap (*p,
swap ( *p, aarr)
r r ) ;;

printf ("\n%s",
printf ( "\n%s", p[0]->str);
p[O]->str),;
printf ( "\n%s", (*p )->str) ;
printf ("\n%s",(*p)->str);
printf ( "\n%s·, (*p )->next->str) ;
printf ("\n%s",(*p)->next->str);

swap ( prO],p[O]->next)
swap(p[0], p[0]->next);;

printf (("\n%s",p[0]->str);
"\n%s", p{O}->str) ;
printf (("\n%s",(*++p[0]).str);
"\n%s", (*++p[O] ),str) ;
printf ("\n%s",
( "\n%s", ++(*++(
++( *++( *p )->next
)->next ).str);
),str) ;
}

swap ( p1, p2)


swap(p1,p2)
struct s1
struct 51 *p1,*p2;
*p1, *p2 ;
{
{
char *temp ;
char *temp;
temp = pt-sstr ;
temp = p1->str;
400
400 Exploring C
Exploring C

pt-sstr = pz-sstr
p1->str p2->str;;
p2->str = temp;
p2->str temp;
}}

(16)
(16) main()
main()
{{
struct
struct node
node
{
{
int data;
int data;
struct node
struct node *Iink
*link;;
};
};
struct node*p,*q-r
struct node *p, *4-~

pp = malloc
malloc ((sizeof
sizeof ((struct n o d e ))) ;;
struet node)
=
qq = malloe
malloc ((sizeof
sizeof ((struct n o d e )}} ;;
struet node)

printf (("%d
printf sizeof ( pp),) , sizeof
"%d %d", sizeof sizeof (q)
( q ) ) ;;
}}

.(17)
{17) #defineNULLO
#define NULL 0
main()
main( )
{{
struct node
struet node
. {{
int data;
data;
struct node *Iink
struct node *link;;
}} ;;
struct node *p, *q
struct node *q;

pp == malloe
malloc ((sizeof
sizeof ((struct n o d e ))) ;;
struet node)
qq == malloe
malloc (sizeof
(sizeof (struet
(struct node)
n o d e ))) ;;

p->data =
p-sdata = 30
3 0 ;;
p->Iink = q;
p->link q;
q->data
q-soata == 40
4 0 ;;
q->link
q-stnk = NULL;
NULL;
Structures-andrUnions
Structures-and-U. nions 401
401

printf
printf (("%d",p->data);
"%d ", p-sdata) ;
=
p = p->link;
p->link;
printf
printf ("("%d",p->data);
%d", p-sdata) ;

((18)
18) #defineNULLO
#define NULL 0
main()
main()
{{
struct node
struct node
{
{ struct node *previous ;
struct node *previous;
int data;
int data;
struct node *next ;
} struct node *next;
}
struct
struct node
node *p,
*p, **qq ;;

=
pp = malloc
malloc (sizeof
( sizeof (struct
( struet nnode)
o d e ) ) ;;
qq == malloc
malloe (sizeof
(sizeof (struct
(struet nnode)
o d e ) ) ;;

p-sdata == 7755 ;;
p->data
q->data
q-sdata == 9900 ;;

p->previous
p-sprevlous == NULL;
NULL;
p-snext == qq; ;
p->next
q->previous
q-sprevious == p; p;
q->next = NULL;
q-snext = NULL;

while
while ((pp! =!= NULL)
NULL)
{{
printf ("%d\n",
printf ( "%d\n", p->data);
p-scata) ;
pp == p->next;
p-snext ;
}}
}

( (19)
1 9 ) #defineNULL0
#define NULL 0
main()
main( )
402
402 Exploring
Exploring C
C

{{
struct
struct node
node
{
{
int data;
int data;
struct node *next
struct node *next ;;
};
};
struct node
struct node *p, *q
*q;

pp = malloc
malloc ((sizeof
sizeof ((struct n o d e ))) ;;
struct node)
qq = malloc
malloc ((sizeof
sizeof ((struct n o d e ))) ;;
struct node)

p->data = 10;
p->data 10;
q->data == 20
q-sdata 2 0 ;;
p-snext == q;
p->next q;
q->next == pp;;
q-snext

while (( pp!!=
while = NULL)
NULL)
{{
printf ( "%d\n", p-soata)
printf ("%d\n", p->data);;
pp == p-snext
p->next: :
}}
}

(20)
(20) main()
main()
{{
struct
struct aa
{
{
int i;
int i;
char ch(2];
char ch[2];
}} ;:
union b
union b
{
{
, int i ;
int i;
char c[2] ;
char c[2];
};
};
printf ( "%d " sizeof
printf ("%d", sizeof (struct
( struct a)
a ) )) ;;
printf
printf ("%d", sizeof (union b )) )) ;;
( "%d", sizeof ( union b
Structures and Unions
Structures and Unions 403
403

((21)
21) main()
main{)
{{
union aa
union
{
{
int i;
inti;
char ch[2];
char ch[2] ;
}} ;;
union au;
union a u;
u.i = 256;
u.i = 2("%d
printf 5 6 ; %d %d", u.i, u.ch[O),u.ch(1)) ;
} printf ("%d%d%d", u.i, u.ch[0I, uch[1]) ;
}
(22)
(22) main()
{
{
struct aa
struct
{
{
long int i;
long int i;
char ch[4];
char ch[4];
};
};
struct as;
struct a s ;
s.i = 512;
printf
s.i ( "%d %d %d", s.ch[O],s.ch[1], s,ch[3]) ;
= 512;
} printf ("%d %d %d", s.ch[0], s.ch[1], s.ch(3]);
}
(23)
(23) main()
main()
{
{
union a
union a
{
{ int i ;
inti;
char ch[2] ;
char ch[2];
};
};
union aau;u;
union
404
404 Exploring
Exploring CC

u.ch[0]
u.ch[O]= 33;;=
u.ch[1]
u.ch[1] == 22;;
printf
printf ("%d
( "%d %d%d %d",
%d", u.ch[0], u.ch[1], u.i);
u.ch[O],u.ch(1], u.i) ;
}

((24)
2 4 ) main()
{{
struct aa
struct
{
int
int i;
int j ;
intj;
};
/ i

struct
struct bb
{
charx;
char x;
chary[3];
chary[3] ;
J}; J
union
union cc
{
struct
struct aa aaa;
a;
struct b bb;
struct b bb;
};
union
union c u;
u;

u.aa.i = 512;
512;
u.aaj
u.aa.j = 512;
512 ;

printf ("%d
( n%d %d",
%d ", u.bb.x, u.bb.yfO]);;
u.bb.x, u.bb.y[O])
printf ("%d
( "%d %d", u.bb.y[1], u.bb.y[2]);;
u.bb.y[1], u.bb.y[2])
}

(25)
(25) main()
{{
struct a
{{
int ii;;
int
Structures and
Structures and Unions
Unions 405
405

intj;
int j;
}J ;
t

struct
struct b
{
charx;
char x ;
chary;
chary;
}
J ;»
union
union c
{
struct aa;
struct a aa;
struct
struct b bb;
bb;
};
union
unioncc u;u;

u.aa.i =
u.aa.i = 256;
256;
u.aaj
u.aa.j = 512
512;;

printf
printf ("%d
( "%d %
%dd "'., u.aa.i, u . a a j ) ;;
u.aai, u.aa.j)
printf ("%d
( "%d %d",
%d·, u.bb.x, u.bb.y);;
u.bb.x, u.bb.y)
}}

((26)
26) main()
main()
{
{
union
union
{
{
unsigned long I ;
unsigned long I;
unsigned int d[2] ;
unsigned int d[2];
char ch[4] ;
char ch[4];
} a;
}a;
strcpy
strcpy (a.ch,
( a.ch, "ABC");
"ABC" ) ;

printf ("%s\n", a c h ) ;;
( "%s\n", a.ch)
. printf ("%u %u\n", ad[0],
printf ( "%u %u\n", a.d[1]);;
a.d{O], a.d{1])
printf ("%lu", a l ) ;;
( "%Iu", a.l)
}}
406
406 Exploring C
Exploring C

Answers
Answers

Answers to [A]
Answers to [A]

(1)
(1) Output
Output

Error message: Lvalue


Error message: Lvalue required
required in
in function
function main
main

Explanation
Explanation

The error
The error message
message is is obtained
obtained forfor the
the simple
simple reason
reason that we
that we
tried to
tried assign aa value
to assign value to
to e.name.
e.name. By By mentioning
mentioning e.name
e.name we we
get the
get the base
base address
address of of the
the array
array name[
name[],], and
and question doesn't
question doesn't
arise of
arise of assigning
assigning anything
anything toto this
this base
base address,
address, as
as its
its aa constant
constant
value. Since
value. Since onon the
the left
left hand
hand side
side of =
of = aa variable
variable should occur
should occur
rather than
rather than aa constant,
constant, thethe compiler
compiler flashes
flashes anan error
error message
message
saying 'Lvalue
saying 'Lvalue required
required in in function main'. Incidentally,
function main'. Incidentally, an an
lvalue is
lvalue is something
something which
which cancan change,
change, or or in
in other
other words,
words, aa
variable.
variable.

(2)
(2) Output
Output

Error message: Declaratior.


Error message: Declaration syntax
syntax in
in function main
function main

Explanation
Explanation

Let us
Let us check
check the the type
type declaration
declaration first.
first. Here
Here wewe find the
find the
structure name
structure missing. This
name missing. This is
is perfectly
perfectly alright,
alright, as you may
as you may
recall that
recall that if
if we
we want
want toto skip
skip giving
giving the
the structure
structure aa name,
name, wewe
must declare
must declare the the variables
variables along
along with
with the
the type declaration.
type declaration.
Thus the
Thus the type
type declaration
declaration isis fine.
fine. Then
Then where
where lies
lies the error?
the error?
The error
The is that
error is that the
the struct
struct variable
variable aa is
is declared
declared twice;
twice; the
the first
first
time along
time along with
with the
the type
type declaration,
declaration, and then again
and then again in the
in the
initialisation statement.
initialisation statement.
Structures Unions
Structures and Unions 407
407

(3)
(3) Output
Output

Error message: Declaration


Error message: Declaration syntax
syntax in
in function main
function main

Explanation
Explanation

At the time of declaration


declaration of structure type, we declared v[2]
outside main(). v[2]
outside main(). v[2] is
is therefore
therefore allotted
allotted extern
extern storage
storage class.
class.
Once external
Once external storage
storage class
class is
is' associated
associated with
with v[2],
v[2], we can't
we can't
initialise it
initialise it using
using the
the keyword
keyword static,
static, which refers to
which refers to static
static
storage
storage class. The compiler
class. The compiler recognises
recognises thethe illegal
illegal declaration
declaration
and flashes the
and flashes the error
error message.
message.

(4)
(4) Output
Output

Error message:
Error message: Pointer
Pointer required
required on
on left of->
left of in function
-> in function ff
Error message: Variable
Error message: Variable required
required on
on left
left of.
of. in function gg
in function

Explanation
Explanation

The function f(),


f(), called from
from main(),
main(), is sent the struetvariable
struct variable
var, which is
var, which is collected
collected inin v.
v. The
The printfO
printf() inin f(
f ( )) attempts
attempts toto
print the structure
print the structure elements
elements using
using the
the arrow
arrow operator
operator with with v,
v,
wherein
wherein lies
lies the
the first error. On
first error. On the
the left
left of
of the
the arrow
arrow operator,
operator,
there must
there always be
must always be aa pointer
pointer to
to aa structure.
structure. On
On the
the other
other hand,
hand,
function g(
function g( )) collects
collects aa pointer
pointer to
to aa structure,
structure, which
which it it uses
uses in
in
conjunction with
conjunction with the
the dot
dot operator.
operator. The The dot
dot operator
operator must must
always
always bebe preceded
preceded by by aa structure
structure variable,
variable, never
never aa pointer.
pointer.
Hence
Hence the second error
the second error message.
message.

(5) Output
Output

Ransacked
Ransacked Ransacked
Ransacked
Ransacked Ransacked
408
408 Exploring C
Exploring C

Explanation
Explanation

The program clearly brings out how the treatment varies for a
string and aa structure.
string and structure. strl[
strl[ ]Iand
and sl.str
sl.str are
are both
both initialised to
initialised to
store "Ransacked".
store "Ransacked". For For copying
copying the the contents
contents ofof one
one string
string to
to
another, we
another, have to
we have to use
use the
the function
function strcpy(
strcpy( ).
). However,
However, the the
copying of
.copying of structure
structure elements
elements isis aa simple
simple affair: saying s2
affair: saying s2 = s1si
does the trick.
does the trick. For
For printing strings, only
printing strings, only the
the name
name of of the string
the string
needs
needs toto be
be mentioned,
mentioned, while
while for
for accessing the structure
accessing the structure ele-
ele-
ments the dot operator should be
ments the dot operator should be used. used.

(6)
(6) Output
Output

1401 14031407
140114031407
1 3.140000 Everything looks rosy
13.140000 Everything looks rosy
Explanation
Explanation
In the
In the elements
elements num and ff of
num and of the
the structure,
structure, 11 and
and 3.14
3.14 are
are
stored. For
stored. assigning contents
For assigning contents to to the
the third
third element
element of the
of the
structure, i.e. the
structure, i.e. array mess[
the array mess[ ], ], strcpy(
strcpyf ),), the string copy
the string copy
function
function isis used.
used. Why
Why use
use aa string
string function for this?
function for this? Could
Could we
we
not have said:
not have said:

m.mess = "Everything looks rosy"


rosy";;

like when
like when we we assigned
assigned values
values to
to num
num and
and f?
f? The
The answer
answer is an
is an
emphatic NO! Unlike m.num m.num and m.f,m.f, m.mess
m.mess signifies an
address, and a base address at that. Hence, it can't
can't ever occur
on the left hand side of the assignment
assignment operator. In other words,
words,
m.mess is not an lvalue.
m.mess is not an lvalue.

The
The first printf()) prints
first printf( prints the
the addresses
addresses of
of the
the three elements
three elements
within the
within the struct.
struct. The
The output
output goes
goes to
to show
show that
that the elements
the elements
of aa struct
of struct arestored
are stored in
in contiguous
contiguous memory
memory locations. Address
locations. Address
Structures
Structures and
and Unions
Unions 409
409

of of m.numis is
m.num foundto to
found bebe 1401.
1401. Sinceanan
Since intintoccupies
occupiestwo two bytes
bytes
in memory, address of the float, m.f, is 1403. Finally, thethe
in memory, address of the float, m.r, is 1403. Finally,
addressof of
address thethearray
arraymess[
mess[]] is is1407.
1407.This
Thisis is fourbytes
four bytesahead
ahead
of the address ofm.f as a float is a four-byte
of the address of m.f as a float is a four-byte entity. entity.

Thesecond
The second printf(
printf( ) )prints
printsout
outthethethree
threeelements
elements ofofthethe
structure.
structure.
(7) Output
(7) Output

abhijeet nagpur
abhijeet nagpur

Explanation
Explanation

Structures can
Structures canbebenested.
nested.That
Thatis,is,a astructure
structuremay maycomprise
comprise o of
f
otherstructures,
other structures, which
whichininturn
turnmay
maybebehosting
hostingother
otherstructures,
structures,
andsosoon.
and on.Here,
Here, the
thethird
third element
element ofofstruct struct emp
em}'isisstruct
struct
address a, which has two elements of its
address a, which has two elements of its own: a char string own: a char string
city[]] and
city[ anda along
long int
intpin.
pin. aahas
hasbeen
beendeclared
declared asasa avariable
variable o of
f
the type struct address, and e, of the type struct
the type struct address, and e, of the type struct emp. While emp. While
initialising e,e, care
initialising care must
.must bebe taken
taken toto provide
provide the the values
values inin
keeping with
keeping with thethe order
order inin which
which the the elements
elements have have been
been
declared in the structure,
declared in the structure.

Through the
Through the printf(),
printf( ), the name isis printed
the name printed out using e.name.
out using e.name,
Since the dot operator is used for accessing an element o of
Since the dot operator is used for accessing an element f aa
structure, it means to access an element of
structure, it means to access an element of a structure which a structure which
itself isis aa part
itself part of
of another
another structure,
structure, the
the dot
dot operator
operator should
should be be
used twice. Hence "nagpur", an element
used twice. Hence "nagpur", an element of variable a, whichof variable a, which
in turn
in turn isis an
an element
element of of variable
variable e,e, isis printed
printed using
using e.a.city.
e.a.city.

(8) Output
(8) Output

100410141016
100410141016
102010301032
102010301032
410
410 Exploring C
Exploring

Explanation
Explanation

v[ ]1 has
VI has been
been declared
declared asas an
an array
array of structures. Understand
ofstructures. that
Understand that
though
though eacheach structure
structure consists
consists of
of dissimilar
dissimilar datatypes, more
datatypes, more
than
than one
one similar
similar structures
structures are
are capable of forming
capable of forming an
an array.
array. The
The
word
word 'similar'
'similar' is important here,
is important here, as
as that
that is
is the
the only criterion
only criterion
Dennis
Dennis Ritchie
Ritchie set for constructing
set for constructing an array of
an array of any
any datatype.
datatype.

The output
The output verifies
verifies that
that elements
elements of of an
an array
array ofof structures, in
structures, in
keeping with the
keeping with the tradition
tradition ofof arrays,
arrays, are
are stored
stored inin contiguous
contiguous
memory locations. The
memory locations. The address
address of of the
the zeroth
zeroth element
element of of the
the
zeroth
zeroth structure
structure is
is 1004.
1004. As
As this
this is
is aa char
char array
array of
of size
size 10, ten
10, ten
bytes are used
bytes are used by
by it. Next, at
it. Next, at 1014,
1014, the
the int
int of
of the
the zeroth
zeroth structure
structure
is stored. After
is stored. leaving 22 bytes
After leaving bytes forfor v[0].i,
v[O].i, the float v(O].b
the Doat v[0].b
occupies bytes 1016 to 1019. Immediately after
occupies bytes 1016 to 1019. Immediately after this, thenext this, the next
structure of the
structure of the array
array is
is stored,
stored, as
as the
the outputted
outputted addresses
addresses 1020,
1020,
1030,
1030, and
and 1032, justify.
1032, justify.

(9)
(9) Output
Output

NBB
N
Nagpur Bombay
Nagpur Bombay
Explanation
Explanation
struct
struct aa comprises
comprises of of char
char array
array ch[]
ch[ ] and
and aa char
char pointer
pointer str.
str.
s1,
si, a variable of type struct a, is initialised next. Here "Nagpur"
a variable of type struct a, is initialised next. Here "Nagpur"
gets stored in
gets stored in the
the array
array ch[
eh]},], and
and "Bombay"
"Bombay" getsgets stored
stored starting
starting
from the address contained
from the address contained in str. in str.

In the first printf(


printf(), ch[0] signifies the zeroth element of the
), ch[O]
array ch[
ch[ ]. Since.this
Since. this array is within a struct,
struct, a dot operator,
operator,
preceded by the structure variable of that type must be used.
Thus, s1.ch[O]
sl.ch[0] refers to the zeroth element of the array ch[ ].
Structures and Unions
Structures Unions 411

As this
As this array
array has
has been assigned the
beenassigned string "Nagpur",
the string "Nagpur", the
the first
first
character ' N ' is printed out.
character 'N'

Next, *sl.str
Next, *sl.str signifies
signifies the
the value
value at
at address
address contained
contained in sl.str.
in sl.str.
Since this
Since this is
is the address at
the address at which
which 'B'
' B ' of
of "Bombay"
"Bombay" is stored,
is stored,
the printf()) prints
the prjntf( prints out
out aa 'B'.
'B\

The next printf(


prjntf( ))'outputs
outputs both "Nagpur" and "Bombay", as
sl.ch denotes the base-address
sl.t!h denotes base address of the former, and sl.str,
sl.str, that
of the latter string.
string.

(10) Output
(10) Output

Raipur Jaipur
Raipur Jaipur
aipuraipur
aipur aipur

Explanation
Explanation
,
At the
At the outset,
outset, struct
struct aa is
is declared
declared toto comprise
comprise of of aa character
character
array
array ch[
eh[]] and
and aa character
character pointer
pointer str.
str. Next,
Next, s2
s2 is declared as
is declared as
aa variable
variable of
of type
type straet
struct b,
b, which
which isis made
made up
up of
of aa ehar
char pointer
pointer
ce and
and another
another variable
variable ssl
ssl of
of type
type struct
struct a.a. While
While initialising
initialising
s2,
s2, the
the base
base address
address ofof the
the string
string "Raipur"
"Raipur" is is assigned
assigned to to s2.c,
s2.e,
"Kanpur" is assigned to s2.ssl.ch[ ], and the base
"Kanpur" is assigned to s2.ss1.eh[ ], and the base address of address of
"Jaipur"
"Jaipur" is
is assigned
assigned to to s2.ss1.str.
s2.ssl.str.

Coming to
Coming to the
the prjntf()s
printf( )s now.,the
now, the first
first one
one is
is supplied
supplied s2.e
s2.c and
and
s2.ssl.str. s2.c gives
s2.ssl.str. s2.e gives the
the base address of
base address of "Raipur",
"Raipur", andand
s2.ssl.str gives the
s2.ss1.str gives the base
base address
address of"
of "Jaipur". Since these
Jaipur". Since these base
base
addresses
addresses areare passed to prjntf(
passed to printf( ),'it
),it promptly prints out
promptly prints the {WIJ
out the two
strings.
.~~ .

The second printf()


printf( ) uses incremented values of these addres-
ses. On incrementing
ses. On incrementing s2.e
s2.c using
using the
the ++ operator,
operator, it
it now
now points
points
to the next
to the next element
element 'a'
'a' of "Raipur". Similarly,
of "Raipur". Similarly, on
on incrementing
incrementing
412
412 Exploring C
Exploring

s2.ss1.str,itit points to the 'a'


s2.ssl.str, 'a' of "Jaipur". With these as starting
starting
addresses, remaining strings are printed out.
addresses, the remaining

(11) Output
(11) Output

Nagpur Nagpur
Nagpur Nagpur Nagpur

Explanation
Explanation

The zeroth
The zeroth and first elements
and first elements of of struct
struct s1s i are
are aa character
character
pointer and an int int respectively.
respectively. The second element is what's what's
new. It is a pointer to a structure.
structure. That is, p stores the starting
starting
address
address ofof aa structure
structure variable
variable ofof the
the type
type struct
struct sl.
si. Next,
Next, a[],
a[ ],
an array of
an array of such
such structures
structures isis declared
declared as as well
well as initialised.
as initialised.
During initialisation the
During initialisation the base
base address
address ofof "Nagpur"
"Nagpur" is is stored in
stored in
a[O].z, 11 is
a[0].z, is stored
stored inin the element a[O].i,
the element a[0].i, and
and aa + 1 1 is
is assigned
assigned
to a[0].p. On
to a[O].p. On similar lines, the
similar lines, the remaining
remaining twotwo elements
elements of of the
the
array are
array are initialised.
initialised. a[l].z,
a[1].z, a[l].i
a[1].i and
and a[l].p
a[l].p are assigned
are assigned
"Raipur", 22 and
"Raipur", and aa + 22 in
in that
that order,
order, and
and "Kanpur",
"Kanpur", 33 andand aa are
are
stored at a[2].z,
stored at a[2].z, a[2].i
a[2].i and
and a[2].p
a[2].p respectively.
respectively.

What exactly
What exactly do
do a,
a, aa +
+ 11 and
and aa ++ 22 signify?
signify? a,
a, of
of course,
course, is the
is the
base address
base address ofof the
the array
array a[a[].]. Let us assume
Let us it to
assume it to be
be 4000,
4000, as
as
shown
shown inin Figure
Figure 10.4.
lOA. Locations
Locations 40004000 and
and 4001
4001 are occupied
are occupied
by the
by the char
char pointer
pointer a[0].z,
a[O].z, since
since aa pointeris
pointer is always
always two
two bytes
bytes
long. The next two bytes are used to store the integer a[O].i, a[0].i,
and then 4004 and 4005 are used by a[O].p. a[0].p. Similarly, the next
6 bytes
bytes store the first structure
structure a[l],.
a[l],. and the 6 bytes after that
that
contain a[2],
a[2], the second structure in the array.
Structures
Structures and Unions
and Unions 413
413

a[0].z a[0].i a[0].p


a[O].z a[O].i a[l].z a[l].i
a[O].p a[1].z a(1].i a[l].p
a[1].p a[2].z a[2].i a[2].p
a[2].z a[2].i a[2].p
AO I
I AO 1
1 40061
14006 1 AlAI I 22 1 1 A2
4012
14012 A2 1 33 4000
14000 JI

•4000
"4000 4002
4002 4004
4004 4006
4006 4008
4008 4010
4010 4012 4014
4012 4014 4016
4016

ptr
4000
I 1
Notes:s
Notes
-- ADAO denotes
denotes address
address from
from where
where "Nagpur"
"Nagpur"isisstored.
stored.
-- Al
A I denotes
denotes address
address from
from where
where "Raipur"
"Raipur" isisstored.
stored.
-- A2
A2 denotes
denotes address
address from
from where
where "Kanpur"
"Kanpur" is is stored.
stored.

Figure 10.4
Figure 10.4

Now, when
Now, when we we say
say aa + 1, we
we dodo not
not arrive
arrive at
at 4001,
4001, but
but at
at 4006.
4006.
This is
This because on
is because on incrementing
incrementing any any pointer;
pointer,- it
it points
points toto the
the
next location
next location of of its
its type.
type, aa points
points toto the
the zeroth
zeroth structure
structure in in the
the
array,
array, i.e. a[0]. Hence,
i.e. a[O]. Hence, on on incrementing
incrementing a, a, it
it will
will point
point toto the
the
next immediate
next immediate element
element ofof its
its type,
type, i.e.
i.e. the
the first
first structure
structure a[1]
a[l]
of the
of array. Likewise,
the array. Likewise, a a + 22 signifies
signifies the address of
the address of the
the second
second
element a[2]
element a[2] of
of the
the array.
array. Thus,
Thus, a[O].p
a[0].p contains
contains address
address 4006
4006
(( refer
refer figure
figure ),
), a[1].p
a[l].p contains
contains 4012,
4012, and
and a[2].p
a[2].p stores
stores 4000.
4000.

A struct
A struct pointer
pointer ptr
ptr is
is now
now set
set up,
up, which
which is
is assigned
assigned a, the
the
base address
base address of
of the
the array.
array.

In the
In the printf(
printf{ ), a[0].z
a[O].z denotes
denotes the
the address from where
address from where "Nag-
"Nag-
pur" is
pur" is stored.
stored. Hence
Hence "Nagpur"
"Nagpur" gets
gets printed out.
printed out.

Since ptr
Since contains the
ptr contains the address
address of of a[O],
a[0], ptr-e-z
ptr->z refers
refers to
to the
the
contents of
contents element zz of
of element of the
the array
array element
element a[O].
a[0]. Thus
Thus ptr-e-z
ptr->z
gives the
gives the address
address AO ( refer figure
AO (refer figure) ) and
and this
this address happens
address happens
to be
to be the
the base
base address
address of
of the
the string
string "Nagpur".
"Nagpur". Hence
Hence' 'Nagpur"
Nagpur"
gets printed
gets printed out.
out.
414
414 Exploring C
Exploring C

Let us now
Let us now analyse
analyse the
the expression
expression a[2].p->z.
a[2].p->z. The
The left
left side
side of
of
the arrow
the arrow operator
operator always
always represents
represents the base address
the base address ofof aa
structure. What structure
structure. What structure does
does a[2].p
a[2].p point
point to?
to? Looking
Looking at the
at the
figure we can
figure we can confirm
confirm that
that a[2].,
a[2].p contains
contains the
the address
address 4000,
4000,
which
which isis the
the base
base address
address of
of the
the array
array a[].
a[ ]. Hence
Hence the
the expression
expression
a[2].p->z
a[2].p->z cancan also
also be
be written as a->z.
written as a->z. Since
Since aa is
is the base
the base
address
address of of the
the structure
structure a[O],
a[0], this
this expression
expression refers
refers to the
to the
element
element zz ofof the
the zeroth
zeroth structure.
structure. Thus,
Thus, "Nagpur"
"Nagpur" gets printed .
gets printed
for the third
for the third time.
time.

(12) Output
(12) Output

o
0 agpur
agpur
11 aipur
aipur
2anpur
2 anpur

Explanation
Explanation

The example
The example deals with aa structure
deals with structure similar
similar toto the
the one
one we
we just
just
encountered. Picking
encountered. Picking up up from the for
from the for loop,
loop, it is executed
it is executed for
for 33
values of j : 0,
values ofj: 0 , 11 and 2. The first time through the for for loop, j is
equal to zero, so the first priDtf(
printf()) prints —a[0].i.
--a[O).i. Since the dot
operator has a higher priority, a[0].i is evaluated,
priority, first a[O).iis evaluated, which is
1. As'
1. —precedes
As -- precedesthe thevalue
valuetotobe
beprinted,
printed,11isisfirst
firstdecremented
decremented
to 0, and
to 0, and then
then printed
printed out.
out.

The second
The printf( )) prints
second ptintf( prints the
the string
string at
at address
address ++a[O].str.
++a[0].str.
a[O].s." gives the
a[0].strgives the starting address of
starting address of "Nagpur".
"Nagpur". On
On increment
increment-..
ing, it
it points to the next character,
character, 'a'
'a' of "Nagpur", so starting
from 'a',
'a', the remaining
remaining string "agpur" is outputted.
outputted.

A similar
similar procedure
procedure is repeated =
repeated for j = 1, and then once again
for =
for jj = 2,
2, following
following which
which the
the execution
execution is
is terminated.
terminated.

(13) Output
(13) Output
Structures and
Structures and Unions
Unions 415
415

8gpur
agpur
Kanpur
Kanpur
Kanpur
Kanpur

Explanation
Explanation

With a similar set up as in the previous two programs, we try


to print some more combinations.
combinations. Let us tackle them one by
one. The following figure should prove helpful in analysing
analysing
these combinations.
combinations.

a[0].z a[0].i a[O].p


a[O].:z;a[O].i a[0].p a[1].z
a[l].z a[1].i
a[l].i a[l
a[l].p a[2].z a(2].i
].p a[2].z a[2].i a[2].p
a[2].p
1 AO
AO 1 11 14006 1
40061 Al
AI 1 2 1
40121 A2
14012 A2 1 3 4000
1 4000 I
4000 4002 4004
4000 4002 4004 4006
4006 4008
4008 4010
4010 4012
4012 4014 4016
4014 4016
ptr

40001
| 4000 |
Notes:
Notes:
-- AO
AO denotes
denotes address
address from
from where
where "Nagpur"
"Nagpur" isisstored.
stored.
-- AlA I denotes
denotes address
address from
from where
where "Raipur"
"Raipur" isisstored.
stored.
-- A2
A2 denotes
denotes address
address from
from where
where "Kanpur"
"Kanpur" isisstored.
stored.

Figure 10.5

++(ptr->z)
tt( ptr-sz)

ptr holds the base address of the array of structures.


structures. We can
also think of this base address as the address of the zeroth
ptr->z thus signifies the element zz of the
structure in the array. ptr-e-z
zeroth structure,
structure, which is the starting address of the string
"Nagpur".
"Nagpur". OnOn incrementing
incrementing this
this using
using ++ operator,
operator, we
we get the
get the
next address,
next address, that
that of
of 'a'
'a' in
in "Nagpur".
"Nagpur". Therefore
Therefore the
the string
string is
is
printed out
printed 'a' onwards.
out 'a' onwards.

a[(++ptr)->i ].z
a[ ( ttptr )->i ].z
416
416 Exploring C
ExplQring C

Intimidating? Won't
Intimidating? Won't seemseem so so after
after we we have
have finished dissecting
finished dissecting
it. Starting
it. Starting from
from the,parentheses,
the parentheses, ++ptr ++ptr leads
leads to to contents
contents of ptr
of ptr
being incremented.
being incremented. CurrentlyCurrently ptr ptr contains
contains the the address
address of the
of the
zeroth structure
zeroth structure of of the
the array
array a[ a[].]. This
This address,
address, as as per
per the
the figure,
figure,
turns out
turns out toto be
be 4000.
4000. Adding
Adding 11 to to this
this address
address takestakes you
you 66 bytes
bytes
further, and
further, and not not 1,1, as
as you
you might
might be be led
led toto believe.
believe. This
This is so
is so
because on
because on incrementing
incrementing any any pointer,
pointer, it it points
points to to the next
the next
location of
location of iits type. Since
ts type. Since ptr is aa pointer
ptr is pointer to to aa structure,
structure, itit skips
skips
as many
as many bytes
bytes as as the
the structure
structure comprises
comprises of, ofandand points
points to the
to the
following location. Our structure si uses
following location. Our structure sl uses 2 bytes for the char 2 bytes for the char
pointer z,
pointer z, 22 for
for the
the int
int i,
i, and
and 2 2 for
for the
the struct
struct pointer
pointer p. Hence,
p. Hence,
on incrementing
on incrementing ptr, ptr, wewe get
get that
that address
address wherewhere a[l],
a[1], the next
the next
structure of
structure the array
of the array begins.
begins. This
This address
address 'as as per
per the
the figure
figure is is
4006. Now, (4006)->i is 2, as has been initialised
4006. Now, ( 4006 )->i is 2, as has been initialised earlier. Thus earlier. Thus
the expression
the expression a[( a[( ++ptr
++ptr )->i].z
)->iJ.z reduces
reduces to to plain
plain and simple
and simple
a[2].z, which
a[2].z, which yieldsyields the
the base
base address
address of of the
the string
string "Kanpur".
"Kanpur".
The same
The same is printed out
is printed out byby printf(
printf(). ).

a[--(ptr->p->i)].z
a[ --( ptr->p->i.) ].z

Following our
Following our strategy
strategy of of crossing
crossing the the bridges
bridges oneone atat aa time,
time,
we start with
westart with the
the inner
inner parentheses. Moving from
parentheses. Moving from left
left to
to right,
right,
ptr->p is
ptr-e-p is evaluated
evaluated first,
first. ptr,
ptr, after
after getting
getting incremented
incremented in the
in the
second printf(),
second printf( ), points
points to the first
to the first structure,
structure, a[1]a[l] ofof the
the array.
array.
The element p
The element p of
of this
this structure
structure stores
stores the address 4012,
the address 4012, or or in
in
other words,
other words, thethe address given by
address given by aa + 2.2. This
This address,
address, as you
as you
would agree,
would agree, isis the
the base
base address
address of of the
the second
second structure
structure of of the
the
array. Thus
array. Thus the parentheses reduce
the parentheses reduce to to (( aa +
+ 22 )->i,
)->i, or 4012->i,
or 4012->i,
which
which is is 3.
3. 33 is
is decremented
decremented to to 22 by
by the
the --- operator,
operator, and and wewe
realise that
realise that the
the expression
expression that that almost succeeded in
almost succeeded in putting
putting us us
off was
off was only
only aa camouflage
camouflage for for a[2].z!
a[2].z! This
This again
again yields
yields thethe
starting address
starting address of of "Kanpur",
"Kanpur", and and the
the same
same is is therefore
therefore dis-dis-
played once again,
played once again. r r

(14) Output
(14) Output
Structures andUnions
Structures and Unions 417
417

Aditya
Aditya
Aditya

Explanation
Explanation

struct si
struct s1 comprises of 2 pointers; one a charchar pointer and
c o m p r i s e s o f 2 p o i n t e r s ; o n e a p o i n t e r a n d

struct sl.
another, a pointer to struct
a n o t h e r , a si. arr[
arr[ ],
], an array of such struc-
p o i n t e r t o a n a r r a y o f s u c h s t r u c -

tures, is declared and initialised. Next, an array of pointers to


t u r e s , i s d e c l a r e d a n d i n i t i a l i s e d . N e x t , a n a r r a y o f p o i n t e r s t o

structures, p[3] is declared. What this means is that each


s t r u c t u r e s , p[3] i s d e c l a r e d . W h a t t h i s m e a n s i s t h a t e a c h

element of array of p[ ) will hold the address of a structure of


e l e m e n t o f a r r a y o f p[ ] w i l l h o l d t h e a d d r e s s o f a s t r u c t u r e o f

the type struct


t h e si.
struct sl.
t y p e

T h e f i r s t arr[0].ptr is assigned to p[0],


The first time in the for loop, arr[O].ptr
t i m e i n t h e p[O], l o o p , i s a s s i g n e d t o

which is the zeroth element of the array of pointers to struc-


w h i c h i s t h e z e r o t h e l e m e n t o f t h e a r r a y o f p o i n t e r s t o s t r u c -

arr[0].ptr contains the address 4004 as per the figure


tures. arr[O].ptr
t u r e s . c o n t a i n s t h e a d d r e s s 4 0 0 4 a s p e r t h e f i g u r e

given below. Likewise, p[l] is assigned the address 4008 and


g i v e n b e l o w . L i k e w i s e , p[l] i s a s s i g n e d t h e a d d r e s s 4 0 0 8 a n d

p[2], the address 4000.


p[2], t h e a d d r e s s 4 0 0 0 .

arr[O].str arr[O].ptr arr[1].str arr[1].ptr arr[2].str arr[2].ptr


a r r [ 0 ] . s t r a r r [ 0 ] . p t r a r r [ l ] . s t r a r r [ l ] . p t r a r r [ 2 ] . s t r a r r [ 2 ] . p t r

I AO
A O
I 4004
4 0 0 4
I Al
A I
4008
4 0 0 8
I A2
A 2
I 4000
4 0 0 0
I|

4000
4 0 0 0 4002
4 0 0 2 4004
4 0 0 4 4006
4 0 0 6 4008
4 0 0 8 4010
4 0 1 0

prO]
P [ 0 ] p[l]
P [ l ]
p[2]
P [ 2 ]

4004
4 0 0 4

6018
6 0 1 8
4008
4 0 0 8

6020
6 0 2 0
4000
4 0 0 0

6022
6 0 2 2
I
Notes:
N o t e s :

-- ADA O denotes
d e n o t e s address
a d d r e s s from
f r o m where
w h e r e "Nikhil"
" N i k h i i " is
i s stored.
s t o r e d .

-- Al
A I denotes
d e n o t e s address
a d d r e s s from
f r o m where
w h e r e "Aditya"
" A d i t y a " is
i s stored.
s t o r e d .

A 2 denotes
-- 1\2 d e n o t e s address
a d d r e s s from
f r o m where
w h e r e "Sudheer"
" S u d h e e r " isi s stored.
s t o r e d .

Figure 10.6
F i g u r e 1 0 . 6
418
418 Exploring C
Exploring C

Following this,
Following this, the
the printf(
priotf( )s
)s get
get executed.
executed. In In the first one,
the first the
one, the
string at p[O]->str
string at p[0]->str is is printed.
printed. AsAs p[0]
prO] is
is equal
equal toto 4004, the
4004, the
expression refers
expression refers to
to the element strofthe
the element str of the first
first structure, which
structure, which
stores
stores A
A1,l , the
the starting
starting address
address of of "Aditya".
"Aditya". Hence
Hence the
the name
name
"Aditya" gets printed
"Aditya" gets printed for
for the
the first
first time.
time.

In the second priotr(),


printf(), mentioning
mentioning p gives the base address of
the array p[ ]. This address according to the figure is 6018.
Hence *p
Hence *p would
would give
give the
the value
value at
at address
address 6018,
6018, which is
which is
nothing
nothing, but
but 4004.
4004. Thus (*p)->str evaluates
Thus (*p}->str evaluates to
to 4004->str,
4004->str,
which yields A1,
which yields A l , the
the base
base address
address of
of "Aditya".
"Aditya". This
This outputs
outputs
"Aditya" once again.
"Aditya" once again.

Finally, let
Finally, let us analyse the
us analyse the expression
expression **p.
**p. A
A quick
quick glance
glance atat
the figure would
the figure would confirm
confirm that
that *p
*p gives
gives the
the address
address 4004,
4004, and
and
**p therefore gives
**p therefore gives the address at
the address at 4004.
4004. This
This address
address this time
this time
too
too turns
turns out
out to
to be
be A
At.l . Thus
Thus "Aditya"
"Aditya" gets
gets printed out through
printed out through
this printf().
this priotf().

(15) Output
(15) Output

Nikhil Nikhil Nikhil


Akhil
Akhil
Akhil
Akhil
Anant
Anant
Akhil
Akhil
narrt
nant

Explanation
Explanation

You can
You can bynow.take
by now.take thethe setting
setting up
up of
of the
the arrays
arrays of
of structures
structures
and pointers to
and pointers tu structures
structures in
in your
your stride.
stride. In
In the
the for
for loop the
loop the
array p[
array p[]] is
is set up with
set up with the
the addresses
addresses 4004,4008
4004, 4008 and
and 4000, as .
4000, as
per
per the
the following figure.
following figure.
Structures and Unions
Structuresand Unions 419
419

AO

4000
4000
I 4004 1
4004

4002
4002
I Al
AI

4004
4004
I 4008
4008 I

4006
4006
I A2~
A2

4008
4008
4000
4000

4010
4010
I
p[0]
P[O] p[l]
P[l] p[2]
P[2]

Notes:
Notes:
4004
4004 4008
4008 4000
4000 I
-- AD
AOdenotes
denotesaddress
addressfrom
fromwhere"
where Akhil"
"Akhil"is is stored.
stored.
-- AlAl denotes
denotes address
addressfrom
from where
where"Nikhil"
"Nikhil"isisstored.
stored.
-- A2
A2 denotes
denotesaddress
addressfrom
fromwhere
where"Anant"
"Anant"isisstored.
stored.

Figure 10.7
Figure 10.7

In the first
In the first printf(
printf( ),
), p[Ol->str
p[0]->str isis same
same as as (( 4004->str
4004->str ).). As
As
4004 denotes
4004 the base
denotes the base address
address of of the
the first structure, str
first structure, str cor-
cor-
responds to
responds the address
to the address AI,
Al, which
which isis the
the base
base address
address of
of
"Nikhil". Hence
"Nikhil". Hence this printf( )) prints
this printf( prints the first string
the first string "Nikhil".
"Nikhil".

*p is another
*p is another way
way of
of referring
referring to
to the
the same
same element
element prO]
p[0] (( as
as
you would
you would recall
recall that n[i] is
that n[i] is equal
equal toto *(
*( nn + ii )
) ).Thus,
). Thus,
corresponding
corresponding to
to *p- >str, "Nikhil"
*p- >str, "Nikhil" is outputted once
is outputted once again.
again.

The third
The third expression
expression uses
uses **p,
**p, which
which is equal to
is equal to *( p[0]),
*( p[O) i.e.
), i.e..
*( 4004 ),
*( 4004 ), which
which can also be
can also be expressed
expressed asas *(
*( arr
arr + 1).
1 ). But the
But the
expression
expression *(*( arr
arr + 1)
1 ) is
is same
same as
as arr[1).
arr[l]. Thus
Thus the
the expression
expression
**p.str can also
**p.str can also be
be thought
thought ofof as
as arr[1] .str. As
arr[1).str. As can
can bebe con-
con-
firmed from the figure, arr[l].str gives Al, which is
firmed from the figure, arr[I].str gives AI, which is the base the base
address
address ofof the
the string
string "Nikhil".
"Nikhil". Hence
Hence "Nikhil"
"Nikhil" gets
gets printed
printed
through the printf().
through the printf().

After this, a function swap(


swap( ) is called; which takes as its
arguments the
arguments base addresses
the base addresses of
of two
two structures,
structures, arr
arr + 11 (( as
as *p
*p
equals arr + 11 )) and
equals arr and arr.
arr. Hence,
Hence, in
in swap(
swap( ),), pI
pi and
and p2
p2 have
have
been declared as
been declared as struct
struct pointers.
pointers. Using
Using an
an auxiliary
auxiliary pointer
pointer
temp, the
temp, strings at
the strings at (( arr
arr + 11 )->str
)->str and
and arr-e-str
arr->str are
are ex-ex-
changed. Thus, "Akhil" is now present where "Nikhil" was and
420
420 Exploring
Exploring C
C

vice
vice versa.
versa. The
The current
current contents
contents of
of the
the array
array arr[
arr[] ] are
are now
now
changed
changed to:
to:

{{
{"Nikhil", arr
{"Nikhil", arr ++ 11}},,
{"Akhil", arr
{"Akhil", arr ++ 2},
2},
{{"Anant",
"Anant", arr}
arr}
}}

Thus,
Thus, "Akhil"
"Akhil" shows
shows up
up for
for the
the next
next two
two printf(
printf( )s.
)s.

Let
Let us
us now
now analyse
analyse the
the expression
expression ((*p*p )->next->str. *p->next
)->next->str. *p->next
is
is same
same asas p[0]->next
p[O]->next Since
Since p[0]
prO] contains
contains the
the address
address 4004,
40()4,
the
the term
term can
can be
be expressed
expressed as as 4004->next,
4004->next, which
which yields
yields the
the
address
address 4008.
4008. Next,
Next, 4008- >str
>str yields
yields A2,
A2, the
the base
base address
address of
of
"Anant".
"Anant". Hence
Hence the
the printf(
printf() ) outputs
outputs "Anant".
"Anant".

After
After this,
this, swap()
swap() is is called
called once
once again
again with
with arrguments
arrguments p[0]prO]
and
and p[0]->next.
p[O]->next. This This time
time p[0]
prO] contains
contains the the address 4004,
address 4004,
while
while p[0]->next
p[O]->next contains
contains the
the address
address 4008.
4008. 4004
4004 and
and 4008
4008
represent
represent the
the base
base addresses
addresses of of the
the first
first and
and second structures
second structures
of
of the
the array
array arr[
arr[]. ]. In
In the
the function
function swap(
swap( )) the
the strings
strings in
in these
these
two
two structures
structures are
are interchanged.
interchanged. So So the
the array
array now
now looks
looks like:
like:

{{
{ "Nikhil", arr
{"Nikhil", a r r++ 11}},,
arr t 2},
{"Anant", arr+ 2},
{ "AkhiI arr}
{"Akhil",
U
arr}
,

}}

With
With this
this changed
changed array,
array, let's
let's look
look at
at the
the last
last set
set of
of printf(
printf( )s.
)s.
The
The first
first of
of these is quite
these is quite simple.
simple. p[0]->str,
p[O]->str, i.e. 4004->str
i.e. 4004->str
yields
yields "Anant"
"Anant" in
in keeping
k~~ping with
with the
the latest
latest contents
contents ofof the array.
the array.

Next
Next isis the
the expression
expression ((*++p[O]
*++p[0] ).str.
).str. In
In the
the parentheses p[0]
parentheses prO]
is
is incremented
incremented by by the
the ++
++ operator.
operator. Thus,
Thus, p[0],
p[O], storing
storing (( arr
arr +
+
1), now contains
1), now contains (arr
( a r r ++ 22).) . Now,
Now, *(
*( arr
arr ++ 2)
2 ) can
can be
be expressed
expressed
Structures and Unions
Structuresand Unions 421
421

as arr[2]. printf( ) prints arr[2].str,


arr[2]. Hence the printf() arr[2].str, which yields
"Akhil".

Not allowing
Not allowing ourselves
ourselves to
to be
be impressed
impressed by the length
by the length of
of the
the
last printf(
last printf( )'s
)'S argument,
argument, wewe start
start within
within the
the parentheses,
parentheses, onon
the left of
the left of the
the arrow
arrow operator. *p, i.e.
operator. *p, i.e. p[0],
p[O], having been
having been
incremented in
incremented in the
the preceding
preceding printf(),
printf(), currently
currently contains
contains ((arr
arr
+
+ 22 ).
). Since
Since the
the ->
-> operator
operator enjoys
enjoys aa higher
higher priority
priority than
than the
the
++,
++, (arr
( arr +
+ 22 )->next
)->next gets
gets evaluated
evaluated next,
next, yielding
yielding address arr.
address arr.
Now
Now thethe ++
++ goes
goes to
to work
work and
and we
we get
get the address arr
the address arr +
+ 1.
1.

The expression
expression can now be rewritten as ++( *( arr arr + 1)
1 ) ).str.
).str.
As *( arr
arr + 1 ) is same as arr[1],
arr[l], the expression is reduced to
++arr[l].str. arr[l].str gives the starting address of "Anant".
++arr[1].str. arr'[Ij.st;:
The ++ operator
The ++ operator increments this so-that
increments this so-that the
the address
address of
of the first
the first
on' of "Anant" is reached. Since this is the address supplied to
'n'
printf( ), the string is printed'
printf( printed Vn' onwards. This corresponds to
the last output "nant".

(16) Output
(16) Output

22
22

Explanation
Explanation

p and q have been declared as pointers to structures of the type


been.declared
struct node.
-struct node. InIn the
the next
next statement
statement we
we come
come across
across malloc(
malloc(), ),
which
which isis aa standard
standard lib
lib ary
ary function.
function. It
It reserves
reserves as
as many
many
locations
locations in
in memory
memory asas its argument specifies.
its argument specifies. Unlike
Unlike arrays,
arrays,
which put ~asidea
which put aside a fixed
fixed number
number ofof bytes
bytes specified
specified at
at the
the time
time
of declaration, malloc(
of declaration, malloc( )) can
can be
be given
given aa variable
variable as
as an
an argu-
argu-
ment,
ment, thus
thus allowing
allowing flexibility
flexibility in
in the
the. size
size of
of memory
memory to to be
be
allocated.
allocated

The struct
The node engages
struct node engages two
two bytes
bytes for data and
for data and two
two for
for link,
link,
hence the size of struct node
ofstruct 4. Therefore when the calls to
node is 4.
422
422 Exploring C
Exploring C

malloc( ) are made,


malloc( made, the argument that is passed is 4. Hence
each time, malloc(
-ea-chtime, malloc() ) reserves
reserves 4 bytes in memory. These bytes bytes
would always be in contiguous
contiguous memory locations. Having
locations. Having
successfully reserved
reserved the bytes,
bytes, malloc(
malloc( )) returns the base
address
address ofof these
these 44 bytes.
bytes. The
The base
base address
address returned
returned during
during the
the
first call to
first call to malloc()
malloc() is is collected
collected in
in pp and
and the
the one
one returned
returned
during
during the
the second
second call,
call, in
in q.
q. As
As pP and
and q q are
are both 2-byte
both 2-byte
addresses, saying sizeof(p)
addresses, saying sizeof(p) andsizeof(q)
and sizeof(q) results
results in
in 22 and
and 22
being outputted.
being outputted.

(17) Output
(17) Output

3040
3040

Explanation
Explanation

pp and
and qq are
are returned
returned the
the starting
starting addresses
addresses of of two
two slots
slots of
of
memory allocated by
memory allocated by the
the two
two malloc(
malloc( )s )s for
for structures
structures of the
of the
type struet
struct node.
node. When we say p..>data,
p->data, we are referring to
the first two
the first two bytes
bytes starting
starting from
from the
the address
address in in p,
p, where
where 30 is
30 is
assigned.
assigned. In In p-e-liak
p->Iink isis stored
stored the
the address
address present
present inin q,
q, which
which
is the base
is the base address
address ofof the
the area
area of
of memory
memory allocated
allocated byby the
the
second maJloc(
malloc(). ). In the structure starting fromfrom address con-
tained in q, 40 and NULL are stored, having defined NULL as
o0 prior
prior to main(
main(). printing p-sdata,
). On printing p->data, we find the 30 stored stored
there. Now we
there. Now change the
we change the contents
contents ofof pp to
to p->link,so
p->link, so that
that pp
is now
is now equal
equal to
to q.
q. Thus
Thus p->data
p-e-data now evaluates to
now .evaluates to 40, and on
40, and on
printing the same this time we get 40.

The arrangement
The arrangement of of the
the data
datatypes in this
types in this problem
problem conforms
conforms to
to
the popular 'linked
the popular 'linked list'
list' data
data structure.
structure. This arrangement is
This arrangement is
shown
shown inin the
the following.figure,
following figure, where
where the
the arrow
arrow represents
represents the
the
pointer to the
pointer to the next
next node.
node.
Structures
Structures and Unions
Unions 423
423

-----t.,
J
\<
1-- node
node ^ I\- node
node >.,{
30
'"---30...... _~.;I--·1
~ 1
40
40 0)
0
4002
4002 4004
4004 5002
5002 5004
5004

pP q
4002 | 5002 j
~

Figure 10.8

(18) Output
(18) Output

75
90
90

Explanation
Explanation

The structure
The structure comprises
comprises of of an
an integer
integer data and two
data and two struct
struct
pointers, previous and
pointers, previous and next.
next. The
The malioc(
malloc( )s)s allocate
allocate 22 blocks
blocks
of memory starting
of memory starting at
at addresses
addresses 4002
4002 and
and 5002
5002 asas per
per the figure
the figure
given below.
below. The whole arrangement can be thought of as a
chain of
chain of 22 structures.
structures. AsAs the
the variable
variable names
names suggest, previous
suggest, previous
of
of p,
p, assigned
assigned NULL,
NULL, indicates
indicates there
there is
is no
no structure
structure prior
prior toto
the one at
the one at p.
p. next
next of
of pp stores
stores the address of
the address the structure
of the structure at at q.
q.
Similarly, previous of
Similarly, previous of qq points
points to
to the
the structure
structure preceding
preceding it in
it in
the chain, which
the chain, which isis present
present atat p,
p, and next of
and next of q
q is assigned
is assigned
NULL,
NULL, signifying
signifying there
there are
are no
no more
more structures after the
structures after the one
one atat
q.
q. This arrangement is
Thisarrangement is nothing
nothing but
but aa 'doubly
'doubly linked list'.
linked list'.

L
424
424 Exploring C
Exploring C

node •{
·1 I\* node
node ·1
00
1
75
1 I· .,
•"
1 *
1
9090
1
00
I
4002
4002 4004
4004 4006
4006 5002
5002 5004
5004 5006
5006

pP qq

~ ~

Figure 10.9
Figure 10.9

The body of the while loop is executed subject to the condition condition
that p is not equal to NULL,
NULL, i.e. O.Since
0. Since p contains 4002, this
condition is
condition satisfied for
is satisfied for the
the first
first time,
time, hence p->data, which
hence p-sdata, which
is 75, gets
is 75, gets outputted.
outputted. Next
Next p p is
is assigned
assigned p->next,
p-e-next, which
which is is
equal to 5002. This is as good as shifting p so that it now
equal to 5002. This is as good as shifting p so that it now points points
to
to the
the next
next node.
node. Since
Since p p now
now contains
contains 5002,
5002, the
the condition
condition inin
the
the loop
loop would
would once
once again
again be satisfied, and
be satisfied, and this
this time
time around
around
the printf()) prints
the printf( prints out
out 90.
90. In
In the
the next
next statement,
statement, p-snext
p->next is is
assigned to p. But this time p->next contains 0 (
assigned to p. But this time p-e-next contains 0 ( NULL ), so NULL), so
p is assigned
P is assigned thethe value
value O.The
0. The condition
condition inin while
while now
now fails,
fails, and
and
the program is
the program is terminated.
terminated.

(19) Output
(19) Output

10
10
20
20
10
10
20
20
10
10
20
20
Structures and Unions
Structures and Unions 425
425

Explanation
Explanation

p and q are declared


declared as pointers
pointers to structures of the type struct
struct
node. With the use of malloc(),
node. malloc(), two areas in memory, each of
the same
the size as
same size as that
that of
of struct
struct node
node are
are reserved.
reserved, pp and
and q collect
q collect
the starting addresses
the starting addresses ofof these
these areas.
areas. According
According to to the figure,
the figure,
these
these addresses are 4002
addresses are 4002 and
and 5002.
5002. Now
Now 10 and 20
10 and 20 are assigned
are assigned
tp
to the data parts
the data parts within
within thethe two
two structures.
structures. Next,
Next, p->next is
p->next is
assigned the contents
assigned the contents ofof q,
q, i.e.
i.e. the
the address
address 5002,
5002, and q->next
and q->next
is assigned the
is assigned the contents
contents ofof p,
p, which
which isis the
the address
address 4002.
4002.

\* node
node H I\* node
node >\
U
~
10
10

4002
4002 4004
4004
'|I ., 20
20

5002
5002 5004
5004
I-1
'~

P
P q

4002 | 5002 1
~ ~

Figure 10.10

The while checks


checks the contents of p for its execution. The first
time since the
time since condition is
the condition is satisfied,
satisfied, p-e-data,
p->data, which
which is is 10,
10, gets
gets
printed.
printed. NowNow pp is is assigned
assigned p-snext,
p->next, which
which is is 5002.
5002. Thus
Thus pp
now
now points
points toto the second structure.
the second structure. Hence
Hence thethe condition
condition in in
while gets satisfied, and so this time p->data yields
while gets satisfied, and so this time p-e-data yields 20. After 20. After
this
this pp isis assigned
assigned the the value
value of of p-e-next.
p->next. Since
Since pp right
right now
now
contains 5002, p-
contains 5002, p- >next
>next this
this time
time turns
turns out
out to
to bebe 4002
4002 (( refer
refer
figure
figure ).). Thus
Thus pp is
is assigned
assigned thethe address
address 4002,
4002, and
and pp now
now points
points
to the first structure. The integer data within the first
to the first structure. The integer data within the first structure structure
stores
stores 10,10, which
which again
again gets
gets printed
printed when
when the the printf(
printf( )) isis
executed.
executed. OnceOnce again
again thethe address
address 5002 is assigned
5002 is assigned to to p through
p through
the statement
,the =
statement pp = p-snext.
p->next. ThusThus contents
contents of
of pp toggle between
toggle between
426
426 Exploring C
Exploring C

4002 and
4002 and 5002.
5002. And
And since
since pp never
never becomes
becomes NULL,
NULL, defined
defined
earlier as
earlier as 0,
0, the
the loop
loop is
is an
an indefinite one.
indefinite one.

(20) Output
(20) Output

442
2

Explanation
Explanation

unions resemble
unions resemble structures
structures is is more
more thanthan oneone ways.
ways. TheThe
methods for
methods for declaring,
declaring, initialising
initialising as as well
well asas accessing
accessing ele-
ele-
ments of
ments the union
of the union are are exactly
exactly same
same as as those
those used
used forfor
structures. However,
structures. However, the the resemblance
resemblance is is only
only skin deep. While
skin deep. While
in aa structure
in structure each element uses
each element uses different
different memory
memory space,space, all
all
the elements
the elements of of aa union
union refer to portions
refer to portions of of the
the same
same slot
slot of
of
memory. Thus,
memory. Thus, struct
struct ~ a allots
allots 22 bytes
bytes for
for int
int ii and
and 22 more
more forfor
ch[
ch[].]. On
On the
the other
other hand,
hand, thethe union
union reserves
reserves aa total
total of
of only
only 22
bytes. The
bytes. The first of the
first of the two
two bytes
bytes allotted
allotted toto intj
int j corresponds
corresponds to to
c[0], and
c[O], and the second to
the second to c[1].
c[l]. Hence,
Hence, the
the sizeof
sizeof operator
operator returns
returns
44 for
for struct
struct aa and
and 22 forfor union
union b, b, and
and the
the same
same is is seen
seen inin the
the
output.
output.

(21) Output
(21) Output

256 01
25601

Explanation
Explanation

In aa union
In union all
all elements
elements refer
refer to the same
to the same slot
slot of
of memory.
memory. Thus,
Thus,
in union
in union a,a, if
if 2
2 bytes,
bytes, say
say 4501
4501 and 4502, are
and 4502, are allocated
allocated to
to int
int
i, then
then ch[0] refers to
ch[O] refers to location
location 4501
4501 and
and ch[l],
ch[l], to
to 4502.
4502.
Structures
Structures and
and Unions
Unions, 427
427

u.i
u x h [ 0 ] - + - u.ch[l]—
~1L~h(0]~~

I 00000000
0000 0000 I 00000001
0000 0001 I
4501
4501 4502
4502

Figure
Figure 10.11
10.11

256,
256, which
which is is assigned
assigned to to u.i, is
is 16-bit
16-bit binary
binary 00000001
000000010000 0000
0000,
0000, and
and this
this is
is what
what isis actually
actually stored
stored inin memory
memory when when we we
say
say 256.
256. Contrary
Contrary to to what
what we we might
might expect,
expect, the
the first
first of
of the
the two
two
bytes
bytes stores
stores 0000
0000 0000,
0000, andand 0000
0000 0001
0001 is is present
present in in the
the second
second
byte.
byte. This
This is is because
because thethe lower
lower 88 bits
bits of
of an
an integer
integer areare always
always
stored
stored first,
first, and
and then
then the
the higher
higher 88 bits.
bits. That
That this
this is
is indeed
indeed so so is
is
shown
shown by by the
the result
result pf
of the
the printf( >.).

(22) Output
(22) Output

1224 74 '
122474

Explanation
Explanation

ss is
is aa variable
variable of of the
the type
type struet
struct a.
a. Unlike
Unlike aa union,
union, assigning
assigning
aa value
value toto s.i
s.i does
does not
not mean
mean that
that the
the other
other element
element in the
in'the
structure,
structure, i.e.
i.e. the
the char
char array
array ch[
ch[ ]] is
is also
also set
set up.
up. Hence,
Hence, when
when
we
we print
print out
out the
the contents
contents of
of the
the arrav. we get
arrav. we get all
all garbage
garbage values.
values.

(23) Output
(23) Output

332515
2515

Explanation
Explanation

l
428
428 Exploring C
Exploring C

..
Since each
Since each element
element of of aa union
union offers
offers aa different
different means
means of of
accessing the
accessing the same
same portion
porti\>~ of
of memory,
memory, initialising
initialising one element
one element
is necessary
is necessary andand sufficient
sufficient for
for assigning
assigning aa value
value toto that
that portion.
portion.
The following
The following figure
figure depicts
depicts the
the union
union variable
variable u u in memory.
in memory.
As
As can be observed,
can be observed, u.ch[0]
u.ch[O] is is assigned
assigned 3, 3, whose binary
whose binary
equivalent is
equivalent is 0000
0000 0011,
0011, and
and u.ch[1]
u.ch[l] is is assigned
assigned 2, 2, i.e.
i.e. binary
binary
0000 0010.
0000 0010. The
The same
same get
get printed
printed through
through printf()
printf( ) asas 33 and
and 2.
2.
However, the
However, the output
output of u.i is
of u.i is not
not straight
straight forward.
forward. This is
This is
because when an integer is stored in memory, its
because when an integer is stored in memory, its lower byte is lower byte is
stored before
stored before thethe higher
higher byte.
byte. Therefore
Therefore whenwhen u.i u.i is printed,
is printed,
binary 0000
binary 0000 0010
0010 0000
0000 0011
0011 is is used
used rather
rather than
than binary 0000
binary 0000
00110000
0011 0010. Now
0000 0010. Now binary
binary 0000
0000 0010
0010 0000
0000 0011
0011 is is equal
equal to
to
decimal 515. Hence u.i outputs
decimal 515. Hence u.i outputs 515. 515.

I-u.i
« U.1 *

I- u.ch[O]-I- — u.ch[l]
.-u.ch[0]-*t u.ch[l]-v
~ ,

I 00000011 I 00000010 II
0000 0011 0000 001~

6450
6450 6451
6451

Figure 10.12
Figure 10.12

(24) Output
(24) Output

00202
202

Here we
Here have aa union
we have union of of two
two structures. The same
structures. The same four bytes
four bytes
of memory
of memory are are made
made accessible
accessible by by different
different names.
names. For in-
For in-
stance, bytes
stance, bytes 6503
6503 andand 6504
6504 can
can bebe accessed
accessed together
together by by
mentioning u.aa.j,
mentioning u.aa.j, oror individually
individually as as u.bb.y[l]
u.bb.y[l] andand u.bb.y[2].
u.bb.y[2].
Integer 512,
Integer 512, which
which is is 0000001000000000
0000 0010 0000 0000 in in binary,
binary, is
is stored
stored
in u.aa.i
in u.aa.i and
and u.aa.j.
u.aa.j. One
One look
look atat the
the figure
figure will tell you
will tell you how
how
the printf()
the printf() generates
generates its output.
its output.
Structures and Unions
Structures Unions 429
429

---- u.aa.i ---_4----


u.aa.i - +
u.aa.j
u.aa.j --- .....
1

1- u.bb.x -+- u.bb.y[0]H—


u.bb.x —4r- u.bb.y[O]-+- u.bb.y[l] -f-u.bb.y[2jH
u.bb.y[l] -r--u.bb.y[2]--I
I 00000000
0000 0000 I 00000010
0000 0010 I 0000 0000 0010 I
0000 I 00000010
0000 0000 |

6501
6501 6502
6502 6503
6503 6504
6504

Figure 10.13
Figure 10.13

(25) Output
(25) Output

256 51201
25651201

Explanation
Explanation

union cc unites
union unites aa structure
structure of type struct
of type struct aa and
and another
another of
of type
type
struct b.
struct b. The figure depicts
The figure depicts the
the sort
sort of
of arrangement
arrangement that would
that would
be present
be in memory.
present in memory.

1---- u.aa.i
u.aa.i---- ....1+--- u.aa.j
u.aa.j --- .....
1
\*— u.bb.x —4*~"
1- u.bb.x u-bb.y —»|
.1' u.bb.y --I
00000000
0000 0000 I 00000001
0000 0001 I 00000000
0000 0000 00000010
0000 0010 I
6501
6501 6502
6502 6503
6503 6504
6504·

Figure 10.14
Figure 10.14

u.aa.i is
u.aa.i is assigned
assigned 256,
256, i.e.
i.e. binary
binary 0000
0000 0001
0001 0000·0000,
0000 0000, andand
u.aa.j, 512,
u.aa.j, 512, i.e.
i.e. binaty
binary 00000010
0000 0010 0000 0000 0000~
0000. In
In keeping
keeping with
with
the rule
the rule that the lower
that the lower byte
byte is is stored
stored first, 256 actually
first, 256 actually gets
gets
stored as
stored as 0000
0000 0000
0000 0000
0000 0001,
0001, and
and 512
512 asas 0000
0000 ()()(O
OOtO 0000
0000
0010. The
0010. first priDtf(
The first printf( )) is
is straight
straight forward.It
forward. It prints
prints out
out the
the
two integers
two integers 256
256 and
and 512.
512. InIn the
the second printf(), u.bb.x
second printf(), u.bb.x and
and
430
430 Exploring C
Exploring C

u.bb.y provide
u.bb.y provide access
access to
to the
the individual
individual bytes
bytes of
of the
the first
first int
int in
in
line, u.aa.i. Hence
line, u.aa.i. Hence the
the output
output 00 and
and 1.
1. Note that this
Note that this union has
union has
no provision u.aa.j byte wise.
provision to access u.aa.j wise. .

(26) Output
(26) Output

ABC
ABC
16961 67
1696167
4407873
4407873

Explanation
Explanation

aa is
is aa variable
variable which
which unites
unites anan unsigned
unsigned long
long I1 (( aa 44 byte
byte
number ), an
number), integer array
an integer array d[]
d[ ] and
and aa character
character array
array ch[].
ch[ ]. Into
Into
the character
the array ch[
character array ch[ ]] is
is copied
copied the
the string
string "ABC".
"ABC". On On
printing, we get
printing, we get this
this string
string as
as the
the first
first output.
output.

a.d[O] refers to the first 2 bytes of the union


a.d[0] union and Ld[l] a.d[l] to the
next 2.
next Since the
2. Since the ascii
ascii values
values of
of 'A'
' A ' and
and '8'' B ' are
are 65
65 and
and 66
66
respectively,
respectively, the the first
first 22 bytes
bytes contain
contain 65 65 and
and 6666 in
in that
that order.
order.
Taken
Taken as as an
an int, the number
int, the number in a.d[0] is
in Ld[O] is the
the binary
binary equivalent
equivalent
of
of 66 and 65
66 and 65 taken
taken as as aa whole,
whole, as
as in
in an
an int
int the
the lower
lower byte
byte gets
gets
stored
stored first. Binary equivalent of 66 is 0100 0010, and that of
first. Binary equivalent of 66 is 0100 0010, and that of
65
65 is
is 0100
0100 0001.
0001. SoSo when
when a.d[0]
a.d[O] is
is printed
printed out using %u,
out using the
%u, the
decimal
decimal equivalent
equivalent of binary 0100
of binary 0010 0100
0100 0010 0100 0001,16961
0001, 16961 is is
displayed.
displayed. Similarly,
Similarly, while
while printing
printing outout a.d[l],
a.d[1], thethe next two
next two
bytes
bytes containing
containing ''C' C (( decimal
decimal 6767 oror binary
binary 0100 0100 0011
0011 )) and
and
'\0' ( decimal 0 or binary 0000 0000 ) are
'\0' ( decimal 0 or binary 0000 0000 ) are used. Hence the used. Hence the
printf(
printf( )) outputs
outputs 67,67, which
which is
is the
the decimal
decimal equivalent
equivalent of of 0000
0000
0000 01000011.
0000 0100 0011.
Structures and Unions
Structures and Unions' 431
431

1---------- al--------
1---ad[O] a.d[I]---
l-a.ch[O]-+- ach[l] -+ a.ch[2]-+- ach[3]-I
I 0100 0001 I 0100 0010 I 0100 0011 I 0000 0000 I
4001 4002 4003 4004

Figure 10.15
Figure 10.15

In the
In the last
last printf(),
printf( ), the
the 44 byte
byte a.J
a.l is
is being
being printed,
printed, which is
which is
interpreted as 0000 0000 0100 0011 0100 0010 0100
interpreted as 0000 0000 0100 0011 0100 0010 0100 0001, or 0001, or
talking
talking in decimals, as
in decimals, as 0,
0, 67,
67, 66
66 and
and 65.
65. Taken
Taken as
as aa whole, its
whole, its
decimal equivalent 4407873
decimal equivalent 4407873 is outputted.
is outputted.
11
Input
Input and Output
Output in C
C
II
nn an
an effort
effort to
to keep
keep CC compact,
compact, Dennis
Dennis Ritchie
Ritchie defined
defined ab-
ab-
solutely
solutely nothing for Input/Output
nothingfor Input/Output (here
(here onwards
onwards referred as
referred as
I/O
I/O)) in
in C.
C. That's
that's right
right -- you read it
you read it right
right the first time!
the first time! Then
Then
what are printf()
what are and scanf()
pri.tf( ) and scanf() which
which we
we used
used consistently
consistently uptil
uptil now?
now?
These
These are
are called
called standard
standard library
library functions.
functions. There
There is no dearth
is no dearth ofof such
such
standard
standard library
library functions
functions that allow you
that allow you toto conduct
conduct all all sorts
sorts of
of
dialogues
dialogues and
and monologues
monologues with C.
with C.

The I/O
The I/O therefore,
therefore, isis entirely
entirely the
the responsibility
responsibility ofof the Operating
the Operating
System. With
System. With different
different operating
operating systems,
systems, the way I/O
the way I/O is
is done
done would
would
obviously
obviously be different. Fortunately,
be different. Fortunately, keeping
keeping the standard library
the standard library of
of
functions common, the
functions common, functions themselves
the functions themselves have
have been
been written
written dif-
dif-
ferently
ferently for different operating
for different operating systems.
systems. Hence,
Hence, we
we can
can use
use printf(
printf(),
),
scanf(),
scanf( ), or
or any
any other
other standard
standard library
library function
function in
in any environment,
any environment,
say DOS or
say DOS or UNIX,
UNIX, andand achieve
achieve the
the same
same result.
result. This
This is
is what
what makes
makes
C programs portable.
C programs portable.

The numerous
The numerous library
.
library functions
functions can
I
can be
be broadly classified as
broadly classified follows:
as follows:

(a) functions L. These receive input from


Console I/O functions L
from the keyboard
and write output
and write output to
to the,VDU.
the VDU.
(b)
(b) Disk I/O functions - These
These are to perform I/O operations on a
floppy disk or a hard d~~k.
disk.
(c) Port
Port I/O
I/O functions
functions -- These
These functions
functions are
are used
used to
to perform I/O
perform I/O
operations
operations on various ports.
Input and Output
Output in C
C 435
435

The following
The following sections
sections deal
deal with
with each
each of
of these
these categories
categories one
one by one.
by one.

Console I/O
Console Functions
I/O Functions

Console I/O
Console I/O functions
functions can
can be
be classified
classified as formatted and
as formatted and unformatted.
unformatted.
The basic
The basic difference
difference between these two
between these two classes
classes is
is that
that with
with the former
the former
class of
class of functions,
functions, wewe can
can govern
govern how
how the
the input
input is
is to be read
to be read from
from the
the
keyboard, or
keyboard, or how the output
how the output is going to
is going to appear
appear on
on the
the screen.
screen.

printf()) and
printf( and sc;anf(
scanf()) fall
fall in
in the
the category
category of
of formatted console I/O
formatted console I/O
functions. These
functions. These cancan be
be used
used for
for reading
reading and
and writing
writing chars,
chars, ints,
ints,
floats, as
floats, as well
well as
as strings.
strings. The
The general
general form
form of
of printf()
printf( ) is
is as follows:
as follows:

printf ("format
( "format string",
string" , list of variables)
variables);;

In the
In the format string, we
format string, we can
can use
use conversion
conversion specifications which
specifications which
begin with
begin with aa %
% andand escape
escape sequences
sequences which
which begin
begin with
with aa \.\. The
The
conversion specifications
conversion have already
specifications have already been
been dealt"
dealt with
with at
at length
length inin
Chapter 6.
Chapter 6. As
As for
for the
the escape
escape sequences,
sequences, these
these are
are shown
shown in in the
the
following figure
following figure along
along with
with the
the purpose
purpose of each.
of each.

Esc seq
Esc seq Purpose
Purpose Esc Seq
&CSeq Purpose
Purpose

\n
\n Newline
Newline \t
\t Tab
Tab
\b
\b Backspace
Backspace \r Carriage return
Carriage return
\f
\f Formfeed
Form feed \a Alert
Alert
V
\' Single quote
Single quote v\" Double qoute
Double qoute
\v
\v Vertical Tab
Vertical Tab \\ Backslash
Backslash

Figure 11.1 Escape


Figure 11.1 Escape sequences
sequences
436
436 Exploring
Exploring C

The printf( ) allows


The allows us us to
to format
format the
the output
output as as we
we wish
wish with
with the
the use
use
of optional
of optional specifiers
specifiers in in the
the conversion
conversion specifications.
specifications. ForFor example,
example,
saying %10d in
saying in aa conversion
conversion specification
specification wouldwould ensure
ensure that
that the
the
integer value
integer value isis printed
printed so so that
that it
it is
is right
right aligned
aligned inin aa total
total of 10
of 10
columns, padding
columns, padding thethe empty
empty columns,
c¢umns, if if any,
any, onon the left of
the left of the
the nurnber
number
with blank
with spaces. Similarly,
blank spaces. Similarly, using
using %-8.2fwould
%-8.2f would mean mean that
that the
the float
Ooat
value is
value is to
to have
have aa total
total field width of
field width of 88 columns,
columns, and and that
that it
it should
shouldbebe
printed upto
printed upto 2 2 decimal
decimal places.
places. The
The minus
minus signsign indicates
indicates that within
that within
the 88 columns
the columns the the float
float value
value should
should be be left
left aligned.
aligned.

Under the
Under the category
category ofof unformatted
unformatted console
console I/O
I/O there
there are several
are several
functions for
functions for handling
handling characters,
characters, integers
integers and
and strings. However,
strings. However,
there are
there are no
no functions
functions available
available for
for handling
handling floats
floats or
or doubles under
doubles under
this category.
this category. The
The following
following figures
figures list
list out
out these
these functions along
functions along
with their
with their purpose.
purpose.

INPUT
INPUT
Datatype
Datatype Function
Function Purpose
Parpose
char
char getch()
getch( ) Gets aa character
Gets character from
from the keyboard
the keyboard
as soon
as soon as
as it
it is
is typed,
typed, no
no need
need to
to hit
hit
Enter
Enter
getche()
getche( ) Similar
Similar toto getch(),
getch(k except echoes
except echoes
the character
the character onon the screen
t e screen
fgetchar()
fgetchar( ) Gets the
Gets the character
character and echoes it
and echoes it on
on
the screen,
the screen, requires
requires Enter
Enter key
key to
to be
be
hit
hit
getchar()
getchar() A macro,
A macro, works
works similar
similar to
to
fgetchar()
fgetchar()
string
string gets())
gets( Accepts
Accepts aa string
string until Enter key
until Enter key is
is
-. hit
hit

Figure 11.2a Unformatted


Figure 11.2a Unformatted Console
Console Input functions
Input functions
Input and Output
Input and Output in
in C
C 437
437

, .
OUTPUT
OUTPUT
Datatype
Datatype Function
Function Purpose
Purpose

char
char pu4ch()
pmch( ) Prints the
Prints the character
character on
on the screen.
the screen.
fputchar( ))
fputchar( Prints the
Prints the character
character on
on the screen.
the screen.
putchar( )
putchar() A macro,
A macro, works
works similar
similar to
to putch(
putch())
and fputchar().
and fputcharQ.
string
string puts())
puts( Outputs aa string
Outputs string to
to the
the screen.
screen.

Figure 11.2b Unformatted


Figure 1l.2b Unformatted Console Output functions
Console Output functions

Disk I/O Functions


Disk I/O Functions

We now
We now come
come to to how
how I/OI/O isis tackled
tackled with disks. Disk
with disks. Disk I/OI/O isis performed
performed
on entities
on called files.
entities called files. Accessing
Accessing the the disk
disk every
every time
time aa read
read oror write
write
operation is
'operation is to be performed
to be performed would would bebe inefficient.
inefficient. Hence
Hence aa buffer
buffer isis
used to
used to hold
hold thethe data
data inin transit
transit toto and
and from
from aa file.
file. In
In aa buffered
buffered readread
operation from
operation from aa disk
disk file,
file, aa fixed
fixed chunk
chunk of of bytes
bytes isis read
read from
from the disk
the disk
into a buffer. The functions requesting data from the
into a buffer. The functions requesting data from the file actually readfile actually read
from the
from the buffer.
buffer. When
When the the buffer
buffer has
has no
no characters
characters left,left, it
it is automat-
is automat-
ically refilled
ically refilled by by aa disk
disk read
read operation.
operation. A A similar
similar sequence
sequence occursoccurs
when writing
when writing to to aa file.
file. The
The useuse of
of aa buffer
buffer thus
thus leads
leads toto efficient I/O
efficient I/O
on disk files because there are fewer disk accesses,
on disk files because there are fewer disk accesses, which are much which are much
slower than reading
slower than reading fromfrom aa buffer
buffer inin memory.
memory. The Disk I/O
The Disk I/O functions
functions
are either
are either High
High Level
Level (( also
also called
called standard
standard I/OI/O or
or stream
stream I/O)I/O ) or Low
or Low
Level ( or system I/O ). The basic difference between
Level ( or system I/O ). The basic difference between them is that in them is that in
the high level functions the buffer management
the high level functions the buffer management is done by the is done by the
functions
functions themselves,
themselves, whereas whereas in in low
low level
level functions
functions this this isis the
the
responsibility of
responsibility of the programmer.
the programmer.
438
438 Exploring C
Exploring C

There are
There are aa large
large number
number of of functions
functions available
available for
for Disk
Disk I/O. The
I/O. The
following figure
following figure gives
gives aa ready
ready reference
reference of
of these
these with
with respect
respect to the
to the
datatypes
datatypes they handle.
they handle.

Functions
functions Input /
Input/ Datatypes Handled
Datatypes Handled Level
Level
Output
Output

getc())
getc( Input
Input characters
characters High
High
putc())
putc( Output
Output characters
characters High
High
fgetcQ
fgetc( ) Input
Input characters
characters High
High
fputc()
fputc( ) Output
Output characters
characters High
High
fscanf( ))
fscanf( Input
Input characters,
characters, strings,
strir:lr' High
High
numbers, reeor
numbers, records
fprintf()
fprintf( ) Output
Output characters, strings,
characters, strir:lr' High
High
numbers, reeor
numbers, records
fread()
fread( ) Input
Input characters, strings,
characters, stri~, High
High
numbers, reeor
numbers, recordss
fwrite()
fwrite( ) Output
Output characters," stri~,
characters; strings, High
High
numbers, reeor
numbers, records
read())
read( Input
Input chunks of
chunks bytes
of bytes Low
Low
write())
write( Output
Output chunks
chunks of bytes
of bytes Low
Low

Figure 11.3 Functions


Figure 11.3 Functions for
for Disk
Disk Input/Output
Input/Output

The files
The files that
that are
are to
to be
be accessed
accessed forfor I/O
I/O must
must first
first be
be opened.
opened. TheThe
function fopen()
function fopen() isis used
used toto open
open aa file
file in
in high
high level
level Disk l/0,whereas
Disk I/O, whereas
the function
the function open(
open()) is
is used
used in
in low
low level
level Disk
Disk I/O.
I/O. Let
Let us
us first
first look
look at
at
fopen().
fopen( Its syntax
). Its syntax is:
is:

fopen ("file
fopen "mode");
( "file name", ilmode" );

A file
A file can
can be
be opened
opened inin several
several modes,
modes, depending
depending upon
upon the
the operations
operations
we intend
we to perform
intend to perform onon the
the file. The following
file. The following figure
figure gives
gives the list
the list
Input and
and Output
Output inC
in C 439
439

of all the possible


possible modes in which a file can be opened. Observe
carefully how fopen()
fopen() reacts when the file to be opened is present/ab-
sent on
sent on the disk.
the disk.

Mode
Mode Operation
~ration Notes
Notes
Text/Binary
Text/Binary
"rVrb"
"r"/"rb" Reading-from
Reading- from filefile **
"w7"wb
"w"l"wb" H
Writing
Writing toto file
file ** ***
**>, ***
V 'fab"
"a"/"ab" Appending
Appendi~ new new contents at
contents at ***
***
the end ofthe
0 the file
H
r+7"rb+"
"r+"l"rb+" Reading existing contents, *
writing
wntll~ new contents and
new contents and
modifying existing contents
modi y'ingexisting contents
of the file '
"w+/wb+"
"w\/wb+" Writing and reading ** ***
**, ***
y

H
a+7"ab+"
"a+"/"ab+" Reading existing contents,
Readi~ existing contents, ***
***
appending
a~pen lOrnew contents
new
t e end 0offile,
the
contents at
file, cannot
at
modify
modify existing contents

*• Returns
Returns NULL
NULLififfile filedoes
doesnotnotexist
exist
* * Overwrites
•• Overwritesthe thefile
fileififititalready
alreadyexists
exists
*** New
••• file isis created
New file created ififlttt doesn't
doesn't exist
exist

Figure 11.4 File Opening Modes


Modes

For opening files


For opening files for
for low
low level
level I/O
I/O aa function
function called
called open()
open( ) is used.
is used.
Like fopen(
Like fopen( )) it it takes
takes as
as its
its argument
argument thethe filename
filename and
and the
the mode
mode in in
which the file
which the is to
file is to be
be opened.
opened. The The file opening mode
file opening mode isis however
however
specified using the
specified using the O-flags
O-flags defined
defined inin the file "fcntl.h".
the file "fcntl.h". These
Thes< O-flags
O-flags
are
are shown
shown in in the
the Figure 11.5. What
Figure 11.5. What if if we
we intend
intend to
to open
open i.i file for
file for
reading in binary mode? In such a case we have
reading in binary mode? In such a case we have to combine the to com! ine the
O-flags
O-ftags using bitwise |I operator.
using bitwise This operator
operator. This operator isis dealt
dealt with
with in
in detail
detail
in Chapter 12.
in Chapter 12. The
The open(
open( )) statement
statement would
would look
look like:
like:
440
440 Exploring
Exploring C
C

open ("temp.dat",
("temp.dat , OO_READ
R E A D |10_BINARY)
O B I N A R Y ) ;;
u

When
When aa new
new file
file is
is to
to be
be created,
created, it
it is
is necessary
necessary to
to use
use the
the flag
flag
0_CREAT.
O~CREAT.

Mode
Mode Operation
Operation
0o. .APPEND
APPEND Opens
Opens aa file
file for
for appending
appending
o CREAT
0. CREAT Creates
Creates aa new
new file
file for
for writing
writing
(( has
has no
no effect
effect ifif file
file already
already
exists
exists ))
o RDONLY
0_ RDONLY Creates
Creates aa new
new file
file for
for reading
reading
only
only
0o.-RDWR
RDWR Creates
Creates file
file for
for both
both reading
reading
'

and
and writing
writing
0o. .WRONLY
WRONLY Creates
Creates file
file for
for writing
writing only
only
0o. BINARY
BINARY Creates
Creates file
file in
in binary
binary mode
mode
0o. .TEXT
TEXT Creates
Creates file
file in
in text
text mode
mode

Figure
Figure 11.5 O-flags
Oeflags for open()
for open()

Once
Once thethe files
files have
have been
been opened
opened we we may
may want
want toto access
access the specific
the specific
part
part of
of the
the file.
file. This
This isis done
done byby positioning
positioning thethe file
file pointer
pointer atat the
the
desired
desired position
position in in the
the file. This
This can
can be
be achieved
achieved through functions
through functions
rewind()
rewind( ) and and fseek().
fseek( ). rewind()
rewind( ) positions
positions the
the file
file pointer
pointer right
right at
at
the
the beginning
beginning of of the
the file.
file. fseek()
fseek( ) in
in that
that sense
sense is
is more
more versatile, since
versatile, since
it
it can
can place
place the
the file
file pointer
pointer virtually
virtually anywhere
anywhere in in the
the file.
file. Its general
Its general
form
form is:
is:

fseek
fseek (file
(file pointer,
pOinter, ± number
number of bytes, anchor);;
bytes, anchor)

On
On calling
calling fseek()
fseek() it
it positions
positions the
the file
file pointer
pointer ahead
ahead (if
( if + ) or behind
or behind
((if
if -- ))the
the location
location specified
specified byby the
the anchor.
anchor. The
The anchor
anchor can
can be:
be:
Input
Input and
and Output
Output in
in C
C 441
441

(a) SEEKSET
SEEK SET - Beginning
Beginning of of the
the file
file
(b) SEEKEND
SEEK END - End
End of
of file
file
(c) SEEK_CUR
SEEK CUR - Current
Current position
position

Having
Having opened
opened the
the files,
files, worked
worked with
with them,
them, we
we need
need to
to close
close them
them
before
before exiting
exiting from
from the
the program.
program. The
The function
function fclose(
fclose( jj does
does this
this for
for
high
high level
level disk
disk I/O,
I/O, whereas
whereas the
the same
same is
is managed
managed through
through close()
close( ) for
for
low
low level
level disk
disk I/O.

There
There are
are some
some standard
standard file
file pointers
pointers that
that do
do not
not require
require the
the use
use of
of
fopen(
fopeD( ).). These
These correspond
correspond to to devices
devices like
like the
the keyboard
keyboard andand the
the
display
display monitor,
monitor, with
with which
which thethe communication
communication is is established
established at
at all
all
times.
times. That
That is,
is, they
they are
are permanently
permanently open open for
for reading
reading or or writing.
writing.
These
These pointers
pointers are
are given
given in
in the
the following figure.
following figure.

Pointer
PoiD.ter Device
Device

stdin
stdin standard
standard input
input device
device ((keyboard)
keyboard)
stdout
stdout standard
standard output device (( VDU
OU!putdevice VOU ))
stderr
stderr standard
standard error
error device (VDU)
device (VOlJ)
stdaux
stdaux standard
standard auxiliary
auxiliary device
device (( serial port))
serial port
stdprn
stdpm standard
standard printing
printing device
device (parallel
( parallel printer
printer) )

Figure
Figure 11.6
11.6 Standard
Standard File Pointers
File Pointers

Port
Port I/O Functions
Functions

Having
Having seen
seen what
what Console
Console and
and Disk
Disk I/O
I/O have/to
haveto offer,
offer, let
let us
us now
now turn
tum
our
our attention
attention to
to the
the Port
Port I/O
I/O functions.
functions. With
With the
the earlier
earlier two
two forms
forms of
of
I/O
I/O we
we were
were able
able to
to access
access the
the keyboard,
keyboard, the
the VDU
VDU and and the
the disks.
disks.
However, they don't
However, they don't equip
equip us
us to
to access
access peripherals
peripherals like
like the speaker
the speaker
442
442 Exploring C
-Exploring

or the
or serial part.
the serial port. For
For instance,
instance, for
for generating
generating aa sound
sound onon the
the IBM
IBM PCPC
compatible we
compatible we would
would have
have toto establish communication directly
establish communication directly with
with
the programmable
the programmable peripheral
peripheral interface
interface chip
chip present
present in
in the computer.
the computer.
In
In such
such cases Port 1/0
cases Port I/O isis the
the only
only option
option available.
available. Thus, toto beep
beep the
the
speaker we write data to the port associated with the PPI
speaker we write data to the port associated with the PPI chip. The chip. The
functions available
functions available under
under this
this category
category are
are given
given in
in the
the following
following
figure.
figure.

Functions
Functiom Input/Output
Input/Output Number
NOJDberofof
bytes accessed
bytes accessed
inportb())
inportb( Input
Input 1
1
outportb( ))
outportbl Output
Output 11
inportw( )
inportw() Input
Input 22
inportw()
inportw() Output
Output 22

Figure 11.7 Functions


Figure 11.7 Functions for
for Port I/O
Port 1/0

inportb() and
inportb() and outportb()
outportb( ) are
are used
used for reading and
for reading and writing'S
writing 8 bit
bit data
data
from or
from or to
to the
the port
port address
address specified
specified as
as their
their arguments.
arguments. As against
against
this, inportw(
. this, inportw()) and
and outportw(
outportw()) areare used
used when
when we we want
want toto receive
receive
or send
or two bytes
send two bytes of
of data
data in
in aa single call.
single call.
Input
fllput and
and Output
Output in
in CC 443
443

Exercise
Exercise

[A] What will be the output of the following programs:

((1)
1) main()
mainO
{{
static char
static char str[ =•
Academy" ;
str{ ]] = "Academy";
prinlf ( '%s\l1%s', str, •Academy" ) ;
printf ("%s\n%s", str, "Academy");
}
}

((2)
2) main()
main()
{{
float a == 3.14
floata 3.14;;
prinlf C\na
printf ("\na;"= %f,
%f, a)
a ) ;;
( "\na =
printf C\na = %6.2T, a)
printf %6.2r, a ) ;;
printf C\na = %-6.2f, a)
printf ( "\na = %-6.2r, a ) ;;
printf ("\na = %6.1f, a ) ;;
prinlf ("\na = %6.1f, a)
prinlf ("\na
printf = %6.or, a)
( "\na = %6.0f, a ) ;;
}}

(3)
(3) main()
main()
{
{
printf ("%20s\n
printf ( '%20s\n', "short
'shorf leg");
,
I
leg' ) ;
printf C%20s\n",
printf ( "%20s\n', "long
'Iong leg");
leg' ) ;
printf ("%20s\n",
printf ( '%20s\n', "deep
~deepfine leg' ) ;
fine leg");
prinlf ('%20s\n', 'backward
printf ("%20s\n", "backward short leg') ;
short leg");
prinlf ("%20s\n
printf ( '%20s\n", "legs
'Iegs all the same!");
,
I
same" ) ;
}}

((4)
4) main()
main()
{{
printf (("Hello\nHi\n");
printf 'Hello\nHi\n') ;
printf ( 'Hello\rHi' ) ;
printf ("HelkArHi");
}
}
444
444 Exploring C
Exploring C

(5)
(5) main()
main()
{{
printf
printf (("Hello\b\b\b\b\b");
"Hello\b\b\b\b\b" ) ;
printf
printf (("Hi!\b\b\bBye");
"Hmb\b\bBye· ) ;
}}

(6)
(6) main()
main()
{{
printf t"l\tam\ta\tboy·
printf (-"l\tam\ta\tboy");
);
}}

(7)
(7) #include
#include "stdio.h"
·stdio.h"
main()
main()
{{
static str[] ] == "In
static char str[ "in the country
country of snake
snake charmers ...• ;
charmers...";
char*s;
char*s;

s = str;
str;
while (*s)
while (*s)
{
putch
p u t c h(*s)
( * s ) ;;
s++
s++; ;
}}

printf
printf (( "\n"
V ) ); ;-
s = str;
str;

while (*s)
while (*s)
{{
putchar ( *s) ;
putchar(*s);
s++
s++; ;
}}
}
}

(8)
(8) #include
#include "stdiah"
"stdio.h"
main())
main(
Input
Input and
and Output
Output in
in C
C 445
445

{{
charch;
char c h ;
int i;
inti;

printf ("Enter
( "Enter any
any number...");
number... • ) ;
scanf ("%d",
( "%d", &
&i)i ) ;;

fflush (stdin);
( stdin ) .;

printf ("Enter
( "Enter any character...");
character... • ) ;
scanf (("%c",&ch);
"%c·, &ch) ;

printf ("\n%d
( "\n%d %c", i, ch)
c h ) ;;
}}

((9)
9) include
#include "stdio.h"
"stdio.h"
main()
main( )
{{
charstr1[30],str2[30];
char str1[30], str2{30] ;

printf ("Enter sentenced");


( "Enter a sentence\n" );
scanf ("%s",
( "%s·, str1 s t r l) ;;
printf ("%s",str1)
( "%s", str1 ) ;
fflush ((stdin);
stdin ) ;
printf ("\nEnter
( "\nEnter a sentence\n"
sentenced");
);
ggets
e t s ( sstr2)
t r 2 ) ;;
printf (("%s",str2);
"%s·, str2) ;
}

(10) mai{ n()


(10) main( )
{
char name[20],
char name[20), sname[20];
sname[20) ;

puts ("Enter
( "Enter your name and surname\n'
surname\n");
);
gets (name, sname);
(name, sname) ;
puts (name, sname);;
( name, sname)
printf (("%s
·%s %s",
%s·, name, sname)
sname);;
446
446 Exploring C
Exploring C

>}

(11)
(11) main()
main()
{{
FILE*fp
FILE*fp;;
fp == fopen
fbpen(("TRIALC·,
"TRIALC", "r")
V ) ;;
fclose ( fp)
fclose(fp); ;
}}

(12) #include "stdiah"


"stdio.h·
main()
main()
{{
char str[20] ;
char str[20];
FILE
FILE *fp;
*fp;
fp == fopert(
fp strcpy (str,
foperv(strcpy (str, ·ENGINEC·),
"ENGINE.C"), ·w·)
V ) ;;
fclose (
fclose(fp);fp) ;
}}

(13) #include
#include "stdiah"
·stdio.h·
mainQ
main()
{{
FILE*fp
FILE *fp;;
char str[80] ;
charstr[80];

TRIALCcontains
I*TRIALC
1* containsonly
onlyone
oneline:
line:
Its round, round, round world! *'
Its a round, round, round world! */
a

=
fp = fopen( "TRIALC", Or")
fopen ("TRIALC', V);
while ((fgets
while fgets ((str, EOF))
str, 80, fp) != EOF
puts ( sstr)
tr);

((14)
14) #include
#include "stdiah"
°stdio.h"
mainQ)
main(
{{
*fp;
FILE *fp;
Input
Inputand
andOutput
Output ininCC 447
447

charc;
char c;

=
fopen ( "TRy. C", V"r") ); ;
fpfp= fopen(TRY.C",
if (fp ==NULL)
if ( fp NULL)
{
{
puts("Cannot
puts ( "Cannotopen
openfile");
file" ) ;
exn(1) ;
exit(1);
}}
while( (( c( c==ggetc
while e t c ( (f fp EOF )
p ) )) !)=!=EOF)
putch(
putch(c); c) :

fclose ( fp ) ;
fclose(fp);
}
}

( (15) include"stdio.h"
1 5 ) ##include "stdio.h"
main()
mainQ
{
{
FILE~, *(s, *ft ;
FILE *fp, *fs, *ft;

fp =
fp = fopen("A.C",
fopen ( "A.C", V"r")); ;
=
fsfs = fopen("B.C",
fopen ( "B.C", "r");
"r") ;
fopen ( ·C.C",
ft = fopen("C.C", V )) ; :
ft = "r"

fclose (fp,
fclose fs, fft)t ) ;;
(fp, fs,
}
}

((16) #include "stdio.h"


1 6 ) #include "stdio.h"
main()
main()
{
{
char name [20], name1 [20] ;
char name [20], name1[20];
int age, age1 :
int age, a g e l ;
printf ("Enter
printf ( "Enter name
name and
and age\n");
age\n" ) :
scant ("%s
scanf ("%s %d",
%d·, name,
name, &age);
&age) ;
printf ("%s %d", name, a g e ) ;;
printf ("%5 %d·, name, age)

printf ("\nEnter
printf ( '\nEnter name
name and
and age\n"):
age\n" ) :
448
448 Exploring
Exploring C
C

fscanf
fscanf (stdin,
( stdin, "%s
"%5 %d", namel,
name1, &age1);
&agel ) ;
fprintf
fprintf (stdout,
(stdout, "%s
"%5 %d", namel, a g e l ) ;;
namel, agel)
}}

((11)
1 7 ) #include
#include "stdiah"
"stdio.h"
mainQ
main( )
{{
char name[20]
char name[20] == "Sandeep";
"Sandeep" ;
int salary = 1500 ;
salary = 1500;

printf
printf (*%s
( "%5 %d\n", name, salary);
%d\n" , name, salary) ;
fprintf (stdout, "%s
fprintf (stdout, "%5 %d", name, salary);
salary) ;
}}

((18)
1 8 ) include
#include "stdiah"
"stdio.h"
mainQ
main( )
{{
static char
static char str[] = "Triplet" ;
st~ ] = Triplet";
char *5 ;
charts;

ss = str;
str;
while (*s)
while (*s) .
{{
putc (*5, stdout);
putc(*s, stdout) ;
fputchar(*s);;
fputchar (*5)
printf (("%c\n",*s);
printf "%c\n", *5) ;
s++;
5t+ ;
}}
}}

((19)
19) /*
1* This
This program
program is stored
stored in a file
file called
called PROB.C
PROB. C */
main
main (argc, argv)
( argc, argv)
intargc;
int argc;
char*argv[];
char *argv[] ;
{{
printf ("%d\n",
printf ( "%d\n", argc)
argc);;
Input and
Input and Output
Output in C
C 449
449

printf (("%s\argv[0]);
'%s', argv(01) ;
}}

((20)
20) Thisprogram
I*This
1* programisisstored
storedininaafile
filecalled
calledPROB.C
PROB.C*/*/
m a i n(x,
main ( x , y)
y)
intx;
intx;
char*y[];
char*y[] ;
{{
printf (("%d\n",
'%d\n', x)
x);
printf
printf ("%s-,y[0]);;
( '%s', y[O])
}}

((21)
21) /*
1* Suppose this program is stored in the file
file PR.C and its
its correspond-
executable file PR.EXE is executed at DOS prompt by saying,
ing exeCutablefile saying,
PR CAT DOG PARROT
PARROT*/ */

main(argc,
main argv))
( argc, argv
int argc;
argc; t

char *argv[] ;
char*argv[];
{{
for ( ii == 0 ;; ii << argc;
argc ; i++
i++))
printf
printf (("%s\n\
'%s\n', argv[i] ) ;'
argvfjl);
}}

((22)
22) main()
main()
{{
char ch = 'z' =
'z';;
static char str[ =
st~]] = 'Zebra'
"Zebra";;

pule (ch,
putc stdprn);;
( ch, stdprn)
(stdprn, "%s",
fprintf (stdpi'n, str);;
'%s', str)
fwrite ((str,
fWrite 5 , 11,, stdprn)
str, 5, stdprn);;
fputs ((str, stdprn);;
str, stdprn)
}

((23)
23) #include"stdio.h"
#include"stdio.h"
450
450 Exploring C
Exploring C

main()
main()
{{
struct
struct aa
{
{
char cily(10] ;
charcity[10];
illt pin;
int pin;
};
};
static struct a b = { "Udaipur", 20} ;
static struct a b = {"Udaipur", 2 0 } ;
static char c(] = "Bangalore" ;
static char c[ ] = "Bangalore';
FILE*fp ;
FILE *fp;
fp == fopen
fp fopen(( "TRIAL
TRIAL",", "wb")
"wb");;
fwritej&b,
fwrite (&b, sizeof ( bb),) , 1,
1 ,fp)
fp);
fwrite(c, 9 , 1 , f p )
fwrite ( c, 9, 1, fp ) ;
}

P3]
[B) Answer the
Answer following:
the following:

(1)
(1) The requirement
The requirement is
is that
that the
the program
program should
should receive
receive aa key
key from
from
the keyboard. However,
the keyboard, However, the the key
key that
that is
is hit should not
hit should not appear
appear
on the
on the screen.
screen. Which
Which of of the
the following
following functions
functions would
would youyou
use?
use? .

(a) getch(
(a) getchf ))
(b)getche()
(b) getche( )
(c) getchar(
(c) getchar( ))
(d)fgetchar()
(d) fgetchar( )

(2)
(2) Which
Which ofof the following functions
the following functions is
is most
most appropriate for
appropriate for
storing numbers
storing numbers in
in aa file?
file?

(a) putc()
(a) putc( )
(b) fprintf(
(b) fprintf( ))
(c) fwrite(
(c) fwrite() )

(3)
(3) Which of
Which of the
the following
following functions
functions is more versatile
is more versatile for
for position-
position-
ing the
ing the file
file pointer
pointer in
in aa file?
file?
Input
Input and
and Output
Output in
in C
C 451
451

(a)
(a) rewind(
rewind() )
(b) fseek(
fseek() )
(c)ftell()
(c) ftell()

(4)
(4) Which
Which of of the
the following
following file
file opening
opening modes
modes would
would destroy
destroy the
the
file
file being
being opened,
opened, if
if the
the file
file already
already exists
exists on
on the
the disk?
disk?

(a)
(a)"w"V
(b) "wb"
"wb"
(c) "wb+"
"wb+"
(d)
(d) "rb+"
"rb+"
(e) "ab+"
ab+
n M

(5)
;(5) Which
Which ofof the
the following
following functions
functions are
are ideally
ideally suited
suited for
for reading
reading
the
the contents
contents ofof aa file
file record
record by
by record?
record?

(a)getc()
(a) getc()
(b)gets()
(b) getsf )
(c)fread()
(c) fread()
(d)fgets()
(d) fgets()

[[C]
Q Attempt
Attempt the following:
the following:

(1)
(1) Write
Write aa program
program which
which would
would remove
remove all
all comments
comments from
from aa CC
program.
program. Your
Your program
program should
should bebe capable
capable ofof removing
removing com-
com-
ments
ments which
which occur
occur at
at the
the beginning
beginning ofof aa statement,
statement, at
at the
the end
end
of a statement as well as the comments which are split over
of a statement as well as the comments which are split over
multiple
multiple lines.
lines.

(2)
(2) A
A file
file opened
opened in in Document
Document mode
mode in in Wordstar
Words tar stores
stores each word
each word
with
with its
its last
last character
character being
being stored
stored as as the
the ascii
ascii value
value of the
of the
character
character plus
plus 128.
128. As against
against this
this aa Non-document
Non-document modemode file
file
is stored
is stored asas aa normal
normal ascii
ascii file.
file. Write
Writea a program
program which would
which would
convert
convert aa Document
Document modemode file
file into
into aa Non-document
Non-document mode file.
mode file.
452
452 Exploring C
Exploring C

Answers
Answers

Answers to [A]
Answers to [A]

(1)
(1) Output
Output

Academy
Academy
Academy
Academy

Explanation
Explanation

We know
We know that mentioning the
that mentioning the name
name of
of aa string
string yields
yields the base
the base
address
address ofof the
the string.
string. When
When this
this base
base address
address is passed to
is passed to
printf( )) it
printf( it prints
prints out each character
out each character in
in the
the string
string till
till it
it en-
en-
counters '\0'
counters '\0' sitting
sitting at
at the end of
the end of the string. A
the string. A string
string written
written
within double quotes also gives the base address of the string. string.
This base
This base address
address when
when passed
passed toto printf() would result
printf( ) would in
result in
printing "Academy" once
printing "Academy" once again.
again.

(2)
(2) Output
Output

a = 3.140000
a=3.140000
aa== 3.14
3.14
aii=3.14
= 3.14
aa= = 3.1
3.1
aa=
= 33

Explanation
Explanation

The first
The first printf(
printf( )) uses
uses the
the format
format specification
specification for
for aa float,
float,
hence a gets printed as 3.140000,
3.14()()()(),as float is printed
as by default a float printed
with 66 decimal
with decimal places.
places. In
In the
the next printf( ),
next printf( ), the
the number
number thatthat
precedes
precedes the
the ff in
in %f
%f is
is an
an optional
optional specifier,
specifier, which governs
which governs
how exactly the
how exactly the variable
variable is
is to
to be
be printed.
printed. 6.2
6.2 signifies
signifies that the
that the
and Output
Input and Output in C
C 453
453

field
field width, i.e.
i.e, the total number of columns that the value
occupies on the screen, should be 6, and that the value should
have 2 digits after the decimal point. Thus 3.14 is printed with
blank spaces on the left, i.e. with right justification. For left
justification,
justification, we use a minus sign with the specifiers, as is done
in the next printf( ). It prints the value of of a starting from
from the
zeroth column, with only 2 decimal digits. The specification
6.1 prints
prints 3.1
3.1 with
with right
right justification. In the
the last printf( ), 6.0
),6.0
specifies
specifies zero
zero decimal digits,
digits, hence
hence only
only 33 is
is displayed
displayed right
justified.
justified.

(3)
(3) Output
Output

short
short leg
leg
long
long leg
leg
deep
deep fine
fine leg
leg
backward
backward short
short leg
leg
legs
legs all the same!
aUthe same!

Explanation
Explanation

The
The output
output isis right
right justified,
justified, as
as the
the field
field width
width specified
specified with
with
each
each %s%s isis plus
plus 20.
20. For
For each
each string,
string; 20
20 columns
columns are
are set
set aside,
aside,
and
andthe
the strings
strings are
areprinted
printed with
with blanks
blanks filling
fillingup
upthe
the remaining
remaining
columns
columns on on the
the left.
left.

(4)
(4) Output
Output

Hello
Hello
Hi
Hi
Hillo
Hillo

Explanation
Explanation
454 Exploring C

The escape sequence


sequence '\n', called new line, takes the cursor to
the beginning
beginning of the next line.line. Hence with the first printf(
printf())
"Hello" and
"Hello" "Hi" are
and "Hi" are printed
printed on on consecutive
consecutive lines.
lines. A
A '\r',
V , on
on
the other hand,
the other hand, takes the cursor
takes the cursor to
to the
the beginning
beginning ofof the
the same
same
line in which
line in which the
the cursor
cursor is
is currently
currently present
present. Hence,
Hence, having
having
printed
printed "Hello",
"Hello", the
the cursor
cursor isis sent
sent back
back at
at 'H',
'H', and then "Hi"
and then "Hi" is
is
printed.
printed. The first two
The first two letters
letters of
of "Hello"
"Hello" are
are therefore
therefore written
written
over,
over, and we get
and we get the
the output
output asas "Hillo".
"Hillo".

(5) Output
Output

Byelo

Explanation
Explanation

The escape sequence


sequence '\b'
'\b' stands for backspace,
backspace, which takes
the cursor to the previous character. In the first printf( printf( ),
"Hello" is printed,
printed, following which the cursor is positioned
positioned
' o ' . Now the 55 backspaces
after '0'. backspaces take the cursor to the letter 'H''H'
of "Hello".
of "Hello". The The control
control now
now passes
passes toto the
the second printf(),
second printf( and
), and
"Hi!" is written over the first three characters of "Hello",
resulting in "Hi
resulting "Hi!lo". again 33 backspaces
llo". Once again backspaces are encountered,
encountered,
which take the cursor back at 'H' 'H' of "Hi!".
"HU". Next "Bye" is
printed on top of "Hi!". The 'lo' '10' that is seen has persisted from
the first printf()'s
printf( )'s "Hello", as it never got overwritten. Hence
the output
the "Byelo".
output "Byelo".

(6) Output
Output

.1I am'
am a boy
boy·

Explanation
Explanation

The message
The message is
is printed
printed with
with spaces
spaces inserted
inserted wherever
wherever the
the
escape sequence
sequence '\t'
'\t' occured.
occured. This sequence stands for a tab.
r
Input
Input and
and Output
Output in
in C
C 455
455

In
In our
our com
com piler,
piler, the
the tabs
tabs had
had been
been setset up
up after
after every
every 55 columns,
columns,
at
at 0.
O. 5,
5. 10,
10, etc.
etc. Hence,
Hence, while
while executing
executing printf(),
printf( ), when
when '\t''\t' is
is
encountered,
encountered, the the cursor
cursor skips
skips toto the
the immediately
immediately next next column
column
which
which is is aa multiple
multiple of of 5,
5 and
and then
then prints
prints the
the next
next word.
word. ThusThus
"I"
"I" is
is printed
printed from the 00 thcolumn,
from the th
column, "am" "am" from the 55th,, "a"
from the th
"a" from
from
the 1loth,
the 0 , and
th
and "boy"
"boy from
II from the
the 1155th column.
th
column. SomeSome compilers
compilers like like
Turbo
Turbo C C allow
allow you
you toto change
change thethe tab
tab settings,
settings, so
so that
that the
the tab
tab
widths
widths can can bebe set
set up
up asas desired.
desired.

(7)
(7). Output
Output

In the country
country of snake
snake charmers...
charmers .
In the country
country of snake
snake charmers...
charmers .

Explanation
Explanation

putch(
putch( ) is is anan unformatted
unformatted consoleconsole I/O function,
function, whereas
whereas
pputchar(
u t c h a r ( )) is
is aa macro.
macro. However,
However, their their working
working is is the
the same.
same.
They
They putput thethe contents
contents of of the
the character
character variable
variable supplied
supplied as as their
their
argument
argument on on to to the
the screen.
screen. Having
Having assigned
assigned toto ss the
the starting
starting
address
address of of the
the string
string str[
str[],], through
through the
the while
while loops,
loops, thethe value
value
at address contained in s is printed out, then
at address contained in s is printed out, then s is incremented s is incremented
so
so that
that itit points
points to to the
the next
next character.
character. Hence,
Hence, the the string
string is
is
printed
printed out out twice.
twice.

((8)
8) Output
Output

Enter
Enter any
any number...
number ... 2
Enter any character...
Enter any character ... aa
2a
2a

Explanation
Explanation

We
We entered
entered 22 and
and aa and
and the
the same
same were
were faithfully outputted.
faithfully outputted.
Quite
Quite straight,
straight, that.
that. What
What you
you might
might be
be wondering
wondering about
about is
is the
the
i
456
456 Exploring C
Exploring

statement mush
statement fflush (( stdin
stdin )"). This
This statement
statement empties
empties thethe buffer
buffer
before prompting
before prompting us us to
to enter
enter aa character.
character. When
When we we typed
typed 22 and
and
hit
hit Enter,
Enter, the
the buffer
buffer stored
stored the ascii codes
the ascii corresponding to
codes corresponding to 22
and
and the
the Enter
Enter keykey (( carriage
carriage return)
return ) temporarily.
temporarily. Then
Then the
the first
first
scanf(
~aDf( )) picked
picked up up the
the 2,2, as when an
as when an integer
integer isis to
to be
be read,
read,
whatever
whatever is typed prior
is typed prior toto hitting Enter is
hitting Enter is treated
treated as
as data.
data. Thus
Thus
13,
13, the ascii code
the ascii code of
of Enter
Enter still
still persisted
persisted inin the
the buffer.
buffer. Had
Had wewe
not said fflush (stdin ), the next scanf() would
not said mush ( StdiD ), the next ~aDf( ) would have picked have picked
up
up this
this 13
13 as the character
as the character to to be
be read,
read, and
and not
not given
given us
us aa chance
chance
to
to enter
enter aa character. Thus, by
character. Thus, by using
using mush()
fflush() the
the contents
contents ofof the
the
buffer
buffer are
are first
first flushed
flushed out,
out, so
so that
that the second ~aDf()
the second scanf() waits for
waits for
us to type a character.
us to type a character.

(9)
(9) Output
Output

sentence
Enter a sentence
Nothing succeeds like success.
Nothing succeeds success.
Nothing
Nothing
Enter a sentence
sentence
Nothing succeeds
Nothing success.
succeeds like success.
Nothing succeeds
Nothing success.
succeeds like success.

Explanation
Explanation

The scaDf()
The scanf() suffers
suffers from
from the
the limitation
limitation that
that aa maximum
maximum of only
of only
one word can
one word can bebe accepted
accepted by it. The
by it. moment aa space
The moment space ((oror aa tab
tab
or aa newline
or newline )) isis typed,
typed, seaDf(
scanf()) assumes
assumes you you have
have finished
finished
supplying information,
supplying information, and hence ignores
and hence whatever follows.
ignores whatever follows.
That's why,
That's why, strl[
str1[] ] stores
stores only
only "Nothing",
"Nothing", as as is
is proved
proved by by the
the
first output. To
first output. To overcome
overcome this this limitation,
limitation, wewe have
have an an unfor-
unfor-
matted console I/O
matted console I/O function
function called
called gets(
gets(). It accepts
).It accepts whatever
whatever
you type
you from the
type from keyboard till
the keyboard the Enter
till the Enter keykey isis hit. To be
hit. To be
precise, gets()
precise, gets( ) accepts
accepts everything
everything until a '\n' '\0' is encountered,
encountered,
which
which it it replaces
replaces withwith aa '\0'.
'\0'. Thus
Thus thethe entire
entire string
string that
that wewe
. entered
entered is is obtained
obtained in in the
the second
second output.
output.
Input
Input and
and Output
Output in
in C
C 457
457

As in the previous program, fflush(


mush( )) flushes
flushes out the
the current
keyboard buffer contents. If
If not used, the Enter key
key present
present in
the keyboard buffer would be read by gets().
gets( ). Since gets()
gets( ) is
is
terminated on reading an Enter key, you won't get a chance to
supply
supply the
the second
second sentence.
sentence.

(10) Output
Output

Enter your name and surname


surname
Jaspal
Jaspal Bhatti
Bhatti
Jaspal
Jaspal Bhatti
Bhatti
Jaspal Bhatti f5+yP-fdfG
Jaspal Bhatti /5+yP~/dfG
Explanation
Explanation
gets( ) and puts(
puts( ) cannot take more than one argument at aa
time. Though no error message is displayed, whatever is typed
before hitting Enter is accepted by the first
first argument name[
name] ],
and the second argument is simply ignored. Thus name[ name] ]
stores the name "Jaspal Bhatti" and sname
sname gets ignored in both
gets(
gets()) and puts().
puts(). That this is indeed so is proved by the output
of printf( ), which prints "Jaspal Bhatti" corresponding to
contents of name[ 1, and all garbage values for the string
nainel ],
sname[].
sname[].

(11) Output
(11) Output

Error message:
message: Undefined symbol FILE in function
function main

Explanation
Explanation

FILE is a structure that is defined in the header file "stdio.h''.


FILE "stdio.h".
Hence, for using this structure, including "stdio.h" is a must.
Saying ## include
include "stdio.h"
"stdio.h" before main()
main( ) would eliminate
the error.
error.
458
458 Exploring C
Exploring

. (12)
(12) Output
Output

No output
No output

Explanation
Explanation

fp has
fp has been
been declared
declared as as aa pointer
pointer to to aa structure
structure called FILE
called FILE
which has
which has been
been defined
defined in in the
the header
header file
file "stdio.h".
"stdio.h". For Foraccess-
access-
ing
ing any
any file,
file, we
we must
must first
first open the file
open the file in
in the
the proper
proper mode
mode using
using
fopen( ). We
fopeD(). could easily
We could easily have
have said
said fopeD
fopen (( "ENGINE.C",
"ENGINE.C",
"w"
"w" )) as
as "E~GINE.C"
"ENGINE.C" is is the
the name
name of of the
the file we want
file we want to to open
open
in write mode. However, saying fopen (
in write mode.However, saying fopeD (strcpy (str, "EN- strcpy ( str, "EN-
GINE.C"),
GINE.C "), "w")"w") isis another, though roundabout
another, though roundabout way way of of saying
saying
the same thing.
the same thing, strcpy(
strcpy ( )) returns
returns the
the base
base address
address of of the
the string
string
str[
str[ ], into which
], into which "ENGINE.C"
"ENGINE.C" has has been
been copied. The same
copied. The same is is
passed as argument to the function fopen(),
passed as argument to the function fOpeD(), and "ENGINE.e"and "ENGINE.C"
gets
gets opened
opened in in write
write mode.
mode. WhatWhat we want to
we want to convey
convey is is that
that
fopen()) needs
fopeD( needs aa pointer.
pointer, toto the
the name
name of of the
the file
file we
we want
want itit to
to
open. How we supply the same is entirely our
open. How we supply the same is entirely our prerogative. prerogative.

(13) Output
(13) Output

Its a round,·
round, round,
round, round
round world!
world!
round, round,
Its a round, round, round
round world!
world!

Explanation
Explanation

In the
In the while
while loop,
loop, fgets(
fgets( )) reads
reads aa: string
string of
of 80
80 characters front
characters from
the file indicated
the file indicated by by fp,
fp, and
and returns
returns aa pointer
pointer to
to the
the string
string it
it
read.
read. If it
it fails
fails to read aa string,
to read string, as
as would
would bebe the
the case
case when
when the
the
end
end of
of file
file is
is reached,
reached, itit returns
returns aa NUlL,
NULL, notnot EOF.
EOF. Hence,
Hence, wewe
must
must compare
compare the returns of
the returns of fgets( with NUlL
fgets( )) with NULL and not EOF,
and not EOF,
Input
Input and
and Output
Output in
in CC 459
459

as
as the
the latter
latter is
is never
never going
going to
to be
be returned.
returned. Thus
Thus the
the loop
loop is
is an
an
indefinite
indefinite one.
one.

(14) Output
Output

. Error
Error message:
message: Null
Null pointer
pointer assignment
assignment

Explanation
Explanation

Try
Try opening
opening any any file
file using
using this
this program
program andand the
the output
output would
would
always
always be be thethe same:
same: "Null"Null pointer
pointer assignment
assignment".'. InIn the
1
the ifif
condition,
condition, instead
instead of of comparing
comparing fp fp and
and NULL, what the
NULL, what single
the single
=
= does
does is
is assign
assign NULL
NUIL to to fp.
fp. Replacing
Replacing the the =
~ with
with the
the com-
com-
parison
parison operator ==
operator == would would eliminate
eliminate the the bug. On removing
bug. On removing thethe
bug,
bug. die
the program
program wouldwould readread the
the file
file character
character by
by character till
character till
the
the end
end of of file
file is
is reached.
reached. EaehEach character
character read
read would
would bebe
displayed
displayed on on the
the screen
screen using
using the
the function
function putch(
putch( ).
).

(15) Output
Output

No
No output
output

Explanation
Explanation

Though
Though you you won't
won't getget any
any message
message here, what you
here, what you aimed
aimed to to .
do
do has
has not
not been
been done.
done. Having
Having openedopened the the three
three files
files through
through
calls
calls to
to fopen(),
fopeR(), fclose()
fclose() goes
goes to work. klose()
to work. fclose() can
can close
close only
only
one
one file
file at
at a
a time.
time. So after taking
Soafter taking fs, Cs, the
the first
first argument
argument in in line,
line,
it
it paid
paid nono attention
attention to to the
the remaining
remaining two. two. Thus
Thus onlyonlythethe file
file
"A.C"
"AC" gets gets closed,
closed, while
while files
files ".B.C"
'tltC" and
and "C.C
"C.C'· remain
remain open.
open.
For
For closing
closing thethe three
three files,
files, wewe must
must call
call fclose(
fcloseO) three
three times.
times ..
If
If we
we wish
wish toto close
close all
all the
the files
files through
through oneone call,
call, we
we can
can make
make
use
use of
of aa function
function called
called fcloscall().
fcloseaDO. This This closes
closes all the files
allthe files that
th~t
are
are currently
currently open,
open, except
except the the standard
standard files
files like
like stdin, stdout,
stdiD, stdout,
etc.
460
460 Exploring C
Exploring C

(16) Output
(16) Output

Enter name and age


Raj 18
Raj18
Raj 18
Raj18
Enter name and age
Sonia 21
Sonia
Sonia21
Sonia 21

Explanation
Explanation

Here the
Here the first
first set
set of
of statements
statements comprising
comprising of
of printf(
printf( )s)s and
and
scanf() is
seanfO fairly sim
is fairly simple. The fseanf()
pie. The fscanf() and
and fprintf(
fpriDtf() ) that follow
that follow
next need
next need some explaining.
some explaining.

fscanf(),), like
fseaDf( like seanf(
scanf(), is used
), is used for
for formatted
formatted reading
reading of of data.
data.
The only
The only difference
difference is is that
that the
the former
former takes
takes an an additional
additional
argument, that
argument, that of of aa file
file pointer.
pointer. This
This pointer indicates to
pointer indicates to the
the
fscanf()) from
fseanf( from where
where the the data is to
data is to be
be read,
read, whereas
whereas scaDf(scanf()) is is
capable of
capable of reading
reading data data only
only from
from thethe keyboard.
keyboard. In In the
the call
call to
to
fscanf() the
fseanf() the file pointer stdiD.
file pointer stdin isis being
being used,which
used,which stands stands forfor
standard input
standard input device,
device, i.e.i.e, th;
the keyboard.
keyboard. Since
Since stdin
stdiD.is is aa pointer
pointer
to a standard file, we do not need to use fopen()
to a standard file, we do not need to use fopen( ) to open it, to open it, as
as
it is
it is always
always open open for for reading.
reading. The The counterpart
counterpart of of fscanf(
fseanf( )) is is
fprintf().
fprintf( It too
). It too needs
needs aa filefile pointer
pointer as as its
its first
first argument.
argument. Here Here
the
the file pointer used
file pointer used is is stdo,ut,
stdout, which
which stands
stands for
for standard
standard outputoutput
device, i.e. the display monitor. Thus, using
device, i.e. the display monitor. Thus, using stdiD. in fseanf() stdin in fscanf()
and stdout in
and stdout in fprintf(
fprintf( )) makesmakes themthem work
work like
like the familiar
the familiar
scanf( )) and
seanf( and printf()
printf( ) functions.
functions. Hence
Hence bothboth the
the sets
sets collect
collect the
the
names and ages from the keyboard
names and ages from the keyboard and output them on the and output them on the
screen.
screen .

(17)
.(17) Output
Output

Sandeep 1500
Sandeep 1500
Input
Input and
and Output
Output in
in CC 461
461

Explanation
Explanation

fprintf(), like its counterpart fscanf(),


fprintf( ),like fscanf( ), requires as as one of
of its
its
arguments
arguments aa file
file pointer.
pointer. The
The argument
argument sent
sent here
here isis stdout,
stdout,
which
which signifies
signifies the
the standard
standard output
output device,
device, i.e.
i.e. the
the VDU.
VDU. As As
standard
standard devices
devices are
are always
always open,
open, we
we can
can access
access them
them without
without
calling
calling fopen().
fopen( ). name[
name[] ] and
and salary
salary are
are initialised
initialised in
in main()
main( )
to
to store
store "Sandeep"
"Sandeep" andand 1500.
1500. Both
Both the
the printf()
print(( ) and fprintf())
and fprintf(
thus
thus send
send the
the output
output toto the
the screen,
screen, and
and we
we have
have "Sandeep"
"Sandeep" andand
1500 printed onto the screen both
1500 printed onto the screen both ways. ways.

(18) Output
(18) Output

m
TTT
rrr
iii
PPP
III
eee
tit
ttt

Explanation
Explanation

The three statements


statements within the while loop do the same job, jdb,
i.e. to put the value at address contained in s onto the screen. "

What
What differs
differs is
is how
how their
their arguments
arguments are are specified. putc(),
specified. putc( ),
unlike
unlike fputchar()
fputchar( ) andand printf(),
printf( ), allows
allows youyou to
to specify where
specify where
the
the character
character isis to
to be
be put.
put. Here,
Here, stdout
stdout indicates
indicates the screen,
the screen,
hence
hence the
the output
output of
of putc()
putc( ) isis sent
sent to the screen.
to .the fputchar())
screen. fputchar(
and
and printf()
printf( ) are
are programmed
programmed to to write
write to to the
the scrt
sere en
en alone,
alone,
hence
hence our
our output
output shows
shows thethe triplets.
triplets.

(19) Output
(19) Output

1
J

J I
462
462 Exploring C
Exploring

C:\PROBJ=XE
C:\PROB~E

Explanation
Explanation

Having made an executable


executable file PROB.EXE,
PROB.EXE, we run this
program by
program by saying' PROB.EXE' at
saying 'PROB.EXE' at the
the DOS
DOS prompt.
prompt. Since
Since wewe
only mention one string, argc, the command
only mention ·one string, argc, the command line variable line variable
collects
collects aa 1.
1. The
The other
other argument
argument to to maine
main(), argv[ ),
), argv[ ], collects
collects
the pointer to
the pointer to this
this string.
string. Through
Through the the program,
program, argc
argc onon print-
print-
ing gives the
ing gives the 11 stored
stored in
in it.
it. The
The next
next printf(
printf()) prints
prints out
out the
the
string at the address contained in argv[0]. Since this
string at the address contained in argv[O). Since this address address
is the address
is the address of of the
the name
name of the file
of the file along
along with
with its
its path,
path, this
this
string is printed
string is printed out.
out.

(20) Output
(20) Output

1
C:\PROB.EXE
C:\PR0B.EXE
Explanation
Explanation
argc and argv
argc and argv are
are commonly
commonly usedused variable
variable names
names assigned
assigned to
to
collect the
collect the command
command line arguments. Here
line arguments. Here we
we have
have given
given the
the
variable
variable names
names asas xx and
and y,
y, still
still we
we get
get the
the same
same result
result as
as with
with
argc and argv. Hardly surprising, as Shakespeare pointed out
argc and argv. Hardly surprising, as Shakespeare pointed out
ages ago, what's
what's there in a name!
name!

(21) Output
(21) Output

C:\PR.EXE
CAT
DOG
PARROT

Explanation
Explanation
Input and
and Output
Output in C
C 463
463

At the
At DOS prompt,
the DOS prompt, four
four strings,
strings, PR.EXE,
PR.EXE, CAT,
CAT, DOGDOG andand
PARROT
PARROT are are passed
passed toto lBaiD(
main(). The base
). The base addresses
addresses ofof these
these
strings are
strings are collected
collected in
in the
the array
array of
of pointers
pointers to
to strings, argv[].
strings, argv[ J.
Hence
Hence inin the for loop
the for loop onon printing
printing the
the value
value at
at the addresses
the addresses
stored in argv[
stored in ], we
argv[ ], we get
get the
the strings
strings mentioned
mentioned at at the DOS
the DOS
prompt.
prompt.

((22)
2 2 ) Output
Output

Appears on
Appears on the printer:
the printer:

zZebraZebraZebra
zZebraZebraZebra

Explanation
~xplanation

This program assumes that you have a printer connected to


your machine. The
your machine. The argument
argument stdpra stdprn is is passed
passed to to all
all the
the four
four
functions used
functions used inin the
the program,
program, indicating
indicating thatthat the
the output
output should
should
be directed
be directed to to the
the printer.
printer. With
With the printf(), we
the printf(), we have
have nono option
option
but
but to to write
write to the screen.
to the screen. ThisThis limitation
limitation is is not
not encountered
encountered
with putc(),
with putt( fprintfX ),
), fpnatf( ), fwrite(
fwrite()) and and fputs(
fputs( ). ). putt(
putc( )) takes
takes as-
as •
its
its argument
argument aa character
character and and prints
prints 'z'
V onto
onto thethe screen.
screen. Aftel,'
After
this
this the fprintf() prints
the fprintf() prints the
the string
string "Zebra",
"Zebra", the the base
base address
address ofof
which
which has has been
been passed
passed to to it.
it. The
The function
function fwrite()
fwrite() alsoalso outputs
outputs
the string to
the string to the
the printer.
printer. ToTo fwrite()
fwrite() we we supply
supply the the base address
base address
of
of the
the string
string to be written,
to be written, the the number
number of of characters
characters to be
to be
written ( from base address onwards ), the
written ( from base address onwards ), the .numberof times the number of times the
string
string is is to
to be
be written
written and
and thethe device
device (( stdpnlln
stdprn in this this case
case )) to
to
which
which it it is
is to
to be
be written.
written. Lastly
Lastly fputs(
fputs( )) also
also outputs
outputs the string
the string
to the printer.
to the printer. Moral
Moral is,is, in
in all
all these
these functions
functions which which are used
are used
normally to write to a file, if the file pointer
normally to write to a file, if the file pointer is replaced by is replaced by
stdprn,
stdprn, the the output
output would
would be be directed
directed to to the printer.
the printer.

(23) Output
(23) Output

No output
No output on screen
on screen
464
464 Exploring C
Exploring

Explanation
Explanation

. The file "TRIAL"


The file "TRIAL" has has been
been opened
opened in in write-binary
write-binary modemode by by
the fopen(
the fopen() ) function.
function. Once
Once opened,
opened, the the fwrite(
fwrite( )s)s write the
write the
contents
contents of of aa structure
structure and
and aa string
string into
into it.
it. This
This highlights
highlights the the
fact that fwrite(
fact that fwrite( )) is
is not
not only capable of
only capable of writing
writing structures,
structures, butbut
strings
strings as as well.
well. All
All that you have
that you have to provide to
to provide to it
it is
is the
the base
base
address
address of of the
the data
data to
to be
be written,
written, the
the number
number of of bytes
bytes (( from
from
the
the base address onwards)
base address onwards ) to to be
be written,
written, number
number of of times
times it is
it is
to be written and the file to which it is to be
to be written and the file to which it is to be written. written.

Answers to [8]
Answers to [B]

(1)
(1) (a)
00

getch( )) is
getch( is the
the answer,
answer, asas of
of the
the four
four it
it is
is the
the only
only one
one that
that does
does
not echo
not echo thethe typed
typed character.
character. TheThe functions
functions getche(
getche( )) and and
fgetchar(),
fgetchar( ), as
as well
well as
as the
the macro
macro getchar(),
getchar( ), all
all print
print the typed
the typed
character on
character on thethe screen.
screen. getchar(
getchar( )) and
and fgetchar(
fgetchar( )) suffer
suffer from
from
_one more restriction. While using them, having entered aa
one more restriction. While using them, having entered
character, it
character, it has to be
has to be followed
followed byby hitting
hitting the
the Enter
Enter key.
key. But
But
for these
for these subtle
subtle differences
differences the
the working
working of of all
all the
the four func-
four func-
tions/macro is
tions/macro same.
is same. -

(2)
(2) (c)

putc( )) and
putc( fprintf( )) are
and fprintf( are text
text mode
mode functions.
functions. In In text
text mode,
mode,
the numbers
the numbers are
are stored
stored as as strings.
strings. For
For instance,
instance, 20000,
20000, anan int,
int,
which occupies
which occupies twotwo bytes
bytes in in memory,
memory, would would be be treated
treated as
as aa
string of
string of characters
characters '2',
' 2 ' , '0',
'0', '0',
'0', '0'
' 0 ' and
and '0'.
'0'. Naturally,
Naturally, this
this
would occupy
would occupy five bytes in
five bytes in the
the file,
file, one
one forfor each
each character.
character.
Thus, three
Thus, three bytes
bytes would
would be be wasted
wasted in in storing
storing aa two
two byte
byte
number. On
number, On the
the other
other hand,
hand, fwrite(
(write() ) isis aa binary
binary mode
mode function
function
which writes
which writes numbers
numbers the the wayway they appear in
they appear in memory.-
memory. ThatThat
is, 20000
is, would be
20000 would be allotted
allotted two two bytes while being
bytes while being stored
stored in
in aa
Input and
and Output
Output in C 465
465

file using
file fwrite(). The
using fwrite(). The saving
saving of
of bytes
bytes brought
brought about
about by using
by using
fwrite() hence justifies
fwrite( ) hence justifies our
our choice.
choice.

((3)
3) (b)

fseek( )) allows
Iseek( allows us us to
to position
position the
the file pointer at
file pointer at the
the beginning
beginning
of the
of the file,
file, at the end of
at the-end of file
file or
or at
at any
any other
other intermediate position
intermediate position
which we
which we specify.
specify. This
This facility
facility however
however is is not
not available
available with
with
rewind(
rewind(),), which
which cancan position
position the pointer only
the pointer only at
at the
the beginning
beginning
of the
of file.The function
the file.The function ftell(
fteD( )) is
is of
of no
no use
use here,
here, as
as all
all it does
it does
is to return the current position of the file pointer that
is to return the current position of the file pointer that is sent is sent
as its
as its argument.
argument.

(4)
(4) (a),(b);(c)
(a), (b): (c)

Whenever an
Whenever an existing file is
existing file is opened
opened inin any
any of
of the
the first three
first three
modes, it
modes, it is first erased
is first erased completely
completely andand then
then the blank file
the blank is
file is
made available for writing. Hence care should be taken
made available for writing. Hence care should be taken to use to use
"w", "wb"
"w", "wb" and
and "wb+"
"wb+" only
only when
when wewe want
want to
to create
create aa new
new filefile
or when
or when we can afford
we can to loose
afford to loose the
the contents
contents of
of the
the existing
existing file.
file.

(5)
(5) (c)

getc( ) can
getc() can read
read only
only one
one character
character at at aa time
time from
from aa file.
file. So
So it
it
doesn't serve
doesn't serve anyany useful
useful purpose heresince we
purpose here-since want to
we want read
to read
the file
the file contents
contents record
record byby record.
record. gets()
gets() is is still
still less
less useful
useful since
since
it accepts
it accepts aa string
string from
from the
the keyboard
keyboard and and notnot from
from the
the file.
file.
fgets( )) would
fgets( would certainly
certainly allow
allow us to read
us to read as as many bytes as
many bytes as we
we
specify, but would hardly prove to be ideal. In
specify, but would hardly prove to be ideal. In a record we may a record we may
have an
have an int,
int, aa char,
char, aa string,
string, etc.,
etc., and
and mind
mind you you allall these
these would
would
be read
be read byby fgets(
fgets( )) as
as one
one single
single string
string of of asas many characters
many characters
as the
as the record
record comprises
comprises of. of. And
And once
once thethe entire
entire record
record isis read
read
as a string, separation of different fields of the
as a string, separation of different fields of the record from the record from the
string would
string would be be aa difficult
difficult task.
task. Hence
Hence fread(frcad()) is is the.
the best
best I
choice, since
choice, since it it allows
allows reading
reading of of aa file record by
file record by record.
record. I ..
I
Moreover, nothing
Moreover, nothing special
special has to be
has to be done
done to to segregate
segregate the the fields
fields
of the record once it has been
of the record once it has been read. read.
I II
I[
466
466 Exploring C
Exploring C
A

Solutions to
Solutions to [C]

(1)
(1) Program
Program

#include "stdiah"
#include "stdio.h"
main (argc, argv))
( argc, argv
argc;
int argc;
char*argv[];
char *argv[] ;
{{
char ch1
ch1,, ch2, source(30),
source[30], target(30)
target[30];;
FILE *fs,
FILE*fs,*ft;*ft ;

ifif(argc!=3)
(argc != 3 )
{
printf ("Enter
( "Enter source
source and target
target filenames
filenames * ) ; I ) ;

scanf (("%s
scant "%5 %s",
%5", source, target);;
source, target)
}
else
{
strcpy ((source,
strcpy argvfl]);;
source, argv(1))
strcpy (target,
strcpy argv[2]);;
( target, argv(2))
}

ifrf ( ((ffss = fopen


fopen ((source, V ) ))===
source, "r") = NULL)
NULL)
{
printf (("\nCannot
printf "\nCannot open
open source
source file... Press any key')
key");;
getch();
getch() ;
exit ( 1 ) ;
exR(1);
}
ifif (( ((1t
f t = fopen (target, V
fopen (target, "w")) ))===
= NULL)
NULL)
{
printf (("\nCannot
"\nCanrld open
open target
target file...
file ... Press any key")
key");;
•• getch();
getch();
fctose(fs);
fdose (fs);
exit ( 2 ) ;
ed(2);
}}
Input
Input and
and Output
Output in
in CC 467
467

while
while ((((ch1
c h l ==getc(fs))
getc(fs) ) !=EOF)
!= EOF)
{{
(ch1 ==== T'f))
ifif (chl
{
{
=
if ( ( ch2 getc( fs ) ) == ,*, )
if ( ( c h 2 = getc(fs ) ) = = * )
{
{ while (1)
while
{ (1)
{ if ( ( ch1 = getc ( fs ) ) == '*' )
if{ ( ( c h l = g e t c ( f s ) ) = = * • )
if ( (ch1 = gete ( fs } ) == 'f)
{
break ;
rf((ch1=getc(fs))== n ,

}
break;
}
}
}
}
else
J
{
else
putc ( ch11ft) ;
{ putc ( ch2, ft) ;
} putc ( c h l , f t ) ;
} putc(ch2,ft);
elSe }
} pute ( ch1, ft) ;
} else
putc ( c h l , f t ) ;
printf ( "\nOone!! Press any key...• ) ;
}
getch() ;
printf ("\nDone!! Press any key...") ;
fclose ( fs ) ;
getch();
fclose ( ft) ;
fclose(fs);
} fclose ( f t ) ;
}
Explanation
Explanation

The program starts by


by checking whether the user has entered
the right number of arguments or not. argc,
arge, as we know,
collects the number of strings passed to main(
main( ) at the OOS
DOS \

i
I
468
468 Exploring C
Exploring

prompt. Comparing the contents of argc with 3,


prompt. Comparing 3, the right
number of arguments,
number arguments, we first ensure
ensure that the proper
tharthe proper
parameters have been specified. Since argv[]
parameters argv[] contains the base
base
addresses of the
addresses of the passed
passed strings,
strings, we
we store
store the
the source
source and
and target
target
file
file names
names in
in source and
and target respectively.
target respectively.

Having opened the file successfully with fopen(), fopen( ), we come to


the actual logic of segregating
segregating comments,
comments. The while loop first
searches for the character'/'
searches characterV which marks the beginning beginning of any
comment.
comment. If If a'/,
a V is collected in
is collected in chl, the next
chI, the next character
character from from
the
the file
file is
is collected
collected in in ch2
ch2 and
and checked
checked whether
whether it is aa ''*'.
it is *'. This
This
is done in order to verify that a comment is indeed
is done in order to verify that a comment is indeed in the offing, in the offing,
and
and chI chl did
did notnot read
read aa solitary
solitary slash'/'
slash 7'.. Having
Having read
read n7*", the
1*", the
next
next two two ifs find when
ifs find when thethe ending"
ending " *VI" are
are encountered,
encountered, whilewhile
(( 1I )) ensures
ensures that that control
control remains
remains in in the
the loop
loop till
till this
this ending
ending
syntax of a comment is reached. Thus,
syntax of a comment is reached. Thus, though the characters though the characters
after
after "1*""/*" are
are read
read from
from thethe source
source file,
file, none
none get
get written
written intointo
the
the target
target file.
file. When
When the the end
end ofof the
the comment
comment is encountered,
is encountered,
the
the break
break takestakes the the control
control out
out of
of the
the inner
inner while
while loop. After
loop. After
this whatever is read from the source is written
this whatever is read from the source is written to the target file to the target file
as
as itit is,
is, till
till the
the next
next comment
comment is met with.
is met with.

(2)
(2) Program
Program

#include "stdio.h"

main (argc, argv)


( argc, argv)
argc;
int argc;
char *argv(] ;
char*argv[];
{{
FILE *fs,
"fs, *ft
*ft;;
int ch;
ch;
charsource[30], target[30];;
char source[30], target[30]

ifif ((argc
argc != 33 )
{{
Input and Output in C 469

printf ( "\nEnter source


printf ("\nEnter source and
andtarget
target filenames");
filenames I ) ;

scant ( "%5 %s", source,


scant ("%s %s", source, target);
target) ;
}}
else
else
{
{
strcpy (source, argv[1]) ;
strcpy (source, argv[1]);
strcpy (target, argv[2]) ;
} strcpy (target, argv[2]);
}

ifif ((( f( sfs==fopen


fopen (source,
( source, V"r")
) ) ) ==
== NULL)
NUll)
{{
printf ("Cannot
printf open source
( "Canna open source file...
file...Press
Press any
any kkey
ey'); I ) ;

getch()
getchj); ;
exn(1);
exit (1);
}
}
if ( ( ft = fopen ( source, -« )) == NUll)
if{ ( ( f t = fopen (source, V ) ) == NULL)
{ printf ( "Cannot open target file... Press any key" ) ;
printf
getchO;("Cannot open target file... Press any key");
getchf);
fclose ( fs ) ;
fclose
exit (2)( f s; ) ;
} exit ( 2 ) ;
}
while ((((cch
while h == ggetc
e t c ( ffss ) ))! =!= EOF)
EOF)
{{
ifif ((ceh
h >>= 128)
= 128)
pute ((ceh
putc h --1128,
2 8 , fft)t ) ;;
else
else
pute (ch,
putc ( ch, fft)t ) ;;
}}
printf ("\nDone!!
printf ( "\nDone!! Press
Press any
any key...");
key...• ) ;
geteh
getch(); () ;

fclose ( fs
fclose f s )) ;
fcJose (
fclose f t ) ;
ft
}
470
470 Exploring C
Exploring

Explanation
Explanation

The WordStar
The WordStar package
package has has its
its special
special way
way of of storing docu-
storing docu-
ments. It stores
ments.1t stores all the letters
all the letters of
of the
the word
word asas it
it is,
is, except
except for the
for the
last letter.
last letter. This
This letter
letter is
is given
given an an offset
offset of
of 128.
128. The
The ascii
ascii values
values
from 128
from 128 toto 255
255 correspond
correspond to to graphic characters, hence
graphic characters, hence thethe
last letter
last letter ofof each
each word
word appears
appears as as aa graphic
graphic character. Thus,
character. Thus,
to convert
to convert aa WordStar
WordStar file file to
to an
an ordinary
ordinary text
text file,
file, all
all we
we need
need
to do
to do is
is restore
restore all
all the
the last
last letters
letters to
to their
their original
original values.
values. In In our
our
program, whenever
program, whenever we we encounter
encounter aa graphic
graphic character,
character, i.e.
i.e. one
one
having an ascii
havingan ascii value
value more
more than
than 127,
127, wewe subtract
subtract 128128 from
from itit
and arrive
and arrive atat the
the character which must
character which must actually
actually bebe present there.
present there.
r

12
II
!.llii

Bits and Pieces


B
y y now
now we we have
have dealt
dealt with
with most
most ofof the
the mainstream
mainstream C. C.

B
applications
However,
However, there
you
you can
can go
applications right
there are
go full
right from
are still
still aa few
full steam
steam ahead
from interacting
few loose
loose ends
ahead and
interacting with
ends to
and use
with the
use C
to be
be tied
C for
the hardware
tied up before
up before
for aa variety
hardware to
variety of
of
designing
to designing
sophisticated
sophisticated software.
software. This
This chapter
chapter gives
gives the
the finishing
finishing strokes with
strokes with
aa brief
brief discussion
discussion onon bitwise
bitwise operators,
operators, enumerated
enumerated datatypes,
datatypes, bit
bit
fields, typecasting, the
fields, typecasting, the typedef
typedef keyword
keyword etc.
etc. Let
Let usus examine them
examine them
one
one by one.
by one.

Bitwise Operators
Bitwise Operators

Programming languages
Programming languages are byte oriented.
oriented. But for getting down to
the
the machine
machine level,
level, i.e.
i.e. for
for interaction
interaction with
with the
the hardware,
hardware, wewe must
must bebe
able
able to access the individual bits of a byte. We do so with the help of
to access the individual bits of a byte. We do so with the help of
Bitwise operators. These
Bitwise operators. These operators
operators allow
allow usus to
to manipulate
manipulate thethe in-
in-
dividual bits of
dividual bits of aa byte.
byte. There
There are
are several
several bitwise
bitwise operators available
operators available
in C. Figure
in C. 12.1 shows
Figure 12.1 shows these
these bitwise
bitwise operators,
operators, and
and how
how they
they are
are put
put
to work. Starting with any two 8 bit numbers, say a
to work. Starting with any two 8 bit numbers, say a equal to 0100equal to 0100
1011
1011 ((decimal
decimal 7575 )) and
and bb equal
equal to 1011 0010
to 1011 0010 (decimal
( decimal 178),
178 ), we
we
examine
examine howhow the
the bitwise
bitwise operators function. We
operators function. use aa variable
We use variable cc for
for
collecting the results
collecting the results of
of our operations.
our operations.
Bits and
Bits and Pieces
Pieces. 473
473

Left shift operator


operator ( «« ) Right shift operator ( » )
Right shift operator ( » )
cc =a«
= a « 11 cc =b»
= b » 11
= 1001 0110
= 1001 0110 ((150 decimal)
150 decimal) = 01011001
= 01011001 ((89 decimal)
89 decimal)
cc =a«
= a « 22 cc =b
= b »2
» 2
= 00101100(44
= 00101100 decimal)
(44 decimal) = 00101100 ((44
= 00101100 decimal)
44 decimal)
cc =a«
= a « 33 cc =b
= b »3
» 3
= 01011000 (( 888
= 01011000 8 decimal)
decimal) = 00010110 (22
= 00010110 (22 decimal)
decimal)

Truth Table
Truth Table for
for Truth Table
Truth Table for
for Truth Table
Truth Table
AND operator OR operator forXOR
forXOR
ooperator
perator
& 00 11 1I 00 11 A
" 00 11
00 0 00 00 00 11 00 00 11
11 00 11 11 11 11 11 11 00

Working of
Working Bitwise AND,
of Bitwise AND, OR
OR and
and XOR
XOR operators
operators

cc=a&b
= a St b =aa I| bb
cc = cc=a"b
=a b A

aa 01001011 aa 01001011
01001011 aa 01001011
01001011
bb 10110010
10110010 bb 10110010
10110010 bb 10110010
10110010

Figure 12.1 Bitwise


Figure 12.1 Bitwise Operators
Operators

Follow the figure carefully. On left shifting, all the bits are moved
one position
one position toto the left, and
the left, on right
and on right shifting,
shifting, to the right,
to the right, with
with zeroes
zeroes
being placed wherever
being placed wherever spaces
spaces are
are created
created on
on shifting
shifting of bits. Note
of bits. Note
that on left shifting a once, it gets multiplied by 2, and by right shifting
that on left shifting a once, it gets multiplied by 2, and by right shifting
bb once,
once, it
it gets
gets divided
divided by by 2.
2. Thus
Thus cc stores
stores decimal
decimal 150150 and decimal
and decimal
89
89 as
as aa result
result ofof the
the operations
operations aa «« 11 andand bb »» 11 respectively.
respectively.
474
474 Exploring C
Exploring C

However, this is not necessarily true always.


always. This
'ibis effect is seen only
when no significant Is shifting.
ls are lost as a result of bit shifting.

The functioning of bitwise AND, OR and XOR ( exclusive OR OR)) can


be easily grasped from
from the truth tables given in the figure.

Another bitwise operator is the one's


one's complement operator, which is
denoted
denoted as ~.-. On applying this to an operand it converts all zeroes
present 0100
present in the operand to ones and all ones to zeroes. Thus if a is 0100
1011,
1011, ~a
-a would yield 1011 0100.

As with arithmetic operators, the assignment operator can be used


with
with any
any ofof the bitwise operators to yield compound assignment
operators. The working of
.operators. of these^
these- bitwise compound assignment
assignment
operators similar
operators is similar to the
the usual compound assignment operators.
operators.
Thus
Thus the expression bb ==bb »» 22 is
the expression is same as &»=
same as fc^>= 2.
2. The
The other
other such
operators
operators are
are ««=,
= , |=,
1=,&=
&= and "=.

Enumerated
Enumerated Data Type

The
The use
use of
of this
this datatype
datatype is is essentially
essentially to to make
make programs
programs more
readable.
readable. ItItallows
allows you you to
to create
create your
your own
own datatype
datatype with
with predefined
values.
values. Though
Though its its form
fonn isis like
like that
that of
of aa structure,
structure, the
the values
values men-
men-
tioned within its braces do not indicate variables, but infact are
tioned within its braces do not indicate variables, but infact are
constant
constant values
values thatthat the
the enum
enum can can take.
take. For
For instance,
instance, aa program
program for
for
Railway
Railway reservations
reservations wouldwould do do well
well to
to have
have an
an enum,
enum, oror enumerated
datatype
datatype of
of the
the following
following form:

enum
enum rail
rail
{{
firstclass,
firstclass,
secondclass,
secondclass,
ac
ac
}}; ;
enum
enum rail
rail personl,
person1 person2;
person2 ;
t
Bit^
Bitf and
and Pieces
Pieces 475
475

Here firstclass, secondclass


Here 6rstcJass, secondclass and ac ae are called enumerators, which
are the
the values that the variable of of the type enum rail can can take. The
next statement declares that personpersenf1 and person2
personl are variables
variables of
of
the
the type
type enum
enum rail.
rail. These
These variables
variables cannot
cannot take
take values
values other
other than
than
firstclass,
firstclass, secondclass
secondc)ass and and ac.
ae. Internally,
Internally, these
these values
values are
are treated
Heatedasas
integers
integers byby the
the compiler.
compiler. Hence, firstclass is
Hence, firstclass is interpreted
interpreted as value 0,
as value 0,
secondclass
secondclass as value 11,, and
as value and ac as 2.
ae as 2. We
We can
can override
override these
these values
values by
by :
I:
'
.

saying
saying inin the declaration:
the declaration: I

enum
enum rail I
{{
firstclass=
firstclass = 20,
20,
secondclass == 30,
secondclass 30,
ac=40
ac = 40
};
};

or any numbers we want assigned.


assigned.

The enumerated
enumerated variables
variables suffer
suffer from
from one minor
minot weakness.
weakness.' The
enumerated
enumerated values cannot be used directly in input/output functions
like printf(
printf( ) and scanf(
scanf( ). This is because these functions
functions are not
understand that by 2200 you mean firstclass or
smart enough to understand OJ:' vice
versa. You would agree that this limitation is quite sensible.

Typedef
Typedef

Renaming datatypes
datatypes with this keyword is another facility which helps
facility.which
in making lengthy or complicated
complicated programs easier to understand. For
example,
example, look at the following statement:
statement:
II
typedef
typedef long
long double
double FF ;
I I
I'
I
Once this is done we can use the sweet and simple F wherever we
F'wherever
intend
intend to
to use
use long
long double.
double. While
While declaring
declaring variables of this
variables-of this type,
type, we
we
can simply say,
476
476 Exploring
Exploring C

FFa,
a , bb,, cc;;

and a, b
and and ce would
band would be treated as
be treated as variables
variables of
of the
the type
type long
long double.
double.
This shortcut
This shortcut proves
proves very
very useful
useful when
when the
the names
names of of datatypes are
datatypes are
long and
long and unweildy.
unweildy.

Typecasting
Typecasting

Typecasting allows
Typecasting allows us us to
to explicitly
explicitly convert
convert the
the value
value of
of an expression
an expression
or aa variable
or variable to to aa particular
particular datatyne,
datatype. IfweIf we want
want the
the result
result of3
of 3 divided
divided
by 22 to
by be aa Ooat
to be float value,
value, wewe can
can achieve
achieve thisthis by
by saying
saying ((float) 3 / 2.
float) 3/2.
Of course,
Of course, promoting
promoting eithereitherJ 3 or
or 22 (( or
or both
both) ) to
to float by writing
Ooat by writing them
them
as 3.0
as 3.0 oror 2.0
2.0 would
would alsoalso serve
serve the
the same
same purpose.
purpose. ButBut there
there may
may bebe
instances when
instances when we we want
want toto use
use the
the value
value ofof the
the same
same variable
variable as as an
an
int at
int at aa few
few places
places andand asas aa float
float at
at others.
others. In
In such
such cases
cases typecasting
typecasting
is the
is the only solution.
only solution.

Bit Fields
Bit Fields

If aa variable
If variable is is to
to take
take only
only two
two values
values 1 loror 0,0, really
really speaking
speaking we we need
need
only aa single
only single bitbit toto store
store it.it. Likewise,
Likewise, if if aa variable
variable is is to
to take values
take values
from 00 to
from to 3, then two
3, then two bits are sufficient
bits are sufficient to store these
to store these values. Then
values. Then
why sacrifice
why sacrifice an an entire
entire integer
integerwhen when oneone or or two
two bits
bits would
would do? The
do? The
reason is
reason simple. C'
is simple. C doesn't
doesn't offer
offer anyanyone one or or two
two bit datatypes.
bit datatypes.
However, when
However, when therethere areare several
several variables
variables whosewhose maximum
maximum values values
are small
are small enough
enough to to pack
pack in in aa single
single byte,
byte, we we cancan use
use 'Bit Fields' to
'Bit Fields' to
store all
store all these
these values
values in in aa single
single byte.
byte. For
For example,
example, suppose
suppose there
there are
are
four variables
four variables a, a, b,
b, ce and
and d d such
such that
that aa can
can take
take anyone
any one of of the
the two
two
values 0 or 1, b can take any value between
values 0 or 1, b can take any value between 0 and 3, C can take any 0 and 3, c can take any
value
value between 0 and 7 and d can take any value between 0 and 15.
between 0 and 7 and d can take any value between 0 and 15.
This means
Tins means that that we we need
need onlyonly one
one bit
bit to
to store
store the
the value
value that
that a can
a can
take, two
take, two bits
bits to store the
to store the value
value of of b, three bits
b, three bits toto store
store the
the value
value ofof cc
and four
and four bits
bits to store the
to store the value
value of of d.
d. Thus
Thus we we need
need 10 10 bits
bits altogether,
altogether,
Bits
Bits and
and Pieces
Pieces 477
477

which
which means
means wewe can
can pack
pack all
all this
this information
information into
into aa single
single integer,
integer,
since
since an
an integer
integer is
is 16
16 bits
bits long.
long. How
How to to achieve
achieve this
this using
using bit
bit fields
fields
is
is shown
shown in
in the
the following
following program:
program:

main()
rnain( )
{{
struct nurn
struct num
{
{
unsigned a : 1 ;
unsigned a : 1 ;
unsigned b : 2 ;
unsigned b: 2;
unsigned c : 3 ;
unsigned c : 3 ;
unsigned d : 4 ;
unsigned d : 4 ;
};
};
struct nurn n ;
struct num n ;
n.a e c:
n.a = 0;
n.b=2;
n.b = 2;
n.c = 5;
n.c = 5;
n.d = 14;
n.d = 14;
printf ( "%d %d %d %d', n.a, n.b, n.c, n.d ) ;
printf ("%d %d %d %d", n.a, n.b, n.c, n.d);
}
}

Observe
Observe thethe declaration
declaration struct
struct num.num. TheThe colon
colon in in the
the declaration
declaration
tells
tells the
the compiler
compiler thatthat we
we are
are talking
talking about
about bitbit fields
fields and
and the
the number
number
after
after it
it tells
tells how
how manymany bits
bits to to allot
allot toto' the
the field.
field. Once
Once we we have
have
established bit fields we can reference them just like ordinary struc-
established bit fields we can reference them just like ordinary struc-
ture
ture elements
elements -- by
by using
using the
the' '.'.' operator.
operator.

Pointers
Pointers to Functions
to Functions
II
We
We have
have studied
studied about
about pointers
pointers toto chars,
ehars, ints,
ints, arrays,
arrays, etc.
etc. Such
Such
pointers
pointers contain
contain addresses
addresses of
of these
these entities,
entities, through
through which
which the entities
the entities
can
can be
be accessed.
accessed. Likewise,
Likewise, functions
functions too
too can
can be
be invoked
invoked using
using their
their
addresses.
addresses. That
That is,
is, we
we can
can have
have pointers
pointers toto functions.
functions. Just
Just like
like
mentioning
mentioning thethe name
name of
of an
an array
array gives
gives the
the base
base address
address ofof the
the array,
array,
478
478 Exploring C
Exploring C

mentioning the
mentioning the name the function
name of the function yields
yields the address
address of the func-
the func-
tion. Thus,
tion. Thus, the statement
the statement

printf (("%d", demo);;


"%d", demo)

would print
would print the
the address
address of
of the
the function demo().
function demo( ). SoTar,
So-far, for invoking
for invoking
aa function
function we
we have
have used
used its
its name.
name. The
The following
following program
program shows
shows how
how
aa point"
pointer can
can be
be used
used for
for calling
calling aa function
function demo(
demo().).

main(]
main{l
i
-{
intdemo() ;
intdemoO;
int
int ((*fpointer)
*fpointer) ()
();;

pointer ==demo;
ffpointer -demo;
(*fpointer) ()::
(*fpointer) ()
}}

In the
In program, we
the program, declare the
we declare the function
function as
as well
well as
as fpointer,
fpointer, aa pointer
pointer
to it.
to it. Having
Having stored the address
stored the address of
of ~mo(
demo()) in
in this
this pointer
pointer, we
we call the
call the
function with
function with the statement
the statement

(*fpointer)();
( *fpointer) () ;

Once the
Once the concept
concept ofof pointer
pointer to
to aa function
function is
is imbibed,
imbibed, it
it can
can be
be used
used
as liberally as
as liberally as the
the ordinary
ordinary char
char or
or int
int pointers.
pointers. For
For example,
exam pie, aa pointer
pointer
to aa function
to function can
can be
be passed
passed to
to another
another function,
function, stored in an
stored in an array,
array,
etc.
etc.
Bits
Bits and
and Pieces
Pieces 479
479

Exercise
Exercise

[A]
[AJ What
What will
will be
be the
the output
output of
of the
the following
following programs:
programs: I
I
(1)
(1) main()
main()
{{
int ii== 32,
int 32,jj = = 65,
65, kk;;
k=i!35;
k = i|35;
printf ("k
printf =
( ok = %d\n",k);
%d\n·, k) ;
= -k~k;;
kk =
printf
printf ("k( "k == %d\n",
%d\n·, k)k) ;
;
k =j &j;
k=i&i;
printf ( ok = %d\n", k) ;
printf ("k = %d\n",k);
}
}

(2)
(2) main()
main()
(f
inti 32,j == 65,
int i== 32,j 65, k;
k;
kk=j"32;
= j 32;
A

printf ( "k == %d\n",k);


printf("k %d\n·, k) ;
k = j « 2;
k=j«2;
printf ("k
( "k = %d\n",
%o'\n", kk)) ;;
k = i » 5;
k=i»5;
printf ( "k = %o'\n·,
printf("k %d\n",k);k) ;
}}

(3) main()
main()
{{
int a == 3,b
inta 3, b =
= 2,c
2, C =
= 1, d;
1,d;
d=aJb&c,
d = a|b&c,
printf ( "d == %d\n",d);
printf ("d %d\n", d) ;
dd=alb&-c;
= a | b & ~c;
orintf
orintf("d("d == %d\n·, d) ;
%d\n",d);
}}

J
480
480 Exploring
Exploring C
C

((4)
4) main()
main()
{{
Oxff;
int aa == Oxff;
int
if ( a « 4 » 12)
if(a«4» 12)
printf (("Leftist");
printf ·Leftist· ) ;
else
else
printf( ·Rightist· ) ;
printf"("Rightist");
}

(5) main()
main()
{{
int aa == 110;
int 0;
iif(a&8==8)
f(a&8==8)
printf ("Bit
printf ("Bit no.
no. 33 is
is on");
on") ;
else
else
printf ("3rd
printf ( "3 rd bit is otr
bit is o f f ) ;;
}

(6) main()
main( )
{{
int aa == 12,
int 12, ii == 00 ;;
w h i l e (aa»=
while ( » = i i))
{
{
printf ( 'a = %d.i = %d\n", a, i) ;
printf ("a = %d.i = %d\n", a, i ) ;
itt ;
i++;
}
} }

(7) main()
main()
{
{
int i == ++ 11 ;;
inti
while (-i)
while (~i)
printf ("vicious
printf ( "vicious circles\n");
circles\n") ;
}}

(8) main()
main()
Bits
Bits and
andPieces
Pieces 481
481

{{
= Oxao,bb==OxOa,
intaa= OxaO,
int Oxoa,c,c,dd; ;
cc=al
= a | bb;;
printf =
(·c = %%d·,
printf ("c d " , cc)) ; ;
d=a&b;
d=a&b;
printf ("d
printf =
("d = %d",
%d", dd)) ; ;
'}

( (9)
9) main()
main()
{{
enum code
enum code
{
{ add,
add,
delete,
delete,
modify,
modify,
unchanged
}; unchanged
}typedef
; enum code CODE;
typedef enum code CODE;
CODE c, d;
CODE c, d ;
c = add;
c = add;
=
d modify;
d = modify;
=
printf (HC %d d = %d', c, d) ;
printf ("c = % d d = % d " , c , d ) ;
}
• I"

((10)
10) main()
main()
{ I
{ !

enum status
enum status {low,
{ low, medium,
medium, high};
high} ; "

enum status
enum status rain;
rain ;
rain =
rain = 0 ; 0';
ifif (rain ==
( rain == low)
low)
printf ( "rain == %d",
printf ("rain rain) ;
%d", rain);
}

((11)
11) main()
main()
{
{
enum
enum status
status {low medium == 20, high
{ low == 10, medium high = 30}
3 0 } ;;

j
482
482 Exploring C
Exploring

enum status rain rain;;


medium;
rain = medium;
ifif ((rain = = 20
rain == 2 0 ))
rain++;
rain++ ;
printf ("rain
( ·rain = %d", rain);;
%d·, rain)
}}

((12)
12) main()
main()
{{
typedefstrud
typedef struct
{
{
char name[2O] ;
char name[20];
int age;
int age;
}a;
}a;
aaemp
emp == {·Sunil·, 3O} ;
{"Sunil",30};
printf
printf ("%s %d", emp.name, emp.age)
("%s %d·, emp.name, emp.age);;
}
}

((13)
13) main()
main()
{{
struct
struct address
address
{
{
char city[20] ;
charcity[20];
int pin;
int pin;
};
};
typedef *
struct address ADDR ;
typedef struct address * ADDR;
ADDR adcr.;
ADDR addr.;
static struct iaddress a = { •Jodhpur", 20 } ;
static struct address a = {"Jodhpur", 2 0 } ;
addr=
addr = &a;&a;
printf ( "%s %d",
printf ("%s %d·, addr->city,
addr->city, addr->pin)
addr->pin);;
}}

((14)
14) mainf)
maint)
{{
printf ("%f (float) ((int) ( (int)6.5/2 + 3.5 \H-
( (int) l( (float) ((int)6.5/2 ) - 3.5
3 . 5)))) ;
i
Bits and Pieces
Bits and Pieces 483
483

((15)
15) main()
main()
{
{
struct num
struct num
{
{
unsigned bitO: 1 ;
unsigned bitO: 1 ;
unsigned bitl : 1 ;
unsigned b i t 1 : 1 ;
unsigned bit2 : 1 ;
unsigned b i t 2 : 1 ;
unsigned rest : 5 ;
unsigned rest: 5 ;
};
};
union a
union
{ a
{ struct num n ;
struct
charch;num n ;
}b; charch;
}b.ch=32;
b;
b.ch = 3 2 ;
printf ("%d
.printf (·%d %d %d %d",
%d·, b.n.bitO, b.n.bitl, b.n.bit2,
b.n.bitO,b.n.bit1, b.n.rest);;
b.n;bit2, b.n.rest)
}}

((16)
1 6 ) main()
main()
{{
int show() ;
intshow();
int
« ( (1)()
* ) ( ) ;;
ff=show;
= show;
printf ("address
(·address == %d\n",
%d\n., f)f ) ;

}
my.
(*f)O;
}
show()
show()
{
{
printf ( ·Diamonds are forever" ) ;
printf ("Diamonds are forever");
}

((17)
1 7 ) ', main()
{{
int show();
show() ;
iint
n t (*f)O;
(*f)();

j
484
484 Exploring C
Exploring

f = show;
f=show;
display (( f)f ) ;;
}}
shl1tl(
showQ)
{
{
printf ( "On the rebound...
printf ('On the rebound...");
I ) ; .

}}
display
display ((ff)
ff )
int (*ff)() ;
int(*ff)();
{
{
(*!f)O;
(*ff)();
)}

((18)
18) main()
main()
{{
int i, fun1 (), fun2(),
int i,fun1(), fun3() ;
fun2(),fun3();
iint
n t (*1[3]
( * f l 3 ])()
) ( ) ;;
1[0]
ffl)] = fun1;;
= fun1
1[1]=
f[1] = fun2;
fun2;
1[2] =fun3;
f[2]=fun3;
for (( ii == 00 ;; ii <=
for 2; iff
<= 2; i++))
(*f[iJ)();
}
fun1()
fun1 ()
{
printf (( "Hail
" H a i l")" ) ;
}
fun2()
fun2()
{
printf (( ,he
" t h e•")) ;
}
fun3()
fun3()
{
printf (("viruses!");
"viruses'" ) ;
}

J
Bits and Pieces
Bits and Pieces 485
485

Answers
Answers

Answers to [Al
Answers to [A]

(1)
(1) Output
Output

= 35
kk=35
= -36
k =-36
kk=O
=0

Explanation
Explanation

Since ints
Since ints are
are being
being considered,
considered, allall the
the operations
operations are carried
are carried
out on
out on 16-bit
16-bit binary
binary numbers,
numbers. iistores
stores 32,
32, which
which is binary 0000
is binary 0000
0000 0010
0000 0010 0000.
0000. On On ORing
ORing itit with
with 35,
35, which
which is is binary 0000
binary 0000
0000 0010
0000 0010 0011,
0011, eacheach corresponding
corresponding pair pair of of bits
bits is compared,
is compared,
resulting in
resulting in 11ifif at
at least
least one
one of
of the
the pair
pair isis aa 1.
1.The
Theresult
resultisiseasily
easily
envisaged to
envisaged to be
be 35 itself.
35 itself.

The ~
The operator gives
- operator the one's
gives the one's complement
complement of of its
its operand.
operand. On
On
complementing k,
complementing k, which
which equals
equals 35,
35, the
the result
result isis 1111 1111
1111 1111
11011100. This
11011100. This number
number is equivalent to
is equivalent to decimal
decimal 65500,
65500, which
which
lies outside
lies outside the
the range
range of
of an
an into
int. Hence,
Hence, after
after +32767,
+32767, counting
counting
resumes at
resumes at -32768,
-32768, yielding
yielding -36.
-36.

Finally i,
Finally i, which
which is32,
is 32, on
on bitwise
bitwise ANDing
ANDing with
with 65
65 (binary
(binary 0000
0000
0000 0100 0001)
0000 0100 0001) results
results in
in aa zero.
zero. This
This is
is only
only natural,
natural, as 32
as 32
and 65
and 65 in
in their
their binary
binary forms
forms have
have no
no corresponding
corresponding pair of bits
pair of bits
as 1.
as 1.

(2)
(2) Output
Output

97
kk == 97
= 260
kk =260
486
486 Exploring
EWlorin,g C
C

=1
kk=1

Explanation
Explanation

The XOR
The XOR operator
operator" yields
A
yields aa 11 only
only if
if the
the 22 bits
bits being compared
being compared
are O'and 1,
are O-and 1, else
else aa 00 results.
results. Thus,
Thus, 6565 and
and 3232 yield
yield 97,
97, which
which is
is
binary 0000 0000
binary OO()O 0000 0110
0110 0001.
0001.

original value 65:


65: 0000
0000 0000
0000 0100 0001
0100 0001
mask 32:
32: 0000 0000
0000 0000 0010 0000
0000
new value 97:
97: 0000 0000 0110 0001
0000

The second printf(


printf()) prints the the value of k, which has has been
assigned the result
assigned the result ofj
of j left
left shifted
shifted twice,
twice.jj is
is 65,
65, i.e.
i.e. 0000 0000
00000000
0100 0001. On
0100 0001. On left
left shifting
shifting twice,
twice, zeroes
zeroes are
are appended
appended on on the
the
right
right and
and jj is
is transformed
transformed to 0000 0001
to 0000 0001 0000
0000 0100,
0100, which
which is
is
decimal 260.
decimal 260.

Lastly, i, containing
containing 32, is right
right shifted 5 times. The sequence
of how the 16 bits are manipulated
manipulated is:

32:
32: 0000000000100000
0000 0000 0010 0000
»
» 000000000001
0000 0000
0000 0001 0000
»» 0000 0000
0000 0000 0000
00001000
1000-
»» 0000000000000100
0000 0000 0000 0100
»» 0000 0000
0000 00000000 0010
0000 0010
»» 0000000000000001
0000 0000 0000 0001

After 55 right
After right shifts,
shifts, we
we get
get 1,
1, which is assigned
which is assigned to k.
to k,

(3)
(3) Output
Output

dd=3
=3
dd=3
=3
Bits
Bits and
and Pieces
Pieces 487
487

Explanation
Explanation

None of the bitwise operators


operators change the value of of the operands
they act on. On saying a |Ib && c, c, the result
result is 0000 0000 0000
0011, i.e. decimal 3, 3, which gets assigned to d. Note that bitwise
&& operator enjoys a higher priority than the |1 operator. When
& ....
aa]| b & ~cC is evaluated, b and cc are still 3,
evaluated, a, band 3,22and
and 1respectively.
1 respectively.
~c-c yields
yields 1111111111111110
1111111111111110 and and on
on ANDing
ANDing itit with
with 0000
0000
0000
0000 0000
0000 0010
0010 (( decimal
decimal 22 ),
), we
we get
get 0000
0000 0000
0000 0000
0000 0010.
0010.
- Finally,
Finally, ORing
ORing this
this result
result with
with 33 again
again yields
yields aa 3.
3.

(4) Output
Output

Rightist
Rightist

Explanation
Explanation

contains hex ff,


a contains ff, i.e. 00000000
0000 0000 1111 1111. Firstly the left
shifting operation is carried out, changing the 16 bits to 0000
1111 1111 0000. Following this, right shift shift is executed 12
times, so that the latter 3 nibbles ( a set of 4 bits is a nibble
nibble))
are pushed out, and as many zeroes crop up on the left. As the
2-byte number is now 0, the if condition fails and the printf(
printf())
of
of the
the else
else block
block gets executed.
gets executed.

(5)
(5) Output
Output

Bit
B~ no. 3 is on

Explanation
Explanation

In the binary equivalent of 8, only one bit is set to 1, which is


bit number 3. On ANDing with a, which contains 10 ((binarybinary
0000 0000 00001010 ), only bit number 3 is copied as it is. All
(000000000001010),
remaining bits are reset to 0, and for this reason 8 can be
remaining
488
488 Exploring
Exploring C .

referred to
referred to as
as aa mask.
mask. Hence
Hence the i f condition
the if condition reduces
reduces to to iiff (( 88
==
== 8 8).). This
This is
is satisfied,
satisfied, therefore
therefore we we get
get the
the output
output as 'Bit no.
as 'Bit no.
33 is
is on'.
on'. This
This simple
simple trick
trick ofof checking
checking whatwhat bits
bits are
are on
on (or
(or 11'))
is extremely
is useful in
extremely useful in aa variety
variety ofof applications
applications like calculating
like calculating
date and
date and time
time for
for every
every file
file in
in the
the directory,
directory, oror finding
finding out the
out the
current file
current attributes etc.
file attributes etc.

(6)
(6) Output
Output

= 12i = 0
aa=12i=O
a = 6i = 1
a=6i=1
aa=1
= 1 i=2
i=2

Explanation
Explanation

In the while
In the condition, aa is
while condition, is right shifted ii times
right shifted times and
and thethe result
result
is assigned
is assigned to to aa itself.
itself. ThusThus the condition aa »»== ij is
the condition is same
same as as aa
=
= aa »> > i.
i. First
First timetime through
through the loop, ii is
the loop, is 0, hence aa remains
0, hence remains
unchanged. Since
unchanged. Since aa is is non-zero,
non-zero, the the condition evaluates to
condition evaluates true
to true
and the
and p r i n t f ( ) gives
the printf() gives us us our
our first
first output.
output. The
The next
next time,
time, a, a, i.e,
i.e.
12 is
12 right shifted
is right shifted once, once, as as ii has
has now
now been
been incremented
incremented to to 1.1.12
12
in binary
in binary is 0000 0000
is 0000 0000 00001100.
0000 1100. On On right
right shifting
shifting thisthis by
by 1, 1,
we get
we get 0000
0000 0000 0000 0000 0000 0110,
0110, which
which is is decimal
decimal 6. 6. Note
Note thatthat ifif
no significant
no significant Is Is are
are lost
lost on
on right
right shifting
shifting once,
once, the
the number
number gets gets
divided by
divided by 2. Hence 12
2. Hence 12 »» 11 yields
yields 6, 6, which
which is is stored
stored in in a.a.
Similarly, in
Similarly, in subsequent
subsequent executions
executions of of the loop aa and
the loop and ii take
take
values 6
values 6 and
and 1 respectively, and
1 respectively, and then
then 11and
and2,2,which
whichare areprinted
printed
out through pprintf(
out through r i n t f ( )).. Once
Once aa andand ii are
are 11 and
and 2 2 and
and the control
the control
reaches the
reaches w h i l e , aa evaluates
the while, evaluates to to o.
0. Hence
Hence the the condition
condition fails,
fails,
and the
and the loop
loop is terminated.
is terminated.

(7)
(7) Output
Output

vicious circles
vicious circles
vicious circles
vicious circles.
Bits and Pieces
Pieces 489
489

Explanation
Explanation

Firstly ii is
Firstly is initialised
initialised to to 1,
1, and
and then
then in
in while, its
its complement
complement is is
taken. -1
taken. ~ l is
i s1111111111111110,
l l l l l l l l l i n 1110, which
which isis also
also aa truth
truth value.
value.
Hence 'vicious
Hence 'vicious circles'
circles' is is printed
printed for
for the
the first
first time
time and the
and the
control goes
control goes back
back to to the
the while.
while. Once
Once again
again -i~i evaluates
evaluates to to the
the
same value,
same value, 1111111111111110.
1111111111111110. This This so
so happens
happens because
because ii
has remained
has remained unchanged,
unchanged, as as i's
i's value
value can
can change
change onlyonly ifif ii
occurs on
occurs the left
on the left hand
hand side
side ofof the
the assignment
assignment operator.
operator. Since
Since
the condition
the condition evaluates
evaluates to to true,
true, the
the printf(
printf()) does
does its
its job
job once
once
again. This
again. This goes
goes onon and
and on,
on, as
as control
control has
has fallen
fallen inin an indefinite
an indefinite
loop, untu
loop, until wewe terminate
terminate the execution by
the execution by typing
typing either ctrl-C
either ctrl-C
or ctrl-scroll lock.
or ctrl-scroll lock.

(8)
(8) Output
Output

c = 170
C 170
dd=O
=0

Explanation
Explanation

aa and
and bb are
are made
made toto store
store hex
hex numbers
numbers aO aO and
and Oa.
0a. These
These hex
hex
numbers
num are nothing
bers are nothing but
but binary
binary 0000 00001010 0000
000000001010 0000 and 0000
and 0000
0000 0000 1010.
00000000 1010. On
On ORing
GRing them
them bitwise,
bitwise, the
the 2-byte number
2·byte number
obtained is
obtained is 0000
0000 0000
0000 1010
1010 1010,
1010, which
which is is decimal
decimal 170. On
170. On
ANDing them,
ANDing them, aa zero
zero results
results as
as in
in the
the binary representations
binary representations
of OxaO
of and OxOa,
OxaOand 0x0a, no
no corresponding
corresponding pairpair of
of bits
bits happen
happen to
to have
have
both Is.
both Is. Hence
Hence the
the output.
output.

(9)
(9) Output
Output

cc=Od=2
=0d=2
II
Explanation
Explanation
490
490 Exploring C
Exploring C

The enumerated datatype code is declared to be capable of


enumerated datatype
taking values add,
taking values add, delete,
delete, modify
modify andand unchanged.
unchanged UsingUsing thethe
typedef statement, two
typedef statement, two variables
variables of of this
this type,
type, cc and
and dare
d are
declared
declared and initialised, cc is
and initialised. is assigned
assigned the
the value
value add,
add, and
and d,d, the
the
value
value modify. The printf()
modify. The printf() thenthen prints
prints out the values
out the values Of
of cc and
and
d.
d. Did
Did you
you expect
expect add
add andand modify
modify to to be
be printed?
printed? Well,
Well, this is
this is
one feature of
one feature of an
an enum
enum thatthat takes
takes away
away some
some ofof its
its usefulness.
usefulness.
When
When values are defined
values are defined forfor anan enum,
enum, they
they are
are interpreted
interpreted asas
integer values 00,1,2,
integer values , 1 , 2, etc.
etc. by default. Thus,
by default. Thus, add,
add, which
which occurs
occurs
first is assigned
first is assigned 0,
0, delete
delete isis assigned
assigned 1,1, and
and so
so on.
on. That
That is
is why,
why,
on
on printing
printing the
the values
values of of cc and
and d,d, we
we get
get 00 and
and 22 respectively.
respectively.

We can, if we want, change these assignment c{fvalues


of values by
explicitly saying
explicitly so. For
saying so. For example,
example, saying
saying add
add = 10 =
in the
10 in the
declaration would give
declaration would give the value of
the value of ccas
as 10.
10.

(10) Output
(10) Output

rain = 00
r a n =

Explanation
Explanation

rain is aa variable
rain is variable ofof the
the type.
type, enum
enum status,
status, which
which isis declared
declared
to be
to be able
able toto take
take values
values low,
low, medium
medium and and high.
high. In
In an enum,
an enum,
the values are
the values are interpreted
interpreted as
as 0,
0, 11 and
and 22 in
in that
that order.
order. Hence,
Hence,
assigning
assigning 00 to to rain
rain is same as
is same as assigning
assigning low
low to
to rain.
rain. The
The if
condition is
condition is therefore
therefore satisfied
satisfied and
and we
we get
get our output.
our output.

(11) Output
(11) Output

rain = 21
r a n =

Explanation
Explanation
Bits
Bits and
and Pieces
Pieces 491
491

In
Inthis
this program
program wewe have
have overridden
overridden the the default
default integer
integer values
values
that
that low,
low, medium
medium and and high would
would have
have taken.
taken. WeWe have
have set
set
them
them toto 10,20
10, 20 and
and 30.
30. Thus,
Thus, assigning
assigning medium
medium to to rain
rain is
is same
same
as
as assigning
assigning 20 20 to
to it.
it. Hence
Hence the
the if
itcondition
condition is is satisfied,
satisfied, and
and the
the
++
++ operator
operator increments
increments rain
rain so
so that
that it
it now
now contains
contains 21.
21. The
The
same
same is is then
then printed
printed out
out by
by the
the printf(
printf( ).).

(12) Output
Output

Sunil30
Sunil 30

Explanation
Explanation

The typedef statement


The typedef statement defines
defines the
the structure
structure inin the
the program
program as as
a.
a. Next,
Next, aa variable
variable ofof this
this type,
type, emp
emp isis declared
declared andand initialised.
initialised.
Note
Note how
how thethe typedef
typedef statement
statement shortens
shortens the
the code used in
code used in the
the
program.
program. TheThe structure
structure elements
elements areare now
now accessed
accessed as as usual
usual
using
using the
the dot
dot operator,
operator, and
and wewe have
have the
the output
output asas the
the values
values toto
which
which emp.name[]
emp.name[] and
and emp.age
emp.age were
were initialised.
initialised.

(13) Output
(13) Output

Jodhpur20
Jodhpur 20

Explanation
Explanation
i/1
In
In this
this case,
case, wewe define
define struct
struct address
address ** s ADDR. Next,
~LasADDR. Next, the
the
variable
variable addr
addr isis declared
declared toto be
be of
of this
this type,
type, i.e.
i.e. aa pointer
pointer to
to the
the
structure
structure of of the
the type
type struct
struct address.
address. The
The address
address of of the
the struc-
struc-
ture
ture variable
variable a a is
is assigned
assigned toto this
this pointer,
pointer, having
having first stored
first stored
"Jodhpur"
"Jodhpur" and and 2020 in
in a.
a. On
On using
using the
the arrow
arrow operator
operator with addr,
with addr,
the
the values
values of of structure
structure elements
elements of of a
a are
are printed
printed out
out byby the
the
printf(
printf( ).).
492
492 Exploring
ExploTing C

Note that
Note that C
C is
is aa case sensitive language.
case sensitive Hence it
language. Hence it treats ADDR
treats ADDR
and addr
addr as two different entities.
entities.

(14) Output
(14) Output

2.500000

Explanation
Explanation

In the innermost
innermost parentheses,
parentheses, the expression
expression is typecast to an
int. Hence, during division 66 is used instead of 6.5,
into Hence, 6.5, which
which
into 3,
results into
results 3, an int. To
an int. To this
this is added 3.5,
is added 3.5, so
so that
that we
we have the
have the
value 6.5.
value 6.5. This result is
This result is typecast
typecast using
using (float),
(float), soso that
that we now
we now
have the value
have the 6.500000, which
value 6.500000, which is is how
how aa Ooat
float is
is represented.
represented.
Once again, (( iint
Once again, n t )) typecasts
typecasts this
this value
value toto an
an integer,
integer, whence
whence
the decimal part
the decimal part isis truncated
truncated andand the
the value
value is
is now
now 6.6. From
From this
this
value,
value, we subtract 3.5,
we subtract 3.5, and
and thus
thus are
are left with 2.5.
left with 2.5. This
This value is
value is
finally typecast to a float, and hence the output
finally typecast to a float, and hence the output displays this displays this
2.500000.
as 2.500000.
.as

! 5 ) Output
)-5)
v Output

00004
004

Explanation
Explanation

struct Dum
struct num isis not
not an
an ordinary
ordinary struct.The
struct. The :: sign
sign indicates
indicates that
that
we are
we are dealing
dealing with
with bit
bit fields.
fields. In
In the
the declaration,
declaration, bitO,
bitO, bitl and
bit! and
bit2 are assigned
bil2 are assigned only
only 11 bit each. Hence
bit each. Hence we we can
can conclude
conclude thatthat
these variables are
these variables are going
going to to take
take not
not more
more than
than two
two values,
values,
which
which can can be represented by
be represented by aa 00 or
or aa 1.
1. Then,
Then, rest
rest is
is assifned
assigned
55 bits,
bits, indicating
indicating that
that rest
rest can
can represent
represent aa maximum
maximum of of 22 ,i.e.
, i.e.
32 values. These
32 values. These declarations
declarations are are made
made using
using the keyword
the keyword
unsigned,
unsigned, as as by
by default
default one
one bit
bit is
is devoted
devoted toto store
store the
the sign
sign ofof
Bits
Bits and
and Pieces
Pieces 493
493

the
the number,
number, andand we
we do
do not
not want
want to
to store
store any
any sign information.
sign inforination.
Thus,
Thus, aa total
total of
of one
one byte
byte is
is used
used by
by bitO,
bitO, bitl,
bitt, bit2
bitl and
and rest.
rest.

Next,
Next, aa union
union ofof such
such aa structure
structure n and
and aa char
char chch is
is declared.
declared.
We
We know
know that
that assigning
assigning aa value
value to
to one
one ofof the
the variables
variables of of aa
union
union automatically
automatically assigns
assigns aa value
value to
to the
the other
other variable.
variable. This
This
is
is because
because the
the same
same 88 bits
bits that
that are
are used
used by
by ch
ch are
are used
used for
for struct
struct
n. Thus, when we say ch = 32, the 8 bits are set
n. Thus, when we say ch = 32, the 8 bits are set up as shown up as shown
in
in the
the following
following figure.
figure.

b.n.bit2

---
7 6
b.n.rest
5
---.j~

432
Iir
. I
I
I 0
b.n.bitl
b.n.bitO

10101
1'1-------
1 I 0 I
b.ch
b I 0
------<01
I 0 I 0 I
Figure
Figure 12.2

On
On printing
printing b.n.bitO, b.n.bitl
b.n.bitl and
and b.n.bit2,
b.n.bitl, we
we get
get the
the Os stored
Osstored
here.
here. Bit
Bit numbers
numbers 7,7, 6, 5, 44 and
6, 5, and 33 store
store the information
the information
corresponding
corresponding toto b.n.rest.
b.n.rest, The
The contents
contents here
here are
are 00100,
00100, which
which
is
is the
the binary
binary equivalent
equivalent of decimal 4.
of decimal 4. Hence
Hence the
the last
last output
output is
is
4.
4.

(16) Output
Output

address = 528
Diamonds are forever

Explanation
Explanation
494
494 Exploring C
Exploring C

This program
This demonstrates the
program demonstrates the use
use of
of pointers
pointers toto functions.
functions, f,f,
which is declared to be a pointer to the function show(
which is declared to be a pointer to the function show(), is
), is
assigned the
assigned the address
address ofthis
of this function,
function. The
The address
address of
of aa function
function
can be
can be obtained
obtainedbyby simply
simpty mentioning
mentioning the the name
name ofof the function.
the function.
The printf(
The printf( )) in
in IDain(
main()). prints
prints this
this address,
address, which
which may may bebe
something other than 528 when you run
something other than 528 when you run the program.the program.

The last
The last statement
statement in
in IDain()
main() calls
calls the
the function
function show().
show(). Instead
Instead
of calling the function by name, we make use of the pointer to
of calling the function by name, we make use of the pointer to
the function.
the function. As
As aa result
result control goes to
control goes to show(
show(),), where the
where the
printf()) prints
printf( prints "Diamonds
"Diamonds are are forever".
forever".

(17) Output
(17) Output

On the rebound...
rebound ...

Explanation
Explanation

To begin
To with, ff is
begin with, is declared
declared as as aa pointer
pointer to
to aa function,
function, which
which
returns an
returns an int.
into Into f is stored
Into fis stored the
the address
address of
of show().
show(). Now,
Now, this
this
address is
address is passed
passed toto another
another function
function display(
display(), where it
), where it is
is
collected in
collected in ff. Hence fY
fY. Hence ff is
is also
also declared
declared to
to be
be aa pointer
pointer toto aa
function. Front
function. From display(),
display( ), the the function show()) is
function show( is called
called byby
mentioning its
mentioning its address,
address, andand we
we get
get our output on
our output on the execution
the execution
of the
of the printf() here.
priiltf( ) here.

(18) Output
(18) Output

Hail the viruses!


viruses!

Explanation
Explanation

Here we
Here are dealing
we are dealing with
with an
an array
array of
of pointers
pointers to functions. To
to functions. To
begin with,
begin with, in
in the
the elements of the
elements of the array
array f[
f[ 1
] the
the addresses
addresses of
of
functions funl(),
functions funl(), fun2()
fun2() and
and fun3()
fun3() are
are stored.
stored. Next,
Next, with
with the
the
Bits and
and Pieces
Pieces 495
495

for loop, calls are-made


are made to each of these functions making use
of their addresses.
addresses. The
The 'first
first call results in "Hail
"Hail"" being out-
putted. Now, when iiis is fuu2( )
1, fun2() is called, and "the " is
"the" is printed.
printed.
Finally, for ii equal to 2, fun3()
fuD3( ) gets called, and the printf( )
here displays "viruses!".
here displays "viruses!".

i! i
I
II

Вам также может понравиться