Mscca 101
Mscca 101
^•
If
I'
k* .
Computer Fundamentals
r
M.Sc.(CA)-101 ,
'•"i
4
4
*;
•' V
7;
SWAMI VIVEKANAND :
SUBHARTI UNIVERSITY
n Meerut (National Capital Region Delhi)
• f . j r+ ■*
r-
;■
\
COMPUTER FUNDAMENTAL AND
4-
PROGRAMMING IN C
y
-H Of D'ST/l^X
/ ^ o\
/ o » *•
51
Ul&S
\ ♦
X f/
DIRECTORATE
OF DISTANCE EDUCATION
SWAMI VIVEKANAND SUBHARTI UNIVERSITY
MEERUT-250 005,
UTTAR PRADESH (INDIA)
t
SLM Module Developed By : Mr. A.K. Mishra
Assessed by:
Study Material Assessment Committee, as per the SVSU ordinance No. VI (2)
Copyright © SVSU
Edition : 2021
DISCLAIMER
No part of this publication which is material protected by this copyright notice may be
reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning,
recording or by any information storage or retrieval system, without prior permission from the
publisher.
Information contained in this book has been published by Directorate of Distance Education and
has been obtained by its authors from sources be lived to be reliable and are correct to the best
of their knowledge. However, the publisher and its author shall in no event be liable for any
errors, omissions or damages arising out of use of this information and specially disclaim and
implied warranties or merchantability or fitness for any particular use.
i
COMPUTER FUNDAMENTAL AND PROGRAMMING IN C
UNIT-1
/
Number System: Decimal, Octal, Binary & Hexadecimal, Representation of Integer,
fixed and floating points, character representation : ASCII, EBCDIC.
UNIT-2
UNIT-3
UNIT-4
INFORMATION REPRESENTATION
1.1 INTRODUCTION
Few basic feature;; which are common to all digital processing of information arc
given below
• All streams of input symbols to a digital system are encoded with two distinct
symbols 0 (zero) and I (one), known as binary digits or bits. Bits can he stored and
manipulated reliably and inexpensively with today's electronic circuits.
•The instructions for manipulating the symbols are to be properly specified so that a
machine can be built to execute these. The instructions for manipulation arc also
encoded using bits.
• A digital computer has a storage unit which stores the symbols to be manipulated
and the encoded instructions for manipulation of the symbols.
1
symbols where each symbol, called a bit, is either a 0 or a 1. The general properties
of number systems, methods of their inter-conversions are also discussed in this
chapter.
Number systems are very important to understand because the design and
organization ofa computer depends on the number systems. The modern -civilization
is familiar with Decimal Number System, in which ten digits, namely 0 to 9 arc used
to represent any number. Now the decimal number system is used frequently in the
field of/Science and Technology. Once the famous Mathematician Laplace stated, "It
is India that gave us the ingenious method of expressing all numbers by means of
ten symbols, each symbol receiving a value of position as well as an absolute, value,
a profound and important idea which appears so simple to us now that we ignore its
true merit." Thus, the importance of a number system does not lie in the number of
symbols used in it but what is important in it is the concept of face value (absolute
value) and the place value (value of position) of a symbol. However, if instead of
decimal system the binary number system, using two digits namely, 0 and 1, had
been popular everywhere, the understanding of computer working would have been
much easier. The binary number system is the one which is used in computers and
is based on the fundamental concept of decimal number system. Various other
number systems such as Octal System and 1-lexadecimal,System (popularly known
as Ilex system) also use the fundamental concept of face value and place value.
2
4. Hexadecimal Number System.
The Binary Number System, as the name suggests, consists of two digits namely, 0
and 1. These binary digits are called BITS. Thus, the word BIT stands for either of
the binary digits, namely 0 or I. Since this system uses two digits only, it has the
base or radix 2. It may be noted that the base digit namely 2, is not the fundamental
or basic digit of the system. Thus, all the numbers in binary system are written with
the help of these two digits namely, 0 and 1. The positional value or place value of
each digit in a binary number is twice the positional value of the digit on its • right.
This number system is identical to decimal number system with the base replaced by
2. The binary numbers ' are usually written with the base indicated as a subscript on
the Least Significant Digit (LSD). For example,
(101101.1011)
Positional
-> 2$$ 24 25 21 2' 2° t 2'1 2'3 '2*
values
l l l I T I i i I I
1 0 1 'I 0 1 1
1 0
t t
MSB Binary LSB
(Most Significant Bit) , point (Least Significant Bit)
Here, the places to the left of the binary point are positive powers of ,2 and places to
the right are negative powers oft. The commonly used terms in coding of data in
computer terminology are:
3
BIT (Binary digij). A binary digit is logical 0 or 1.
Nibble. A group of four bits (binary digits) is called a Nibble. It is useful in coding the
numeric data to hexadecimal form. Byte. A group of8 bits make a byte. A byte is the
smallest unit which can represent a data item or a character. , Computer Word. A
computer word, like a byte, is a group of fixed number of bits which varies from
computer to computer but is fixed for each computer. The number of bits in a
computer word is known as the word size or word length.
(i) The circuits and switches in a computer have only two states, either on or off,
which are represented by 1 and O. •
(ii) Handling of two digits, that is, 1 and 0 is simpler, cheaper and more reliable.
(iii) Every operation or activity that can be performed by decimal number system can
also be done using binary number system, so it does not create any problem.
This number system has base or radix 8. The basic digits of this system are 0, 1, 2,
3, 4, 5, 6 and 7. It may be noted that the base 8 is not the, basic digit of the system.
It is commonly used as a shorthand way of expressing binary quantities. Also the
numbers represented in octal number system can be used directly for input and
output operations. The octal number system is also a positional value system,
wherein each octa. digit has its own value or weight expressed as a power of 8. For
example
(157246.3174)8
4
Positional -► 8 84 83 82 81 8° 8'1 S'2 8'3 8^
values | | i i I I I I i I
I 5 7 2 4 6 3 1 7 4
t Octal
t
MSD LSD
(Most Significant Digit) point (Least Significant Digit)
\
Fig. 2. Octal number shown with positional values.
Here, the places to the left of the octal point are positive powers of 8 and places to
the right are negative powers of 8.
In a number system the base is not the fundamental digit of the system because
fundamental digits in this system are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. The value of each
digit in a number depends upon the following : -
(i) The face value of the digit, that is, the digit itself. .
5
(iii) The position of the digit in the number. Thus, the magnitude of a number
depends upon the digits of which it is made, position of the digits and base of the
system. For example,
(3514798265)
Here, the places to the left of the decimal point are positive powers of 10 and places
to the right are negative powers of 10.
In a decimal number as we move from right to left (starting with the digit before
decimal point) the positional or place value of each digit is 10 times the positional
value of the digit to its right and as we move from left to right * (starting with the digit
after decimal point) the positional value of each digit becomes one-tenth of the
positional value of the previous digit. The part of thenumber before the decimal point
is called integral part and the one after the decimal point is called the fractional part.
The Hexadecimal Number System, popularly known as Hex System, has sixteen
symbols and therefore has the base Or radix as 16 or H. It is very well suited for big
6
computers. The hexadecimal number system represents an .information in the
concise form. The sixteen symbols used in this system are :
0,1,2,3, 4, 5, 6, 7, 8, 9,A,B,C,D,E,F
Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F
For example,
(6A9E83.C5BD),6
t t .
Hexadecimal LSD
MSD (Least Significant Digit)
(Most Significant Digit) point
Here, the places to the left of hexadecimal point are positive powers of 16 and
places to the right are negative powers of 16.
Table 1 illustrates the relation between binary, octal, decimal and hexadecimal
number systems:
7
Table 1. Numbers with different bases
Hence, for computers the binary number system is required. But, the binary number
system at the moment is indispensabie for computers as it suffers from the defect of
8
expansion. For example, a number in decimal system requiring only one digit for its
representation may require more than one bits in binary form.
To overcome this problem various other number systems such as Octal (base 8) and
Hexadecimal (base 16 or H) were developed. A base greater than 10 is preferred
because it will require even lesser number of digits. The choices of bases 8 and 16
are useful because of their being multiple of two.
A binary number can be converted to its decimal equivalent by adding the Weights of
the various positions in it • which have a 1.
Solution :
= 16 + 0 + 4+2 + 0.
= (22)10,
It must be noted that the binary number 10110 has five digits in all. The most
significant digit (MSD) has the fifth position (starting from rightmost digit) so it is
multiplied by 24 and each digit on its right will be half of it in its positional value, so
these are multiplied by 23, 22, 2', 2° respectively and the products so obtained are
added to get the required decimal equivalent.
=128+64+0+16+8+4+0+0.
9
= (220)10
= 220.
Divide the given number N by 2 and let the quotient be q, and the remainder be R..
Again divide the quotient q, by 2 • and let the remainder be R2. Continue the
procedure of division till the quotient becomes 0 and in this case let the • remainder
be R„.
N = R„ R„R3 R2 Rn
10
Solution : (i) Start dividing 25 by 2 and continue the procedure till the quotient is 0.
The procedure is shown below :
2 25
(=*,)
2 12-1
2 6-0 •
2 3-0 (-Ra)
2 1-1
0-1 (=iy
The required number in the binary number system
= R, R4 R3 R2 R,
= 11001 (25),0
= (11001)2
(ii) Start dividing 283 by 2 and continue the procedure till the quotient becomes 0.
2 283
2 141-1
2 70-1 (-R2)
2 35-0
2 17-1
2 8-1 (=R5)
2 4-0 (=1^)
2 2-0
2 1-0
0-1
n
The required binary equivalent of 283
R R, R R, R R R, R, R
(100011011)2
Thus, (283)10 = (100011011)2
The decimal digits and their binary equivalents are given in Table 2.
0 0 (0*2')
! 1 (1*2°)
2 10 (1 * 21 + 0 * 2®)
3 II (| x 21 + 1 x 2C)
4 100 (I x 2] + 0 * 21 + 0* 2°)
5 101 (j x 2: + 0 * 2' + I * 2°)
6 no (1 x 21 + 1 x 2' + 0* 2°)
..7 . 1.11 (1 x 2: + 1 x2'+ 1 x 2°) .
8 1000 (1 x 25 + 0 x 2l + 0x 2‘ + 0 x '2<>)
9 1001 (1 x2, + 0x2, + 0x2‘ + l x2*)
0. f1 f2 f3 fa
while multiplying by 2, it must be noted that every time only fractional part is to be
multiplied and not the integral part. The following examples illustrate the procedure. -
Example 1. Convert the decimal fractional number 0.8125 into its binary equivalent.
Solution :
12
<-0.6250
x2
/2 <e-0Q.25OO (Multiply only the fraction part)
y-2
<-11.5000
y-2
if* <-□>0000
Thus, (0.8125)10 fl f2 f3 f4
= (0.1101)2
Slution.
0.33
x2
/ <-[0].66 (Multiply only the fraction part)
x2
jfi [j].32
*2
A <-1.64
x2
<—[T].28
x2
A. <—1.56
y-2
If, <—[D. 12
(0.33),, =
= (0.010101...)2
13
1.3.4 Conversion of Mixed Numbers (from Decimal to Binary).
A mixed number consists of an integral part as well as a fractional part. For example,
38.625 is a mixed number. A mixed number in decimal system can be converted to
its binary equivalent by converting the integral and fractional *parts separately into
their binary equivalent.
Example. Convert the decimal number 38.625 into its binary equivalent.
Solution : The given decimal number has two parts, namely an integral part 38 and a
fractional part 0.625; These are to be converted into their binary equivalents
separately, as given below:".
2 38
2 19-0
2 9-1
(=»*)
2 4-1
2 2-0 (=R4)
2 1-0
0-1 (=RJ
Thus, the binary equivalent of(38)10 = R6 R5 R4 R3 R2 R1
= (100110)2
14
0.625
x2
f <-[11.250
x2 (Multiply only the fraction part)
f - <-[2.500
x2
/3 <-[01.000
For converting integer decimal numbers into their equivalent octal numbers, divide
the given number repeatedly by 8 till the quotient obtained is zero. The following
example illustrates this concept: -
Solution: (i) Start dividing 759 by 8 and continue the procedure till the quotient is 0.
The procedure is shown below:
15
8 759
8 94-7 LSD
8 11-6
8 1-3
0-1 MSD
For converting decimal fractions into their equivalent octal "fractions, multiply the
fractional part repeatedly by 8 •. and keep track of the overflow. The process of
multiplication continues till the fractional part becomes zero or upto ..required
number ofdigits..
A mixed octal number can be converted to decimal number by the formula given
below
M = dn+i 8n+dn8n-i + dn-i 8n-2 +......dsSa +d28i +di8o +d-i8-i + d-28-2 +d-38-3 +....+ d-n8-n
Example 1. Convert thefollowing octal numbers into their decimal equivalents : ti)
(47), (ii) (564),
16
Solution, (i) (47)8 = 48x81+7x8°
= 32+7=39 -
=5 x 64+6 x 8+4 x 1
= 320+48+4
= 372
= 3x1/8+4x1/64
= 3x0.125+4x0.015625
= 0.375 + 0.062500
= (0.4375)10
= (0.691406250)10
17
11.3.7 Conversion from Octal to Binary
The octal number system is widely used as a shorthand way of expressing binary
values. The octal number system » « groups three binary bits together into one digit
(0 to 7) as given in Table 3.
To convert an octal number to its binary equivalent, each digit of the octal number is
converted to its 3 bits binary equivalent.
Solution : (i)
18
1_H (Replace each octal digit by its 3 bits binary equivalent)
(746)8 = 7 4 6
(111100110),
(740)s - (111100110), •r
= (11101.01000111)2
= (100001111.010101)2
For converting a binary number into its octal equivalent the following steps are
followed
19
(i). Divide the given binary number before the binary point into groups of three bits
each (from right to left) and alter the binary ponit into groups of three bits each (from
left to right) by adding 0 bits for completing the groups (if needed).
on ioi , . , , ft
-Solution: (i) (U101), “5 5" (Replacing each group by its octal equivalent, U
added on lefimost position for completing the group)
For converting integer decimal numbers into their equivalent hexadecimal numbers,
divide the given number repeatedly by 16 (it the remainder is greater than or equal to
10 then write its symbol, that is, A to F, otherwise the digit 0 to 9) till the quotient
obtained is zero.
Solution. (1) Startdividing 28 by 16 and continue the procedure till the quotient is 0.
The procedure is given below:
20
16 28
16 1-C
0-1
Thus (28)10 = (1C)16
16 1795
16 112-3
16 7-0
0-7
Thus, (1795)10=(703)16
For converting, decimal fractions into their equivalent hexadecimal fractions, multiply
the fractional part repeatedly by 16 and keep track of the -overflow. If the overflow is
greater than equal to 10 then write its symbol, that is, A to F, otherwise the digit 0 to
9. The process of multiplication continues till the fractional part becomes zero or upto
required number of digits.
21
1.3.10 Conversion of Hexadecimal Numbers to their Decimal Equivalents
For converting a hexadecimal number to its binary equivalent, each digit of the
hexadecimal number is converted to its 4-bits binary equivalent. For reading
convenience, usually each nibble (4-bits binary equivalent) is written with a little
space in between. The following examples illustrate this concept:
22
(i) (F3A.CB)J6.
It is the conventional form for number representation. Every integer has a sign (+ or
—) and a string of digits representing the magnitude.
For example, . + 241 or 745 arc positive integers (+ sign -may be omitted)
—127, — 82 are negative integers
23
The sign of a number is represented by the MSB (Most Significant Bit). If it stores
value 0, -the sign is +, and if stores 1, the sign is —.
Let us assume that the Word size of the computer is 16 bits, then + 93 will be
represented as given below :
Since, bit pattern of93 consists of 7 bits, it is expanded to 15 bits by adding the
required number ofzeros to the left as .000000001011101.
t t
MSB LSB
(1 for —sign)
Integer Range for N Bit Word. The range for integer numbers using .sign and
magnitude representation is given by the formula :"
N-1 N-1
—2 to 2 —1
as 1 bit is used for sign notation so (N-1) bits represent the magnitude.
-216-1 to 216-1-1
Note. 1 n this method of representation, we obtain two representations for 0, one for
1 + 0 and other for — 0.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 I 0
1
MBS (0 for+ sign)
i
LSB
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
n— 1 n—1
For example,
25
The number — 45 using a 16-bit word is represented as given below :
(45)10 = (101101)2
1 1 1 1 1 1 1 1 1 1 0 1 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Representation of + 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Using two complement positive numbers are represented by their binary equivalents
(also known as true forms} and negative numbers by their 2's complement form. For
an n'-bit number, the maximum positive number which
n—1
can be represented in 2’s complement form is (2 —1) and the minimum negative
number is 2's complement ofa number is found by adding 1 to its I’s complement.
or
26
For finding the 2’s complement of a number, start from the LSB and write the bits as
it is till the first 1 appears (do not ehange the first 1 to 0), then write the I’s
complement of the remaining bits to the left side of it. For example, 2's complement
of binary number 1110001 will be calculated as given below :
0 + 0 0
0 + 1 1
1 + 0 1
1 + 1 = 10
Vs complement is 1111111111010011
+1
2's complement is 1111111111010011
27
In general, the negative numbers are stored in the computer memory in 2's
complement form and positive numbers in sign and magnitude form.
A comparison between Ps" and 2's complements reveals the advantages and
disadvantages ofeach.
(i) The Ps complement has the advantage of being easier to implement by digital
components (vi2. inverter) since the only thing to be done is to change the 1 's to 0’s
and vice versa. To implement 2's complement we can follow two ways : (1) by ^finding
out the Ps complement of the number and then adding 1 to the LSB of the 1’s
complement, and (2) by leaving all leading 0's in the LSB positions and the first 1
unchanged, and only then changing all 1 ’s to 0's and vice versa.
(ii) During subtraction of two numbers by complement method, the 2's complement is
advantageous since only one aritlunetic addition is required. The Vs complement
requires two arithmetic additions when an end-around carry occurs.
Using Vs complement:.
1010
+ 0101 (Ps complement of 1010)
+ 1111 (negative zero)
28
£
100
+ 0110 (2's complement of 1010)
(Carry over) 10000
After dropping the carry over, the result is + 0000. .• In this 2’s complement method
no question of negative or positive zero arises.
29
A number having both integer part as well as a fractional part is called real number
or floating point number. It may he either positive or negative. For example, 975.88,
0.586 — 0.586, — 0.866 represent real decimal numbers and 101.001, 0.0101, -
100.1001 represent binary real numbers.
Real numbers arc represented in the memory of the computer by their mantissa and
exponent. In the general form,
N=Mx
The mantissa M and the exponent e are actually stored in a register of a computer.
But, the base or radix R and the *.radix-point (decimal or binary point) are not
present in the register. An assumption is made about these and the electronic
circuitry taking these things into account performs the computation and manipulation.
.. Let us assume a 16-bit.word for a computer having two parts : a 10-bit mantissa
and a 6-bit exponent. The mantissa . is in two’s complement form ; the left most bit
represents a sign bit. The binary point is assumed to be to the right of the sign bit.
f
' ‘i •' *
<■
___Mantissa ■>K
Exponent__^ -»
10 bits 6 bits
0 111 1 I 10 0 0 0 1 0 0 0 1 1
AA
I Assumed Binary Point
Sign
bit
The 6 bits of the word store the exponent without any sign. The reason for not having
the place for storage of the sign -.of exponent is that the exponent is represented in
biased form. Now, let us understand the meaning of biased form of the exponent.
The minimum number represented by 6 bits is (-25), that is, —32. While representing
align the floating point numbers, this number 32 is added to the actual exponent,
30
thus leaving no space for negative exponent. The new exponent (after adding 32 to
the actual exponent) is called Biased Exponent. This code for floating point
representation is called as the base 2 excess 32 code. Some examples of this
system for exponent part are given in Table 4 given below :
Now, using the above definitions, the floating point number in figure 7 is :
= (111.11)2
= 7.75
There are many formats of storage of floating point numbers on different computers."
Some use two words for the mantissa and one for the exponent; others use one and
31
one-half word for the mantissa and one-half word for the exponent. Few systems
even allow to select a format out of many, depending on the accuracy desired. Some
use excess-n notation for the exponent; some use 2's complement. Some even use .
signed magnitude for both the mantissa and the exponent.
Floating point numbers are used to express very large and very small numbers.
Using above mentioned system of storage for numbers, we can have 9-bit accuracy
(1 bit allowed for sign of mantissa). The exponent bits add nothing to accuracy, only
to magnitude. The accuracy of fixed point 2’s complement numbers expressed in 16
bits is of 15 • bits. So, the floating points are less accurate than an equivalent length
fixed point number.
For achieving the full 10 bits of accuracy in the floating point number, the most
significant bit of the mantissa is Made non-zero and the number so obtained is said
to be in the normalized (or standard) form. The process of shifting of mantissa left to
make the most significant bit "non-zero is called normalization.
Many applications of computer require not only of handling numbers, but also of
letters. To represent alphabet it is necessary to have a binary code for the alphabet.
In addition the same binary code must represent the decimal numbers and some
other special characters. An alphanumeric code is a binary code of a group of
elements consisting of ten decimal digits, the 26 letters of the alphabet (both in
upper-case and lower-case), and a certain number of special symbols such as #, /,
&, %, etc- The total number of elements in an alphanumeric code is greater than 36.
Therefore it must be coded with a minimum number of 6 bits (26 = 64, but 25= 32 is
insufficient). One possible six bit. alphanumeric code is given in Table 5. It is used in
many computers to represent alphanumeric characters and symbols internally and
therefore can be called "internal code". Frequently there is a need to represent more
32
than 64 .characters including the lower case letters and special control characters.
For this reason the following two codes are normally used.'
ASCII
The full form of ASCII (pronounced "as-kee") is "American Standard Code for
Information'lnterchange", used in most microcomputers. It is actually a seven bit
code, where a character is represented with seven bits. The character is stored as
one byte with one bit remaining unused. But often the extra bit is used to extend the
ASCII to represent an additional 128 characters. Some of the codes are shown in
Table 5.
The same word CODES in A SCII-8 code can be represented as given below :
EB CD1 C
It is pronounced as "ebb-see-dick". It is a 8 bit code and can represent 256 different
characters. All of the 256 bit combinations are not meaningful, so the code can still
add new characters ifrequired.
The full form of EBCDIC is "Extended Binary Coded Decimal Interchange Code". It is
also an alphanumeric code generally used in IBM equipments and in large
computers for communicating alphanumeric data. For the different alphanumeric
33
characters the code grouping in this codecs different from the ASCII code. It is
actually an . eight bit code and a ninth bit is added as the parity bit. Out of the 8 bits,
the first '4 bits are known as zero bits and the remainder 4 bits represent digit values.
34
T 11001.1 1010100 11100011 0,3
u 110100 1010101 11100100 0,4
V 110101 1010110 11100101 0,5
w 110110 1010111 11100110 0,6
X 11011 10111000 11100111 0,7
Y 111000 1011001 11101000 0,7
z 111001 1011010 11101001 0,7
0 000000 0110000 11110000 0
1 000001 0110001 11110001 1
2 000010 0110010 11110010 2
3 000011 0110011 11110011 3
4 000100 0110100 11110100 4
5 000101 0110101 11110101 5
6 000110 01110110 11110110 6
7 000111 0110111 11110111 7
8 001000 0111000 11111000 8
9 001001 0111001 11111001 9
Blank 110000 0100000 0100000 No punch
011011 0101110 01001011 12.3.8
{ ) 111100 0101000 01001101 12.5.8
+ 010000 0101011 01001110 12.6.8
101100 0101010 01011100 11.4.8
$ 101011 0100100 01011011 11.3.8
) 011100 0101001 01011101 11.5.8
/ 110001 0101111 01100001 0,1
111011 0111100 01101011 0,3,8
001011 0111101 01111110 6,8
100000 0101101 01100000 11
35
1.5 SUMMARY
• The binary number system has the base or radix 2, the octal 8 and hexadecimal 16.
• Complements are used in digital systems for simplifying the subtraction operation
and for logical manipulations.
Codes are used to represent information, error detection and error correction.
• Integers can be represented in computer memory using sign and magnitude, 1 's
complement and 2's complement forms.
• In general, the negative numbers are stored in the computer memory in 2’s
complement form and positive numbers in sign and magnitude form.
(i) (94.00625)10 ( )
(ii) (11011.0101)2 = ( )10 ( )
(iii) ASCII stands for (..............
3." Find the 1' and 2’s complement of the following binary numbers :
36
(v) 0002 (vi) .11112
(vii) 0.1012 (viii) 100.012
7. Why was son code extended to EBCDIC? Write code for the following words :
37
UNIT-II
COMPUTER FUNDAMENTAL
2.1 INTRODUCTION
Computer is perhaps the most powerful and versatile tool ever created by man.
Computers have made a serious foray into every nook and corner of our everyday
lives. Their presence can be felt at almost every working place viz. schools, colleges,
homes, offices, industries, hospitals, banks, airways, railways, research
organizations and so on. Computers, large and small, are used nowadays by all
kinds of people for a variety of purposes.
A digital computer is a digital device which processes digital data. Thus computer
(digital) can be defined as a . multipurpose, programmable machine built by logic
circuits which accepts binary data as input, processes the data 'according to the
binary instructions, read from its memory and provides result in the form of binary or
analog as its output.'
A digital computer is basically an electronic device that can transmit, store and
manipulate information i.e., data. • Several- different types of data can be processed
by a computer. These include numeric data, character data, (name, address, etc.'),
graphics data (charts, drawings, photographs, etc.), and sound (music, speech
pattern, etc.). The two most common data types are numeric data and character
data. Scientific and technical applications are concerned primarily with numeric data,
whereas business applications usually require processing of both numeric and
character data..
38
2.2 CHARACTERISTICS OF COMPUTERS
Computers have some remarkable features which have made them so very popular.
These features are basically the reasons for which the computers were originally
built. These features are:
1. Automatic. The computers are automatic machines in the sense that once started
on a job, they carry on, until the job is finished, normally without any user's help. But
computers cannot start themselves. They have to be instructed, which (the
instructions) specify the way of the job completion.
2. Speed. The computers can work at enormously high speeds. They are capable of
taking logical decisions, performing arithmetic and non-arithmetic operations on
alphabets and copying at unbelievable speed. While talking about the speed of a
computer, we do not talk in term of seconds or even milliseconds (10""3). For a
computer the units of speed are microseconds (10-6), nanoseconds (10-9) and even
picoseconds (10-12). A powerful computer can perform 3 to 4 million simple
arithmetic operations per second. The reason for this extremely fast speed of a
computer can be attributed to the fact that a computer is an electronic device that
operates on electrical signals known as electric pulses. These pulses travel at
extremely high speeds and hence the fast speed of computers.
3. Accuracy. The computers produce highly accurate and reliable results. In majority
of cases the accuracy is close to cent per cent. However, errors can't be ruled out
but these are mainly due to human father than technological weaknesses, that is,
due to error in logic developed by the programmer or due to inaccurate data i.e,
garbage-in-garbage-out (GIGO).
39
(iii) It can perform logical operations.
(iv) It'can transfer data internally i.e., data can flow from one part to the other in the
machine.1
5. Diligence. A computer is capable of performing the same task over and over
again with the same degree of accuracy and reliability as the first one. This is
because unlike human beings, a computer is free from monotony, tiredness, lack of
concentration, etc., and hence can work for hours together without creating any
errors.
6. Large and Perfect Memory. As a human being our ability to acquire and retain
knowledge is limited. But this is not the case with computers. A computer can store
and recall any amount of information because of its secondary storage capability
with perfect accuracy. Even after several years, the information recalled will be as
accurate as on the day when it was fed into the computer. A computer loses
information only when it is asked to do so.
7. No LQ. A computer is not intelligent on its own. It cannot think on its own. It can
only perform tasks that a human being can. The difference is that it performs these
tasks with unthinkable speed and accuracy. It cannot take decisions on its own. Only
the user can determine what tasks the computer will perform.
40
Storage unit
Program Input Output / Results
unit Secondary unit
and data
memory
Primary
memory'
Control
unit
CPU
i (Central processing unit)
i
1
Arithmetic and
Logic unit
Input Unit
41
/
3.. It supplies the converted instructions and data to the computer system for further
processing.
Output Unit M
The output devices receive' results and other information from the computer and
provide them to the users. The computer sends information to an output device in
the binary form. An output device converts it into a suitable form convenient to users
such a-s printed form, display on a screen, voice output, etc. Some of the popular
output units are
2.. Printer
3. Plotter
1. It accepts the results produced by the computer which are in coded form.
Storage Unit.
The function of storage unit is to "store information. The data and instructions that
are entered into the computer system through input units have to be stored inside
the computer before the actual processing starts. . Similarly, the results produced by
computer after processing must be kept somewhere before they are passed onto the
output unit for display. Moreover, the intermediate results produced by the computer
42
must also be preserved. The storage unit or the primary/main memory of the
computer provides support for these storage functions. The main memory" is a fast
memory. It stores programs along with data. The main memory is directly accessed
by the CPU. The secondary memory, also called the auxiliary memory, is used to
store the information, data and program instructions permanently. These may be
used later on or deleted whenever not required..
3. It stores the final results of processing before they are passed onto the output unit.
The CPU is the brain of a computer. Its primary function is to execute programs.
Besides executing programs, the CPU also controls the operation of all other
components such as memory, input and output devices. The major sections of a
CPU are
(i) ALU. The function of an ALU is to perform arithmetic and logic operations such as
addition, subtraction, multiplication and division: AND, OR, NOT, EXCLUSIVE OR
Operations. It also performs increment, decrement, left shift and clear operations.
(ii) Control unit. The control unit is the most important part of the C.P.U. as it
controls and co-ordinates the activities of all other units such as ALU, memory unit,
43
input and output unit. Although, it does not perform any actual processing on the
data, the CU acts as a central nervous system.
3. It sets up the routing, through the internal wiring, of data to the correct place at the
correct time.
4. It can determine the storage location from Where it is to get the next instruction
after the previous instruction has been executed.
Any device that allows information from outside the computer to be communicated to
the computer is considered an input device. Since the Central Processing Unit (CPU)
of a digital computer can understand only discrete binary Information, all computer
input devices and circuitry must eventually communicate with the computer in this
form. Many devices are 'capable of performing, his task. Some common computer
input devices are
1. Punched cards
2, Card-readers
4., Keyboard
5 Mouse
6. Joystick
44
7. Trackball
9.. Voice-recognition
10.. Optical-recognition
11.. Scanners
(ii) Digital Device. A digital device is a discrete mechanism which represents all
values with a specific number system. For example, digital watches and computers
all process discrete information and use the binary number system.
ANALOG INPUT DEVICES. The Joystick, Trackball, Mouse and Paddle Controls
are all- transducers that • convert a graphics system user's movement into changes
in voltage. A transducer is a device that converts energy from one form to another.
DIGITAL INPUT DEVICES. Some of the digital input devices are Keyboard,
Lightpen, Digital Cameras and Digitizing Video Images, an Acoustic Tablet, A
Magnetic Pen and Tablet (DiGitiZer).
GRAPHICAL INPUT TECHNIQUES. The use 'of graphical input devices should not
be influenced purely by the way the user uses pens and pencils. The user should
instead consider the following three factors when .he/she writes program for these
devices :
45
(a) What is the user trying to do ?
(c) How can the display and computer help the user ?
Each of these questions has many different answers according to the situation, and
for each set of answers the user programs the input devices in different ways. The
result is that he/she develops certain programming techniques for the use of input
devices in each environment.
When we want to design the different characters in a natural and systematic Way,
the graphical feedback (such as cursor on screen) can play an important role in the -
input process. It helps the user in using an unfamiliar program. There are many
graphical input techniques such as :
(iv) Modes
The most important fact that should be considered while choosing any input device is
that the CPU of the computer must not be overloaded.
Punched Cards
in the early years of computer evolution, the punched cards were the most widely
used input medium for most computer system. These days they are not extensively
46
used in computer industry as number of fast input devices are available, but in order
to understand the potential of currently available input devices, it is necessary to
understand the concept behind the working of punched cards. There are two types of
punched cards—one has eighty columns and the other has ninety six columns;
8 Mimiiln
9 itniiiiili mimnliiiiiiii|iMni(|nmMniiii*»iiiiMHii‘i«J‘i»’'‘*‘J
The 80-column card is divided from left to right into 80 vertical columns numbered
from 1 to 80. It is again "divided into 12 rows numbered 12,11,0,1,2,3,4,5,6,7,8 and
9 from top to bottom. Each column of this card can be represented as one character,
so a maximum of eighty characters can be represented on one card. The digit 0 to 9
are represented by punching one hole in the corresponding row position. The
alphabet A to Z are represented by a combination of two holes in two of the row
positions. The top three rows-12, 11 and 0 are zone punching positions and the rows
47
0 to 9 are numeric punching position. A logical combination of zone and numeric
punches is required to .represent alphabets.
For example, letter A through I are coded by using a 12 zone punch and numeric
punches 1 through 9; letter J through R are coded by using a 11 zone punch and
numeric punches 1 through 9 and letters S to Z are coded by using a 0 zone punch
and numeric punches 2 through 9 respectively. Special characters are coded by
punching one, two or three column cards. This coding system is known as Hollerith
code after the name of the Herman Hollerith who first used punched cards.
The 96-column card, which was developed to store 20 percent more data in a small
amount of space, never found widespread use. It is only one-third the-size of an 80-
column card. The 96 columns are separated into three 32 column sections or tiers.
The upper portion of card, which is not used, for punching holes is used as the print
area These cards have round holes instead of rectangular holes of 80-column cards.
Moreover the standard 6 bit code is used instead of Hollerith code for. recording the
data on 96 column card. Each of the 96-columns has 6 punch positions and
remaining four are numeric positions. The presence of a hole in a punch position
indicates 1 bit. Punched cards are rarely used today. However, you may occasionally
encounter them in large companies such as public utilities, where they are still used
for billing. When the customer returns the card with payment, the keypunch operator
uses the keypunch machine to record new data on the card, then he or she runs the
card through a card reader to input the data into the computer (usually a mainframe)
Card Readers A card reader is an input device, it transfers data from the punched
card to the computer system. The card reader will read each punch card by passing
light on it. Each card, will be passed between a light source and a set of light
detectors. The presence of hole causes the light to produce a pulse in the director.
These pulses are transformed into binary digits by the card reader and sent to the
computer for storage. Card is then submitted in the output stack. Card readers can
read upto 2000 cards per minute.
48
■a*
UOl'l'iiR
STACKF-RS
I'UNCHliO BUANJC
CARDS CAJ<_DS
RHADINO PUNCHING
STATION STATION
KJ-YDOA.RO
HOPPUR
READ VERJI-Y
STATION STATION
o—O
mmm\
REJECT NORMAL
STACKER STACKER
49
There are two types of card readers depending upon the mechanism used for
sensing the punched holes in the cards :
• Photoelectric card reader. In this type of card reader, light passing through the
punched holes are detected by photoelectric cells. These are faster and accurate in
comparison of other type of card reader.
• Wire brush card reader. In this type of card reader, a card is passed between a
wire brush and a metal roller. Ifa punch exists, the brush makes electric contact with
the roller and then sends signals to the computer to which the card reader is
connected. 1
Key-Punching Machines
There is another device to punch data on a punch card~the key punch. It contains a
keyboard which looks like a • typewriter keyboard. When characters are typed in the
keyboard, corresponding holes are punched in the blank card. Then these cards will
be sent to card reader to feed the information to the computer. Commonly used key
punch machines were ISM 026 and IBM 029. These machines have the following
components
• Keyboard
• Card hopper
• Punching station
• Card stacker
• Column indicator
• Backspace key
50
• Program drum
.• Reading section
• Switches
Some of these above mentioned components have been shown in Figure 3 and
Figure 4.
Keyboard
keyboard is perhaps the most popular and widely used device for entering data and
instructions in a computer system. A keyboard is similar to the keyboard of a
typewriter. It contains alphabets, digits, special characters and some control keys. A
general purpose keyboard normally contains cursor control keys and function keys.
Function keys allow user to enter frequently used operations in a single keystroke,
and cursor-control keys can be used -to select displayed objects or co-ordinate
positions by positioning the cursor on the screen.
BSP**
Arrow Keys
Alphabet Keys
Fig. 6. A keyboard
51
When a key on the keyboard is pressed an electrical signal is produced. This signal
is detected by an electronic circuit called keyboard encoder which is a special 1C or a
single-chip microcomputer.. The encoder detects which .key is pressed and sends
the binary code, corresponding to the pressed key, to the computer. The encoder
contains a lockup table in ROM. The binary code is obtained from the lockup table.
Type Purpose
Arrow Keys To move the cursor in the top, down, left and right
directions in a document.
Backspace Key To deleted the character on the left the cursor.
Caps Lock To capitalize letters.
Del To delete the character from the current position of the
cursor.
End To move the cursor to the end of the line
Enter To start a new paragraph in a document.
Esc To cancel a command.
Home move the cursor to the beginning of the line.
Ins To insert characters.
Shift To type the special characters above the numeric keys. If
you press this key along with a number key, the 'special
character above that number will be typed. For example :
To type "#", you have to press the shift key and the
number key 3.
Space Bar To enter a space.
Tab To enter multiple spaces between two words in a
document.
52
Mouse
A. mouse is a pointing device. It is a small hand held box and it is used to position
the cursor on the screen. The -.amount and the direction of movement can be
detected by the wheels or the rollers on the bottom of the mouse. The wheels have
their axes at right angles. Each wheel is connected to a shaft encoder and Whenever
the wheel moves this shaft encoder emits electrical pulses. The distance moved is
determined by the number of pulses emitted by the mouse.
A mouse can be picked up and put down at any position on the screen without
change in cursor movement. By moving the mouse the user can point to menu on
the screen. The mouse generally has two 'or three buttons on its top for indicating
the execution of some operation, such as recording cursor position or invoking a
function. By pressing the button the user indicates his/her choice to the computer.
The movements of the mouse cursor always match that of the mouse. There are
three kinds of clicks. They are left-click, right-click and double click. The mouse can
be used to drag and drop objects on the screen.
Note. : It is a good practice to use the mouse pad instead of just any fiat surface for
movement of the mouse.
53
Joystick
A joystick is also a pointing device (See Figure 8). It is used to move the cursor
position on the screen. It consists of a small, vertical lever fitted on a base. This lever
is used to move the cursor on the screen. The screen-cursor movement in any
particular direction is measured by the distance that the stick is shifted or moved
tram its center position. The amount of movement' is measured by the
potentiometers-that are plugged at the base of the joystick. When the stick is
released, a spring brings it back to its center position. The joystick can move right or
left, forward or backward.
Tracball
A trackball is also a pointing device (See Figure 9). It consists of a ball which is fitted
on a box. The ball can be rotated, with the fingers or palm of the hand to move the
cursor on the screen. The amount, and direction of rotation can be detected by, the
potentiometers which are attached to the ball. Trackballs arc generally fitted on
keyboards.
54
While a trackball is a two divisional positioning devices, a spaceball provides six
degrees of freedom. A spaceball does not actually move. The amount and direction
of movement is determined by the strain gauges that measure the amount of
pressure applied to the spaceball as the ball is pushed and pulled in various
directions.
Touch Panels.
A touch, panel is a very sophisticated and user friendly input devices. It allows the
displayed objects or screen positions to be selected by the touch of a finger. "There
are three methods by which an input to the touch panel can be recorded namely
optical, electrical or acoustical methods.
An: optical touch panel has a line of infrared light emitting diodes (LEDS) along one
vertical edge and along one horizontal edge of the frame. Light detectors are fitted
along the opposite vertical and horizontal edges. Now when the 'panel is touched
these detectors take a note of all the beams that are disturbed by the touch. The two
crossing beams that are interrupted identify the horizontal and vertical co-ordinates
of the screen position selected.
The touch panels are generally used for applications Where the processing options
are represented with graphical ions.
55
Light Pen.
It is yet another pointing device (See Figure 10). It is used to select screen positions
by detecting the light *coming from points on the CRT screen. It is a penlike device
which is photosensitive. When the tip of the pen touches
the screen then the position on the CRT screen is detected by the pen. An activated
light pen, pointed at a spot on the screen as the electron beam lights up that spot,
generates an electrical pulse that causes the co-ordinate position of electron beam
to be recorded. The light pen can be used to draw directly on the CRT screen.
Digitizer
A digitizer is an input device that can also be called a graphics tablet, i.e., a digitizer
and a graphics tablet can be one and the same device. There are several versions of
the graphic tablet. The basic type consists of an even surface .containing a series of
parallel wires in the X" and Y directions. Conceptually it is very similar to a piece of
graph paper. A tablet or digitizer consists essentially of three interconnected parts :
56
1. A thin flat plate (known as the platen or, confusingly, the tablet) which forms the
work surface or active area.
3. A controller which converts the electrical signals arising from the interaction of the
pointer and the platen into location information relative to some origin.
The most usual pointing devices are either a stylus or a puck (multiple button
cursor). The puck is probably better for digitizing drawings whilst the stylus is better
for pointing, picking and choosing.
Digitizing is used to input a drawing produced on paper into the graphics system.
The is accomplished by taping the drawing onto the digitizing tablet as per size and
using the input device to locate endpoints of lines, arcs, etc.
Voice-recognition
57
been made to develop a computer that can listen to the users and talk to them. The
voice input to the computer i.e voice-recognition by a computer is much more
difficult than the voice output. It because, of the "’5,-: that the rules for generating
voice through a speaker or a telephone system can easily be diefined compared to
the rules for interpreting words spoke by a person. The tones of speech, speed,
accent" and pronunciation differ from person to person. These differences in speech
makes voice-recognition a difficult job. In a voice input system the speech is
converted into electrical signals employing a microphone. The signals are sent to a
processor for processing. The signal pattern is compared with the patterns already
stored in the memory. A word is recognized only when a choice match is found, and
then the computer gives a corresponding output. At present a voice-recognition
system is costly. In future it is expected to become cost effective and will be widely
used for direct entry of data. IBM has developed "a Talk writer with 6000 words. It is
capable of detecting words with 95% accuracy.- It is meant for business
correspondence. A voice-recognition system can be used in factories at places
where both hands of worker are engaged in the job he is doing and he wants to input
some data into the computer. It can also be used to assist bedridden and
handicapped persons in a number of tasks; to- control access to restricted areas; to
identify a customer in a bank etc. Today's programs reach about 95% accuracy at
conversational speeds. Two major voice—recognition systems are IBM's Via Voice
and L&H’s Naturally Speaking.
Touch Screen
Some computers have touch screen which is sensitive to user's touch. One can use
finger to point- the command . -displayed on the screen. It is popular on laptops.
Many techniques have been used to make the screen sensitive to touch as
described below:'
58
(i) 'Capacitive screen uses a device which can sense changes in capacitance when
and where the tiger touches the screen with a stylus or finger.
(ii) Infrared screens have light-emitting diodes and photo detector cells to cover the
screen with invisible light. LEDs emit infrared light and photo detectors receive it.
When the user touches the screen, some light beams are interrupted and the
computer then senses the position of the finger.
Optical Recognition
Optical recognition occurs when a device scans a printed surface and translates the
image the scanner sees into a machine-readable format that is understandable by
the computer. The three types of optical recognition devices are given below1:
(i) Optical Character Recognition (OCR). It uses a device that reads preprinted
characters in a particular font (typeface design) and converts them to digital code.
OCR characters appear on utility bills and price tags on departmental store items.
59
(ii) Optical .Mark Recognition (OMB). It uses a device that reads pencil marks and
converts them into computer-usable form. The best known example is the OMR
technology used to read the various competitive examinations test.
(iii) Optical Bar Recognition (OBR). It is slightly more sophisticated type of optical
recognition. The bar codes are the vertical zebra-striped marks you see on most
manufactured retail products-every candy to cosmetics to comic books. The usual'
bar code system in use is called the Universal Product Code (UPC). Bar codes
represent data, such as name of the manufacturers and the type of product. The
code is interpreted on the basis of the width of the lines rather than the location of
the bar code. The bar code does not have the price of the product. Bar code readers
are photoelectric (optical) scanners that translate the symbols in the bar code into
digital code. In this system, the price of a particular item is set within the store's
computer. Once the bar code has been scanned, the corresponding price appears
on the sales clerk's point-of—sale (POS) 'terminal and on your receipt.
Scanner They are a kind of Input Device. Scanners are capable of entering
information directly into the computer and it is not required to key the information.
This make data entry more interactive, faster and accurate. Examples of scanners
are : Optical scanners and Magnetic-ink character readers.
(I) Optical Scanner. Optical scanners use light source and light sensors to read
information recorded on a paper commonly used optical scanners include Optical
Character Reader (OCR), Optical Mark Reader (OMB) and Optical Bar Code
Readers (OBCR).
60
. j-
The ANSI (American National Standard Institute} has adopted a standard type font
called OCR—A for use with OCRs shown in Figure 12.:
61
ABCDEFGHI J KL MNOPQRS
T U V WX YZ01 23456789. ■■
i
- (} %? : = + / *
SIGN. oooooooooooo
oooooooooooo
ADDRESS
oooooooooooo
CENTER oooooooooooo
oooooooooooo
2testform no. 2 TEST CODE 3 ROLL NUMBER oooooooooooo
oooooooooooo
ooo oo o oooo o oooooooooooo
6 BIRTH DATE
ooo oo o oooo o oooooooooooo
MM DD YY
oo o oooo o
oooooooooooo
oo oo oo ooo oooooooooooo
oo oo oo
o o o
ooo oo o oooo o oooooooooooo
o o o ooo oo o oooo o oooooooooooo
■ o o o ooo oo o oooo o oooooooooooo
o o o ooo oo o oooo o oooooooooooo
o o o
o . o o
oooooooooooo
Q
ooo
62
OMRs come in a variety of sizes and shapes depending on the sizes of the forms to
be read and the required loading and processing capacity of the reader. OMB
devices are easily available for Apple 'and IBM Compatible personal computers.
Optical Bar Code Readers. This method uses a number of lines (bars) of varying
thickness and spacing between them to represent the desired information. Bar codes
are used on most grocery items. An OBCR can read such bars and convert them
into electrical pulses to be processed by a computer. The most commonly used bar
code is Universal Product Code (UPC). The UPC code uses a series of vertical bars
of varying Widths. These bars are 'detected at ten digits. The first five digits identify
the supplier or manufacturer of the item. The second five digits identify individual
product. The code also contains a check digit to ensure that the-information read is
correct or not.
81-87522-11^
Fig. 14. A bar-code
Magnetic Ink Character Readers (MICR). This device was developed in the late
1950s to assist the banking industry in automation of the process of accounting the
bank cheques. MICR devices speed up the processing of input iron and paper
documents which are written with a magnetic ink which contains LT011 Oxide
particles in it. The characters have a standard configuration which makes them
recognizable to humans and at the same time provides signals produced from the
63
read head to electronic circuitry. These signals are analysed to sense the .characters
used and then these arc transmitted to the memory unit. MICR is an example of
patter recognition technique and has successfully replaced the time consuming and
expensive punched card processing. Human involvement is required to encode the
cheque amount and other descriptions thus, some room- for error does remain.
Figure 15 shows the layout of MICR encoding on a personal cheque.
•Terminals. Terminals are much more limited than the personal computers although
they look like them. Terminals have only a screen and a keyboard and the
electronics that allow them to communicate with the computer to which they are
connected and are used only to send information to the computer and receive
information from it. Here we will discuss dumb terminal, intelligent terminals and
Internet terminals. -
• Dumb terminal. It is also known as Video Display Terminal (VDTJ, has a display
screen and a keyboard and can input and output but not process data. Usually the
output is text only. For instance, airline reservations clerks use these terminals to
access a mainframe computer having flight information. Dumb terminals cannot
perform functions independent of mainframe to which they are linked.
• Intelligent terminal. It has its own memory and processor, as well as a display
screen and keyboard. Such a terminal can perform some functions independent of
any mainframe to which it is linked. For example, an automated teller machine
(ATM), a self service banking machine that is connected through a telephone
network to a central computer. Another example is the point-of-sale (POS) terminal,
used to record purchase at a store's checkout counter.
64
2.5 OUTPUT DEVICES
An output device is a device which accepts results from the computer and displays
them to the user. The output device also converts the binary code obtained from the
computer into human readable form.
t
t
\
■ f
j
/' ;
% if'’
4
t
-'2*
• i i_». J
ss
Hard copy output is a computer output, which is permanent in nature and can be
kept in paper files, or can be looked at a later stage, when the person is not using
the computer. For example, output produced by printers or plotters on paper.
Soft copy output is a computer output, which is temporary in nature, and vanishes
after its use. For example, output shown on a terminal screen, or spoken out by a
voice response system. The commonly used output devices are : CRT screen,
printers and plotters.
65
2.5.1 Hard Copy Devices .
Hard copy is printed output. For example, printouts, whether text or graphics, from
printers. Film, including microfilm and microfiche is also considered hard copy
output. The hard copy output devices are printers.
Print Quality
i
We can have a considerable variety in the quality of hard copy. Some of the print
qualities are given below :
Near-typeset quality.
This type of print is similar to what is produced by a typeset machine, such as the
print of a magazine.
Letter-quality.
This type of print is the equivalent of good typewriter print. It is made using solid-line
(fully formed) characters rather than characters made up of dots or lines. This is
used mainly in business letters and in formal correspondence between persons.
Near-letter quality.
All the printers don't produce the fully formed characters but print high-quality
documents using a near-letter quality print. This is done by some printers when the
print head makes multiple passes over the 'same letters, filling in the spaces
between the dots or lines being printed.
66
Standard-quality.
This type of print is provided by the printer when characters composed of dots or
lines are formed by a single pass of the print head. In general, standard-quality suits
for most informal applications..
Draft-quality.
The draft-quality print lies at the low end of the quality scale and sometimes known
as compressed . print. It is sometimes used for rough drafts, informal
correspondence, or computer program printouts. The characters are formed with a
minimum number of dots or lines and are smaller in size than the standard-quality
characters.
Printers
■i A printer is an output device that prints characters, symbols and perhaps graphics
rough paper or another hard copy medium. The resolution or quality of sharpness of
the image, is indicated by dpi (dots per inch), which is a measure of the dots that are
printed in a linear inch. For PC printers, the resolution is in the range 60-1,500 dpi.
They provide information in a permanent readable form. There are a variety of
printers available for various types of applications. Depending upon the speed and
approach of printing, printers can be classified as :
There is yet another classification, depending upon the technology used for printing
'(whether or not, the image produced is formed by physical contact of the print
67
mechanism with the paper). According to-this classification, printers are of two types
Character Printers. Character printers print only one character at a time. They are
low-speed printers and are 'generally used for low volume printing Work. Characters
to be printed are sent serially to the printer. Three of the most commonly used
character printers are described below :
Ribbon Pnpcr
l
Ovwnxcvcr*
\on of
Hnm m«r
Better Quality Printers. Better quality printers are used Where good printing quality
is needed. These printers use a print wheel font known as a daisy wheel. There is a
character embossed on each petal of the daisy wheel. The wheel i§ rotated at a
rapid rate with the help of a motor. In order to print a character, the wheel is rotated.
When the desired character spins to the correct position, a print hammer strikes it to
produce the output. Thus, daisy wheel printers are impact printers. Its speed is in the
range 10-90 CPS (Characters Per Second). It has a fixed font type. Normally 2 or 3
fonts are available. It cannot print graphics.
68
character is printed in a number of steps. One dot column of the dot-matrix is taken
up at a time. The selected dots of a column are printed by the print head at a time as
it moves across a line. The shape of each character i.e., the dot pattern is detained
from the information held electronically in the printer.
flBCDEFGHUKLHN
OPORSTUVW •V «*
lit
0123456789“ «5.
The dot—matrix printers are faster than daisy wheel printers. This speed lies in the
range of30-600 cps. But the print quality of a dot-matrix printer is low as compared to
that of a daisy wheel printer. Dot-matrix do not have fixed character font. So they can
print any shape of character. This allows for many special characters, different sizes
of print and the ability to print graphics such as graphs and charts. These are the
only printers that can use multilayered forms to print ’’carbon copies".
Inkjet Printers. Inkjet printers are non-impact printers. They employ a different
technology to print characters on the' paper. They print characters by spraying small
drops of ink onto the paper. Special type of ink with high iron content is used. Each
droplet is charged when it passes through the valve. Then it passes through a region
having horizontal and vertical deflection plates. These plates deflect the ink drops to
the desired spots on the paper to form the desired character.
69
iz'i .*
/—< - ■ ^; V. S -- .«■ - r •
f^:
L\ «>'•
?K3k
'■»
'*'* i> j
‘<ll4’V'
/. :|J' 4 . . : ? ■ fc
► < x *r •'1^ ?:■
— U»ft
*
o I
! i
•*
}■ . V . »■ ■ <*» , •*>
!
C
: <i i
* mt. i»ryw>"Ti “- T
Inkjet printers produce high quality printing output. The speed of inkjet printers lies in
the range of. 40-300 cps.-They allow all sorts of fonts and styles.
Therefore, the document printed may contain multiple character styles and a variety
of font sizes. Colour printing is also possible by using different coloured inks.
Line Printers. As the name suggests, a line printer prints one line of the text at a
time. They are impact printers and are used for producing high volume paper output.
They are fast printers and the printing speed lies in the range of 300-3000 lines per
minute. Drum printer and chain printer are the most commonly used line printers.
Drum Printer. A drum printer consists of a solid, cylindrical drum which contains
complete raised characters set in each band around the cylinder. The number of
70
bands is equal to the number of printing positions. Each band contains all the
possible characters. The drum rotates at a rapid speed. There is a magnetically
driven hammer for each possible print position. The hammers hit the paper and the
ribbon against the desired character on the drum when it comes in printing position.
The speed ofa drum printer is in the range of200 to 2000 lines per minute.
rrrrrrrrbbr^Hi
Q q qqqqQQQQQQQpi
pppppppppppp* u
P
0 oooooooooooo
N N N N NN N N NN N
M M M M M M M M
Chain Printers. Chain printers use a rapidly rotating chain which is called print
chain. The print chain contains characters. Each link of the chain is character font.
There is a magnetically driven hammer behind the "paper for each print position. The
processor sends all the characters to be printed in one line to the printer. When the
desired character' conies in the print position the hammer strikes the ribbbn and
paper against the character. A chain may contain more than one character set, for
example, 4 sets. The speed lies in the range of400-2400 lines per minute.
71
Complete chain
composed of live
48-chnracler sections
One section of 48 characters
Page Printers. Page printers are non-impact printers. They print one page at a time
at a very high speed of 2,000 lines per minute. They are very costly and are
economical only when printed volume is very high. Page printers are based on a
number of technologies like electronics, xenography arid lasers. These techniques
are called Electro-photographic techniques, in these printers, an image is produced
on a photosensitive surface using a laser beam of other light source. The laser beam
is turned off and on under the control of a computer. The areas that are exposed to
the laser attract toner, which is generally an ink. power. Thereafter, the drum transfer
the toner to the paper. Then the toner is permanently fused on the paper with heat or
pressure in a fusing station. After this drum is discharged, cleaned so that it is ready
for next processing. They can produce 300 pages per minute.
72
Fig. 23. A laser printer.
"The differences between a dot-matrix printer and a laser printer are given in Table
2.
73
Thermal Printers .
These printers are a variation of the non-impact dot-matrix type' in which selected
needles are pressed against heat sensitive paper in a dot-matrix method for
formation of characters. It is not possible to have mass printing with ordinary dot
matrix or other impact printers. However, there is a very little noise" associated with
thermal printers. The advantage of this type of printer over the dot-matrix type is that
the thermal unit is much quieter. These provide, high quality colour output. The
disadvantages are that a special type of paper must be used and it is not possible to
produce multiple copies. These are- expensive and slow also.
LED Printers
The Light Emitting Diode (LED) or Liquid Crystal printers use LEDs which are
cheaper alternatives of laser printers. Here, LEDs are used to produce image on the
drum rather than a laser beam. For example, Epson ERL 5200 Printer.
Plotters
A plotter is an output device used to produce hard "copies of graphs and designs.
They use ink pen or inkjet to draw graphics and drawings. Pens could be
monochrome or multi-coloured. Plotters are slow devices because a lot of
mechanical movement is required during plotting. The graphics and designs -
produced by pen plotters are uniform . and precise and are of very good quality. Pen
plotters are basically of two types : Drum plotters and Flatbed plotters (use pens)
and Electrostatic plotters (do not use pens).
74
Drum Plotters.
In case of a drum plotter there is a drum that moves back and forth to produce
vertical motion. The paper on which the design, has to be made is placed on this
drum. A pen is mounted horizontally across the drum in a pen carriage. The pen
moves horizontally along with the carriage left to right or right to left on the paper to
produce drawings. Coloured drawing can also be produced by using multi-coloured
pens.
Flatbed Plotters
In the case of a flatbed plotter, a paper is spread and fixed over a rectangular flatbed
table. This paper is fixed and does not move. A pen-holding mechanism is designed
to provide all the motion. Multi-coloured graphs and designs can be produced by
using pens with multi-coloured inks.
Top vicw-
s \
l
(2) Pen . T \...................
i carnage t \ (4) Control (5) Writing panel
(1) pen station (3)Ybar \ panel
(pen 1, pcn2,... * ,
pen 8, from bottom to top) (6)pen Prcsure leVer
75
(1) pen station—holris pens ready for use.
(2) Pen carriage-hOlds the pen used or plotting.
(3) Y bar —moves the pen carriage to left and right.
(4) Control panet -’has keys to control the operation of the plotter and lamps which
indicate the status of the plotter.
Electrostatic Plotters. These use electrostatic charges to create images out of very
small dots on specially treated paper. The paper is run through a developer to allow
the image to appear. These are faster than pen plotters and can produce images of
very high resolution. Figure 24shows a flatbed plotter. The cost of a plotter can range
from about $1000 to more than $100000 depending on the machine's speed and
quality of images. Large plotters, used with large computer systems, can produce
drawings upto 8* x 8', or sometimes even larger.
Monitors. These are also known as display screens, CRTs, or simply screens—arc
output devices that show 'programming instructions and data as they are being input
and information after it is processed." The size of a computer screen is measured
76
diagonally from corner to corner in inches. For desktop microcomputers, the most
common sizes are 13, 15, 17, 19 and 21 inches; for laptop 'COInplltBI'S,. 12.1, 13.3
and 14.1 inches.
Monitor Viewable
Screen image
Size area
15 inches 14 inches
17 inches 16 inches
a
21 inches 20 inches
In deciding which display screen to opt, you will require issues of screen clarity (dot
pitch, resolution and refresh rate),
types of monitor (CRT versus flat panel, active-matrix flat panel versus passive-
matrix flat panel), and color and resolution standards (SVGA and XGA).
• Screen clarity—dot pitch, resolution, and refresh rate". Major factors affecting
screen clarity (often mentioned in ads) arc dot pitch, resolution and refresh rate.
These relate to the individual dots known as pixels, which represent the images on
the screen. A pixel, for "picture element”, is the smallest unit on the screen that can
be turned on and offer made different shades.
Dot pitch (dp) is the amount of space between the centers ofadjacent pixels; the
closer the dots, the crisper the. image. For a .28dp monitor, for instance, the dots are
28/100ths of a millimeter apart. Generally, a dot "pitch of .28dp will provide clear
images.
77
Resolution is the image sharpness of a display screen; the more pixels there are per
square, the finer the level of detail attained. Resolution is expressed in terms of the
formula horizontal pixels x vertical pixels. Each pixel can be assigned a colour or a
particular shade of gray. Standard resolutions are 640 x 480, 800 x 600, 1024 x 768,
1280 x 1024, 1600 x 1200 and 1920 x 1440 pixels.
Refresh rate is the number of times per second that the pixels are recharged so that
their glow remains bright. In -general, displays are refreshed 45-100 times per
second. The higher the refresh rate, the more solid the image looks on the screen—
that is, the less it flickers. Refresh rate is measured in hertz; a high-quality monitor
has a . refresh rate of75 hertz—the screen is redrawn 75 times per second.
Type of Monitors
The two types of monitor are CRT and flat-panel. CRT. A CRT, for cathode-ray type,
is a vaccum tube used as a display screen in a computer or video display terminal.
Figure 26 il lustrates CRT display.
I k.'
'i
.T
IT
(
'<
*
J
■ T? - ~
'1
4^
N —-
■m
. .- ■ I
*' * ♦
i
78
The same kind of technology is found not only -in the screens of desktop computers
but also in television sets and fight-information monitors in airports. The CRTs are
considerable cheaper (5-10 times) than flat-panel displays. Figure 27 illustrates the
basic operation of a CRT. A beam of electrons, emitted by an electron gun, passes
through focusing and deflection systems that direct the beam towards specified
positions on the phosphor-coated screen. The phosphor then emits a small spot of
light at each position contacted by the electron beam. The light emitted by the
phosphor fades away rapidly. Therefore, some mechanism is needed to maintain the
screen picture. One way to retain the picture is to redraw the picture repeatedly by
quickly directing the electron beam back over the same points. This type of display is
also called refresh CRT.
A CRT display comes is two varieties. Monochrome [only one colour) and colour
(multicolor). Monochrome displays come in green, blue, orange, yellow, pink, amber,
red and white depending upon the type of phosphor material used.
Magnctc Phosphor
deflection coils coated
screen
Focusing
Election
beam
«• • Connector Election
pins gun
79
green are used. These three phosphor colour dots are put of each pixel position.
One phosphor dot emits a red light, another emits a green light and the third emits a
blue light. Three separate electron beams are employed to illustrate the dots of three
different phosphors. By.varying the intensity of the three electron beams the intensity
of red, blue and green dots is varied. This gives the appearance of a triangular spot
of desired colour.
Electron
B
Selection
G of
shadow mask
R
Magnified
phosphor-dot
triangle
i
Screen
Fig. 28. Operation of three electron gun CRT.
Compared to CRTs, flat-panel displays are much thinner, weigh less and consume
less power. Thus, they are better for portable computers, although they are available
for desktop computers as well. Figure 29 illustrates a flat-panel display
80
I
n
si . iv
Him
hr
-/ '* *
n
>1
/
1
■il
Advantages
• Flexibility of usage.
81
much brighter and sharper' than passive-matrix screens, but they are more
complicated and thus more expensive. They also need more power, affecting the
battery life in laptop computers.
"Video Standards
PCs have graphics cards (also known as video cards or video adapters) that convert
signals from the computer into video signals that can be displayed as images on a
monitor. The monitor then separates the video signal into three colour: red, green
and blue signals. Inside the monitor, these three colours combine to make up each
individual pixel. Video cards have their own memory, video RAM or VRAM, which
stores the information about each pixel. The common colour and resolution
standards for monitors are VGA, SVGA, XGA, SXGA and UXGA. Figure 30
illustrates comparison of video standards :
It was developed by IBM for PCs. In graphics mode, the resolution is either 640 480
or 320 x 200 with. 16 colours and 256 colours respectively. In text mode, VGA
systems provide a resolution of 720 x 400 pixels. The total palette of colours is
2,632,144. It uses analog signals rather than digital signals.
82
Principal
A single pixel Video resolution
standard in pixel
VGA 640 x 480
VGA 320 x 200
VGA 720 x 400
SVGA 800 x 600
XGA 1024 x 768
SXGA 1280 x 1024
i • I UXGA 1600 x 1200
f
It has a resolution of up to 1024 x 768 pixels, with 65,536 possible colours. It is used,
mainly with 17-inch and 19-inch monitors.
It has a resolution of 1280 X 1024 pixels. It is often used with 19-inch and 21 inch
monitors.
83
UXGA (Ultra Extended Graphics Array)
It has a resolution oft 600 X 1200 pixels. It is expected to become more popular with
graphic artists, engineering designers and other using 21-inch monitors.
A computer is capable to storing bulk of data and retrieving or accessing the stored
data as and when required. A personal computer may store a few thousand of
characters whereas a mainframe may store billion of characters. The bulk of data
can’t he stored in the main memory as this memory is costly and naturally some
other cheaper memory . devices arc required. These cheaper memory devices,
called SECONDARY STORAGE DEVICES can store bulk of data at very less cost.
Data are stored in secondary storage in the same binary codes as in the main
storage and are made available to main storage as needed. The commonly used
secondary storage devices are Magnetic Tape, Floppy Disk, Hard Disk and CD-
ROM.
From the above discussion on memory we conclude that computers use two types of
storage or memory. Figure 31 Illustrates the two types of memories.
Memory
Secondary or
Primary of External storage
Internal storage
I 1
Magnetic Tape Floppy disk Hard disk CD-ROM
RAM ROM
The choice' of a particular secondary storage device for a given application mainly
depends upon how the stored information needs to be accessed. Basically there are
two methods of accessing information.
84
(i) Sequential or Serial -Access
A Sequential Access Device is one in which the data can be retrieved in the same
sequence in which it is stored, so that the access time varies according to the
location of storage. Sequential processing is quite suitable for applications like
preparation of monthly pay slips, monthly electrically bill etc. In these" applications,
each record needs to be processed at scheduled intervals. Magnetic rape and
punched paper media-are widely used examples of sequential access storage
devices.
In many applications we need to retrieve a record directly rather than going through
all the records to reach the-desired one. For example : In a computerized bank, we
might need to check the account status of a particular Customer at any instant of
time. In such applications, it is inefficient to use a sequential storage device as most
of the time is wasted in looking for the particular record. For such online real time
processing applications Direct Access Storage Devices are used. These direct
access devices are also called Random-Access devices because the information is
available randomly. Thus, a Direct Access Storage Device is a device in which the
data can be stored randomly and it can be accessed directly. Magnetic Disk and
Magnetic Drum are typical examples of Direct-Access Storage Devices.
Random Access Memory is also known as primary storage; and it temporarily store
85
2. Data before and after it is processed by the CPU.
Because its contents are temporary, RAM is said to be volatile as the contents are
lost when the power goes off or is' turned off This is the reason why you should
frequently—every 5-10 minutes, say—transfer (save) your work on a secondary-
storage device such as your hard disk, in case the electricity goes off while you are
working. 1 :our types of RAM chips are used in PCs which are given below :
• SDRAM. The type of dynamic RAM used in most PCs today is SDRAM
(synchronous dynamic RAM, which is synchronized by the system clock and is much
faster than DRAM. Often in computer advertisements, the speed of SDRAM is
expressed in megahertz.
• SRAM. Pronounced "ess-ram", SRAM (static RAM) is faster than any DRAM and
will retain its contents without having to be refreshed by the CPU.
• . RDRAM. Rambus dynamic RAM, or RDRAM, is faster and more expensive than
SDRAM and is the type of memory used with Intel's P4 chip.
If you are short on memory capacity, you can usually add more RAM chips by
plugging them into the motherboard. Chips can be brought single or in so-called
memory modules, circuit boards that can be plugged into expansion slots On the
motherboard. There are two types of such modules :
86
SIMMs and DIMMs
Bath of these are DRAM chips. A SIMM (single inline memory module) has RAM
chips on only one side. A DIMM (dual inline memory module) has RAM chips on both
sides.
Unlike RAM, to which data and instructions are constantly being added and
removed, ROM (Read Only Memory) cannot be written on or erased by the computer
user without special equipment. ROM chips have fixed start-up instructions. That is,
ROM chips are loaded, at the factory, with programs having special instructions for
basic computer operations sometimes called firmware, such as those that start the
computer or put characters on the .monitor. These chips are nonvolatile; their
contents are not lost when power to the computer is switched off.
in computer terminology, read means to transfer data from an input source into the
computer's memory or CPU. The opposite is write-to transfer' data Porn the
computer's CPU or memory to an output device. Thus, with a ROM chip, "read—
only" means that the CPU can retrieve programs from the ROM chip but cannot
modify or add to these programs.
PROM. A PROM is a programmable ROM. ROM chips are provided by the computer
manufacturers and it is not possible for the user to change the contents of a ROM
chip. However, in a PROM the contents are decided by the user.. The user can store
permanent programs, data or any other kind of information in PROM. PROM are
'programmed to store information using a facility know as PROM programmes.
87
However, once the 'chip has been programmed the recorded information cannot be
changed i.e., PROM becomes a ROM. So PROM is also a permanent storage.
EPROM. A variation to PROM is EPROM which stands for erasable PROM. As the
name suggests it is possible to erase the contents of a EPROM chip unlike a PROM
chip. The stored data in EPROMs is erased by exposing it to high intensity short
wave ultraviolet light for about 20 minutes. EPROMs are used to store programs
which are permanent but need updating.
EEPROM. EEPROM is an electrically erasable PROM. The chip can be erased and
reprogrammed on byte by byte i basis. Hence selective erasing is possible. Its
disadvantage is that it requires different voltages for erasing (21 V), writing (21 V)
and reading (5V) the stored information. It also has high cost and low reliability.
FLASH. EPROM. This is the latest type of ROM, which is becoming very popular.
Using a special program, a manufacturer can modify the contents of the flash
EPROM while it remains in the computer.
Floppy Disks.
A floppy disk is a very popular direct access secondary storage medium for micro
and mini computers.
88
A floppy disk, often called a diskette or simply a disk, is a removable flat piece of
mylar plastic packaged in a 3.5-inch plastic case. Data and programs are stored on
the disk's coating by means of magnetized spots, following standard on/off patterns
of data representation (such as ASCII). The plastic case protects the mylar disk from
being .touched by human hands. Originally, when most disks were larger (5.25
inches), the disks actually were "floppy", not rigid; now the plastic disk inside is
flexible or floppy. Floppy disks are inserted into a floppy-disk drive, a device that
holds, spins, reads data from, and writes data to a floppy disk. Read means taking
data from secondary storage (converted to electronic -signals) to the computer's
memory (RAM). Write means copying the electronic information processed by the
computer to secondary storage.
Sliding
hole cover
f
89
The Floppy Drive is of a moving head variety and therefore the floppy can be
removed and replaced by another. The head actually contacts the surface during
reading/writing, though in other times it is lifted up from the surface. The hole at the
centre is to allow a spindle to lock the floppy so that it can rotate. The Index hole is
used to recognize the starting sector of any track. The purpose of write permit notch
is to protect valuable information recorded on the floppy from accidental damage. If
this notch is covered, writing is not allowed on the floppy, only reading is possible. If
the notch is not covered reading as well as writing is possible.
A new floppy can't be used without formatting it. Formatting a disk is to create a set
of magnetic concentric circles called tracks. Tracks are further divided into sectors.
Most high density disks have 80 tracks.
(I) Moving files between computers that are not connected through communication
channel..
(iii) Backing up data or programs, the primary" copy of which is stored.on hard disk.
Note.: Do not remove the disk when the access light is on.
Let us compare the 3.5 inch floppy disk with some 3.5 inch floppy-disk cartridges, or
higher-capacity removable disks—Zip disks, Super Disks and HiFD disks :
• 3.5 Inch floppy-disks-1.44 megabytes : The current standard for traditional floppy
disks is 1.44 megabytes, the equivalent of 400 type-written pages. Today's floppy
carries the label 21-1D, in which the 2 stands for "double-sided" (it stores data on
90
both sides) and the HD stands for "high-density" (which means it stores 'more data
than the previous -standard—DD, for "double density").
• Zip disks-100 or 250 megabytes : These are special disks with a capacity of 100
or 250 megabytes, produced by Iomega Corp. At 100-250 megabytes, this is at least
7 0 times the storage capacity of the standard floppy. These are used to "store large
spreadsheet files, database files . image files, websites and multimedia
representation files. These require their own Zip disk drives, which may come
installed on new computers, although external Zip drives are also available in
market.
• Super Disks-120 megabytes : These are disks with a capacity of 200 megabytes,
produced by mation. The Super Disk drive can also read standard 1.44 megabyte
floppy disks, which Zip drives cannot do.
• HiFD Disks-200 megabytes : These are disks with a capacity of 200 megabytes,
produced by Sony Corp. The disk drive can also read standard 1.44 megabytes
floppies. These have 140 times the capacity of today's standard floppy disks.
Hard Disk
Magnetic disk is the most popular direct access storage medium. A magnetic disk is
made of aluminum or other metals or metal alloys instead of "plastic. The disk is
coated on both sides with magnetic material (iron oxide). Unlike a floppy disk, a hard
disk cannot be inserted or removed from the hard disk drive. A disk drive is a device
that writes information on recording platters that resemble gramophone records. Disk
91
drive reads information written on to the disk. In order to increase the storage
capacity a large number of disks or platters are grouped together and are mounted
on a common drive to form a disk pack. A term cylinder is. usually used in case of a
disk pack. A disk pack generally contains 6 platters. One platter has two recording
surfaces one above and the other below it. No data is recorded on the topmost and
the bottom-most surfaces.
Hard disks are quite sensitive devices. The read write head does not actually touch
the disk but rather rides on a cushion of air about 0.000001 inch thick. The disk is
sealed from impurities within a container, and the whole apparatus is manufactured
under sterile conditions. Otherwise, all it would take is a human hair a finger print
smudge, a dust particle, or a smoke particle to cause what is called head crash. A
head crash happens when the surface of the read write head or particles on its
surface come into contact with the surface of the hard-disk platter, causing the loss ■
of some or all the data on the disk. A head crash can also happen when you bump a
.computer too hard or drop something heavy on the system cabinet. So, always take
up backup of data.
Each surface has concentric circles dividing the disk into tracks. Disk drives have
read/write heads for writing to and . reading from the disks. Some disk drives have
fixed read/write heads. In this case, each track has a read/write head associated with
it and therefore, the only delay "in accessing a specific record is the rotational-delay.
Each track is divided into a number of fixed length physical blocks called sectors.
These are like blocks on magnetic tape. Sector is the smallest unit of data for
transfer. The sectors are separated by inter record gaps. Bits of character are
recorded serially in each sector. Disks are available in different sizes and with
different speeds. Different type of disks have different number of tracks and sectors.
Number of tracks is generally 800 and number of sectors per track is 64.
Movable head disk drives have single read/write head per recording surface. The
arm having read/write head moves on the recording surface so that it can be
positioned on any track for reading or writing. All the read/write heads move together
92
and therefore, all the read/write heads are positioned on the tracks on surfaces in the
same plane. The same number of the track on each of the surfaces together are said
to form a cylinder. \
uuuuuu 9 §
EZ
AAAAAAt
uuuuuu 3 cr 3
AAAAAA
vuuuuv § 3
AAAAAA
"| CTWtTW^:
4-
Movable
9
Y//s<AV//sy/s^
access
Fixed access arms >—I Unused arms *Z l of*■ {«—»\
Direction 1
Unused
•surface arm movement surface
Fig. 33. A disk drive havingfixed head. Fig. 34. A movable head disk.
93
I
Track 000
Track 799
Sector
Fig. 35.
frequently sped& speeds in revolutions per minute. A floppy disk chive rotates at only
360 rpm; a 7200—rpm hard drive is going about 300 miles per hour.
Access Time The access time of a record on a disk consists of 3 factors viz, Seek
Time, Latency Time and Data Transfer Time.
Seek Time : It refers to the time taken to position the read/write head at the desired
track on the disk.
Latency Time : It refers to the time taken to position the read/write head at the
desired sector of the track. Latency time depends on the speed of rotation of the
disk.
94
Data Transfer Time : It is the actual time required to transfer the data. The data
transfer time depends upon density of stored data and rotational speed of the disk.
Differences between a Floppy Disk and a Hard Disk The differences between a
floppy disk and a hard disk are given below:
Storage capacity of one surface = No. of tracks x no. of sectors x bytes per sector.
Storage capacity of the disk pace = Storage capacity of one surface x no. of
surfaces’ Number of cylinders No. of tracks per surface
Transfer rate = No. of bytes per track x rotational speed
»
Example. A 6 disk pack has 6'00 tracks per surface. There are 10 sectors per track
and 512 bytes per sector.
95
(ii) How many cylinders does the "disk pack have ?
Solution :
= 30720000
1024 x 1024 Mb
= 1024 x1024Mb
= 29.29 Mb= 30 Mb
(iii) No. of tracks per cylinder = No. of usable surfaces on the disk =10
Everyone who has ever played an audio CD is familiar with optical disks. An optical
disk is a removable disk, usually 4.75 inches in diameter and less than one-twentieth
of an inch thick, on which data is written and read through the use of laser beams.
An audio CD holds upto 74 minutes of high-fidelity stereo sound. Some optical disks
96
are used strictly for digital data storage, but many are used to distribute multimedia
programs that combine text, visuals and sound.
Optical disk storage system consists of a rotating disk which is coated with an thin
metal or- other material that is highly reflective. Optical storage techniques make use
of pinpoint precision which is possible with laser beams. A laser uses a concentrated
and narrow beam of light. Hence, a laser beam is used to write information, to or
read information from an optical disk. I Optical storage devices focus a laser beam
on the recording medium, which is a spinning disk. Some areas of the disk reflect the
laser light into sensor, whereas others scatter the light. As the disk rotates past the
laser and the sensor, a spot that reflects the laser beam into the sensor is interpreted
as binary one, and the absence of reflections is interpreted as binary zero.
The storage density of optical disks is enormous, the storage cost is extremely low
and the access time is relatively fast. An optical disk can hold over 4.7 gigabytes of
data, the equivalent of 1 million typewritten pages. A typical shortcoming of optical
storage devices is that they are permanent storage devices. Data once recorded
cannot be erased and hence the disk cannot be reused.- Extensive research-is being
carried out to develop erasable optical disks. The types of optical disks are :
(iv) DVD-ROM (Digital Versatile or Digital Video Disk, with Read Only Memory).
(i). CD-ROM. For PC users, the best known type of optical disk is the CD-ROM." CD-
ROM (Compact Disk Read Only Memory) is an optical-disk format that is used to
hold pre-recorded text, graphics and sound. The disk's content is recorded at the
time of manufacture and cannot be written on or erased by the user. CD-ROM uses
the • same technology that is used in music CDs. The disk is made of _a resin, such
as polycarbonate and is coated with a material that is highly reflective, usually
97 ■
aluminum. Data is recorded by focusing a laser beam on the surface of the disk. The
laser beam is turned on and off at a varying rate because of which tiny holes (or pits)
are produced on the metal coating. In order to read the stored data, a less powerful
laser beam is focused on the disk surface. This beam is strongly reflected by the
coated surface and weakly reflected by the pits, thereby producing patterns of on-off
reflection that can be converted into electronic signals.
CD-Rom
Laser source—^
Fig. 36. CD-ROM
CD-ROMs do not use concentric circles. Rather they use simple spiral tracks. The
capacity of CD-ROM is 650 M13, equal to over 300,000 pages of text.
(ii) CD -R (Compact Disk Recordable). CD-R can be written to only Once but can
be read many times. This allows users to make their own CD disks, though it is a
slow process. (Recording a complete disk takes 20-60 minutes). The information
recorded once cannot be erased. CD—R disks are most commonly used for archival
applications. Its advantage is high capacity, better reliability and longer life.
(iii) CD-RW (Compact Disk Rewritable). A CD-RW disk, also known as an erasable
optical disk, allows users to record and erase data, so that the disk can be used over
and over again. Special" CD-RW drives and software are needled. CD-RW disks are
98
useful for archiving and backing up large amount of data or work in multimedia
production or desktop publishing. CD-RW disks cannot be read by CD-ROM drives.
(iv) DVD-ROM. A D VD-ROM (Digital Versatile Disk or Digital Video Disk, with Read
Only Memory) is a CD-style disk with extremely high capacity, able to store 4.7-17
gigabytes. The surface of a DVD contains microscopic pits, which represent the Os
and Is of digital code than can be read by a laser.
The DVD drives can also take standard CD-ROM disks, so1 a user can watch DVD
movies and play CD-ROMs using these. DVDs have enormous potential to replace
CDs for archival storage, mass distribution of software and entertainment. DVDs not
only store far more data but are different in quality from CDs. The variants of DVDs
are:
All of these three types are reusable, that is these can be recorded on and erased
many times.
The differences between a hard disk and a CD-ROM are given below :
99
30 milliseconds. 300 milliseconds.
Data can be read or written as and when It is a permanent storage medium. Data
required. These *can be reused. once recorded, cannot be erased and
hence, the CD-ROMs cannot be reused.
Hard disks are not portable. CD-ROMs are portable
Hard disks require a less complicated CD-ROMs require a more complicated
drive mechanism. drive mechanism
Hard disks have 'a very large storage It has a storage capacity of about 650
capacity (Disk packs have ) virtually Megabytes.
unlimited storage capacity.
It is costly It is cheap.
Not a better storage medium for data CD-ROMs have a data storage life in
archiving as compared to CD-ROMs. excess of 30 year. These are a better
storage medium for data archiving as
compared to Hard disks.
Magnetic Tape
Magnetic tape is a secondary storage device which can hold large volumes of data
on it. The tape is a sequential access media and data on it can be accessed
sequentially. Large files are stored on them. It is one of the most popular. storage
media because of lower cost.
The Magnetic tape is made up of thin plastic ribbon coated on one side with
ferromagnetic material. It is % inch in width and over 2500 ft. long. The coated side
of the tape is usually divided into nine horizontal rows called tracks. Along the Width
of the tracks every "character is stored with one bit in each track. The eight bits of
EBCDIC or ASCII code of the character occupy 8 tracks while the ninth track is used
as.' parity bit.
100
The density ofrecording on a tape is the number of characters per inch on the tape.
Typical tape densities are 800 bpi (bytes per inch), 1600 bpi and 6250 bpi. Records
are written one after the other on the tape. The processing program reads one
record at a time into the primary memory for the data to be processed. During the
time this record is being processed the tape drive stops. It will be moving the tape
under the magnetic read/write head when the next record
Track 1 i
Track 2 1
Track 3 0
Track 4 0
Track 5 1
Track 6 0
. Track 7 1
Tracks G
Track 9 (Parity Bit) 0
is to be read. So between reading two consecutive records the tape drive stops and
starts again. During the time that the drive deaccelerates to stop and accelerates
again to a constant speed at which data from the tape is read a certain length of tape
is empty. This empty portion of tape which occurs between every two records is
called Inter Record Gap (IRG).
101
The IRGs are a wastage of storage space of the tape and cause slowing down of the
program execution. Hence, a number of records are grouped together into a block
and one block is transferred at a time into the buffer area in the Computers primary
memory. The individual records are read one by one by the program from this buffer
memory for processing. The tape drive has to stop and start between reading of
blocks. Once again gaps called Inter Block Gaps (IBGs) are generated between
blocks of data. Since the IBG occur less frequently than the IRGs the empty space in
the tape is reduced.
The initial and final few ft. of the magnetic tape are used for winding on a reel and
hence can’t be used. The beginning and end of the usable part of the tape are
marked by markers called "Load Point" and "End of Reel" markers. The first record
after load point is known as the Header Control Label. This record gives information
about the contents of the tape. Several sequential files may be stored in the tape.
Each file has its own header and trailer markers to identify the beginning and end of
each file.
Tape
*■ s' * • -.S Record Record motion
t
Tape mark
\ t / Interrecord '
(end of file)
Fig. 38. Magnetic tape markers and labels
102.
>
4 One block
Interblock
t
The rate at which data is transferred between the tape and the CPU depends on the
tape drive speed and the density of recording. The actual rate will, however, be lower
than the value due to presence of IBGs and the start/stop time lost.
103
cache speeds up processing. Cache memory, uses special chips, often SRAM (static
RAM) chips. On some systems, these chips are four times as fast as regular
memory. However, the chips cost six times as much. It’s this cost that keeps -them
from being used for the entire system's memory.
The technique used to access cache memory is very different from that of accessing
the main memory. When the CPU accesses main memory, it outputs the data
contained at the specified address. On the other hand the cache memory first
compares the incoming address to the address stored in the ache. If the address
matches, it is said that a 'hit', has occurred. Then the corresponding data are read. If
the address does not match it is said that a 'miss' has occurred. In this case data is
read from the main memory. The data read from main memory is also provided to
cache memory so that when this specific address is accessed next time, a hit may
occur.
Caches are sometimes described by their logical and electrical proximity to the
microprocessor's core logic-. The closed physically, and electrically to the
microprocessor's core logic is the primary cache, also called a Level One Cache or
LI. A secondary cache (or Level Two Cache i.e., L2) lies between the primary cache
and the main memory. The secondary cache or L2 is generally larger than the
primary cache or LI but it operates at a lower speed (to make its larger mass of
memory more affordable).
The currently designed microprocessors have both the primary and secondary
caches as part of the microprocessor itself. Earlier designs have the secondary
cache in a separate part of a microprocessor module or in external memory. LI and
L2 caches differ in the way they connect with the core logic of the microprocessor. L
I invariably operates at the full speed of the microprocessor's core logic with the
widest possible bit-width connection -between the core logic and the cache. L2 often
operate at a rate slower than the chip's core logic, although all current chips operate
the secondary cache at full core speed.
104
A major factor that determines how successful the cache will be is how much
information it stores. The larger' the cache, the more data that is in it and the more
likely any required byte will be available there when your system needs it. Obviously,
the best cache is one that's as- large as, and duplicates, the entirety of system
memory. Chip-makers try to" design caches as large as possible within the
constraints of fabricating microprocessors affordably.
These days primary caches (LI) are of size 64 or 128 KB. Secondary caches (L2)
range from 128 to 512 KB for .0-lips, for desktop and mobile applications and upto 2
MB for server-oriented microprocessors.
In addition, most current computer operating systems allow for the use of virtual
memory-that is, some free hard-dish space is used to extend the capacity of RAM.
Virtual memory reduces the overall cost of the system because it's cheaper to store
data on a hard disk drive than it is to add additional memory chips to the computer.
The processor searches for data or program instructions; in the following order: first
LI, then L2, then RAM, then hard disk (or CD—ROM). In this order, each kind of
memory or storage is slower than its predecessor.
105
Units of Memory
The binary number system has only two digits : 0 and 1. Thus, in the computer, the 0
can be represented by the electrical current being oil’ and the I by the current being
on. All data and program instructions that go into the computer are stored in terms of
these binary numbers.
♦ Bit (Binary Digit). In the binary number system, each 0 or 1 is called a bit, which is
short for "binary digit."
• Byte. To represent letters, numbers, or special characters (such as ? or *), bits are
combined into groups. A group of 8 bits is called a byte, and a byte represents one
character, digit, or other value. The capacity of a computer's memory or of a floppy
i .
disk is denoted in numbers of bytes or multiples such as kilobytes and megabytes.
• Kilobyte. A kilobyte (K, KB) is about 1000 bytes. "(Actually, it's precisely 1024
bytes, but the figure is commonly rounded.) The kilobyte was a common unit of
measure for memory or secondary-storage capacity on older computers. 1 KB
equals about 1/2 page of text. '0 Megabyte. A megabyte (M MB) is about 1 million
. bytes (1,048,576 bytes). Measures of microcomputer primary-storage capacity today
are expressed in megabytes. 1 MB equals about 500 pages of text.
• Gigabyte. A gigabyte (G, GB) is about 1 billion bytes (1,073,741,824 bytes). This
measure was formerly used mainly with mainframe computers, but is typical of the
106
secondary storage (hard disk) capacity of today’s microcomputers (PCs). 1 GB
equals about 500,000 pages of text.
2.7 SUMMARY
• A computer is a fast electronic device that processes the input data and provides
the information as output.
• A computer is more accurate, faster, diligent and has much more memory than
human beings. .
• The Input/Output devices are also known as peripheral devices because they
surround the CPU.
• Printers are broadly classified into two types—Impact and Non-impact printers.
• ROM (Read Only Memory) is one in which information is permanently stored, that
is it is non-volatile memory.
107
• A floppy disk, often called a diskette or simply a disk, is a removable flat piece of
mylar plastic packaged in a 3.5.inch plastic case.
• A hard disk can't be inserted or removed from the hard disk drive.
• An optical disk is a removable disk, usually 4.75 inches in diameter and less than
one-twentieth of an inch thick, on which data is written and read through the use of
laser-beams.
• Magnetic tape is a secondary storage device which can hold large volume of data
on it. It is a sequential access media.
• Cache temporarily stores instructions and data that the processor is likely to use
frequently. Thus, cache speeds up processing.
2. What is an input device ? Name some of the commonly used input devices.
(a) Printers
(c) LED
5. .What are the differences between a hard disk and a CD-ROM '?
108
Unit-Ill
PROGRAMMING FUNDAMENTALS
3.1 INTRODUCTION
*1
-► Output
Input >
Program code ♦m
*
There are various planning tools for mapping the program logic, such as flowcharts,
pseudocode, decision tables and hierarchy charts etc. A program that does the
109
desired work and achieves the goal is called an effective prograM whereas the
program that does the work at a faster rate, is called an efficient program.
The software designing includes mainly two things—progr'am structure and program
representation. The *program structure means how a program "should be. The
program structure is finalised using top-down approach or any other popular
approach. The program structure is obtained by joining the subprograms. Each
subprogram represents a logical subtask.
The program representation means its presentation style so that it is easily readable
and presentable. A user friendly . program (which is easy to understand) can be
easily debugged and modified, if need arises. So the programming style should be
easily understood by everyone to minimize the wastage of time, efforts and cost.
Change is a way of life, so-is the case with software. The modification should be
easily possible with minimum efforts to suit the current needs of the organization.
This modification process is known as program maintenance. *Flowcharting
technique is quite useful in describing program structure and explaining it. The other
useful techniques for actually designing the programs are
no
expression. If computer problem-solving is approached in this spirit then the chances
of success.are very bright..
When lot of efforts are made in understanding the problem we are dealing with,
chances of success are also bright. We cannot hope to make useful progress in
solving a problem until it is clear, what it is we are trying to'solve. The preliminary
investigation may be thought of as the problem definition phase. The problem
definition defines what • the problem is without any reference to the possible
solutions. It is a simple statement, may be one to two pages and should sound like a
problem. The problem definition should be in user language and it should be
described from the user's point of view. It usually should not be defined in technical
computer terms. As the analyst assigns the programs to different programmers
module-wise, the programmers understand the problem given to them. The
'programmers define the problem of each program on a document and proceed for
ill
the next step. In simple words, a lot of care should be taken in working out precisely
what must be done.
The' problem solver should obtain information on the following three aspects of the
problem after the analyses :
1. Input specification .
2. Output specification
3. Special processing, if any. i
1. Input Specifications
(ii) -Input data format i.e., order, spacing, accuracy and units.
(iv) Restrictions, if any, on use of these data values and what to do if an input data is
not accepted by the computer, should it be ignored or modified.
(v) The indication of end of input data (if specified by a special symbol). .
2. Output Specifications
112
(ii) Output data format i.e. , precision (number of significant digits), accuracy, units,
the position on the output sheet and suitable headings for making the output
readable.
(iii) Amount of output required because the program has to be coded according to
the number of output data values required.
It means processing, of input data under some, conditions. If conditions are violated,
certainly results are going to be incorrect. The processing under special condition(s)
and the recovery action should be handled carefully. If the special processing
conditions are ignored and left in the problem definition phase, it may be a costly
affair later on. So, in the problem definition phase, detailed information about input,
output and special processing is gathered. These conditions are taken into
consideration while solving the problem. The method of solution is not specified in
this phase.
There are many ways to solve most of the problems and also many solutions to most
of the problems. This situation makes the job ofproblem-solving a difficult task. When
we have many ways to solve a problem -it is usually difficult to recognize quickly
which paths are likely to be fruitless and which paths may be productive. A block
often occurs after the problem definition phase, because people become concerned
with details of the implementation before they have completely understood or worked
out an implementation-independent solution.
The problem solver should not be too concerned about detail. That can be taken into
account when the complexity of the problem as a whole has been brought under
113
control. The old computer proverb states, "the sooner you start coding your program
the longer it is going to take".
This approach of focusing on a particular problem can often give us' a platform we
need for making a start on the solution .to the general problem. It is not always
possible that the solution to a specific problem or a specific class of problems is also
a' solution to the general problem. We should specify our problem very carefully and
.try to establish . .whether or not the proposed algorithm (step by step procedure in a
finite number of steps to solve a problem) can meet those requirements. If there are
any similarities between the current problem and other problems that we have solved
or we have seen solved, we should be aware of it. In trying to geta better solution to
a problem; sometimes too much study of the existing solution or a similar -problem
forces us down the same reasoning path (which may not be the best) and to the
same dead end. Therefore, a better and wiser way to get a better solution to a
problem is, try to salve the problem independently.
Any problem we want to solve should be viewed from a variety of angles. When all
aspects of the problem have been seen, one should start solving it. Sometimes, in
' some cases, it is assumed that we have already solved the problem and then try to
work backwards to the starting conditions. The most crucial thing of all in developing
problem—solving skills is practice.
Probably the most widely known and most often used principle for problem-solving is
the divide-and-conquer strategy, The given problem is divided into two or more
subproblems which can hopefully be solved more efficiently by the same technique.
114
If it is possible to continue in this way we will finally reach the stage where the
subproblems are small enough to be solved without further splitting.
This way of breaking down the solution to a problem has been widely used with
searching, selection and sorting algorithms.
3.3 FLOWCHARTING
(ii) Provide an Overview. A clear overview of the complete problem and its
algorithm is provided by the flowchart. Main elements and their relationships can be
easily seen without leaving important details.
(iii) Help In Algorithm Design. The program flow can be shown easily wittfthe help
of a flowchart can be easily drawn in comparison to write a program and test it.
115
Different algorithms (for the same problem) can be easily experimented with
flowchart.
(iv) Check tie Program Logic. All the major portions of a program are shown by the
flowchart, precisely. So the accuracy in logic flow is maintained.
(v) Help in Coding. A program can be easily coded in a programming language with
the help of a flowchart. All the steps are coded without leaving any part so that no
error lies in the code..
Flowchart Symbols
Flowcharts have only a -few symbols of different sizes and shapes for showing
necessary operations. Each symbol has specific meaning and function in a flowchart.
These symbols have been standardized by the American National Standards
Institute (ANSI). The basic rules that _a user must keep in mind While using the
symbols are:
116
1. Use the symbols for their specific purposes.
5. Enter and exit the symbols in the same way. The flowchart symbols along with
their purposes are given below :
117
when programs are broken into
Connector modules.
118
v 7*
Stalcinonl 1
Stalciiicnt 2
l
l
Statement IM
I
F*ig. 3. Sequence cnnlml structure.
119
(test condition)
»•
THEN ELSE
(statement) (statement)
I
Fij». 4. Selection control structure (IF-THEN-ELSE).
A variation on the usual selection control structure is the case control structure. This
offers more than a single yes-or-no decision. The case structure allows several
alternatives, or "cases", to be presented. "IF Case 1 occurs, THEN do thousand-so.
IF Case 2 occurs, THEN follow an alternative course..." And so on). The case control
structure saves the programmer the trouble of having to indicate a lot of separate 1F-
THEN-ELSE conditions. Figure -5 illustrates this :
Case
Condition ^
•* s'
i
Fig. 5; Variation on selection: the case control structure.
120
In the iteration, or loop, control structure, a process may be repeated as long as a
certain condition remains true. There are two types of iteration structures—
REPEAT- UNTIL and WHILE-DO. Of these, REPEAT-UNTIL is more often
encountered. ..
REPEAT read in student records UNTIL there are no more student records.
WHILE read in student records DO—that is, as long is—there continue to be student
records.
The difference between the two iteration structures is : If several statements are to
be repeated, we must decide when to stop repeating them. WHILE-DO structure can
be used to stop them at the beginning of the loop. 'Or we can decide to stop them at
the end of the loop using REPEAT-UNTIL structure. REPEAT-UNTIL iteration means
that the loop statements will be executed at least once, because the condition is
tested in the end of loop. One thing that all three control structures have in common
is one entry and one exit. The control, structure is entered at a single point and
excited at another single point. This helps simplify the logic so that it is easier for
others following in a programmer's footsteps to- make sense of the program.
121
REPEAT UNTIL WHILE DO
4 ♦
The systems designer and programmer use the following types of flowcharts in-
developing algorithms :
1. System flowcharts
1. System Flowcharts " It plays a vital role in the ’system analysis. A system is a
. group of interrelated components tied together according to a plan to achieve a j
predefined objective. The elements and characteristics of a system’ are graphically
shown and its structure and relationship are also represented by flowcharts symbols.
The system analysts use the system flowcharts for analyzing or designing various
systems. The different stages of a system are :
122
(i) Problem recognition
(ii) Feasibility
(v) Implementation
(vi) _Evaluation
All the above stages use the system flowchart for convenience. Any alternative
solution for the existing system or the entirely new system can be systematically
represented. The working system is well documented by a precisely drawn system
flowchart.
A. system flowchart indicates the hardware, identifies the various files and
represents the general data flow. A modular program flowchart on the other hand
defines the logical steps for the input, 'output and processing of the information of a
specific program. In structured or modular programs, the independent modules or
units are written for different procedures. This module is useful in performing the
specified operation in other programs too. The exact operation in detail is not
performed but only the relationship and order in which processes are to be
performed Fare-included.
It is also called as block diagram. Its main advantage lies in the fact that the
programmer can concentrate more on flow of logic and temporarily computer level
details are ignored. Alternate algorithms without much time . .consumption or effort
can also be tried using it. These help a lot in communicating the main logic of the
program.
123
3. Detail Program Flowcharts
These are the most comprehensive and elemental charts in developing the
programs. The symbols represented by it are quite useful for coding the program in
any computer language. Each computer language has its own syntax, so "there may
be some difference in performing the operations to be followed for coding a program.
A detail program flowchart represents each minute operation in -its proper sequence,
reduced to its simplest parts.
The following rules and guidelines are recommended by ANSI for "flow-charting :
6. The flow of the flowchart should be from top to bottom and from left to right.
7. For a complex flowchart, use connectors to reduce the number of flow lines. The
crossing of lines should be avoided as far as possible.
124
Levels of Flowcharts
(1) Macro Flowchart. It shows the main segment of a program and shows lesser
details, (ii) Micro Flowchart. It shows more details of any part of the flowchart.
(i) Time Consuming. These take a lot of -time and are laborious to draw with proper
-symbols and spacing, especially for large complex programs.
(ii) Difficult to Modify. Any change or modification in the logic of -the program
generally requires a completely new flowchart for it. Redrawing a flowchart is tedious
and many organizations either do not modify-it or draw the flowchart using a
computer program.
(iii) No Standard Available. There are no standards provided all over the world for
the details to be .included in drawing a flowchart. So different people, draw flowchart
with different views.
125
3.4 STRUCTURED PROGRAMMING CONCEPTS
• Readability
• Clarity of programs.
• Easy modification
The go to statement should be avoided so far as possible. The three basic building
blocks for writing structured programs arc given below :
1. Sequence Structure
2. Loop or Iteration
1 Sequence Structure:
1
I
I
[
T
1
T
P'ig. 7. Scqtidrtcc ■structure.
126
It consists of a single statement or a sequence of statements with a single entry and
single exit as show above.
2. Loop or Iteration :
S'
«-
I
Fig. 9. Binary decision structure.
127
It consists of a condition (simple or compound) and two branches out of which one is
to be followed depending on the condition being true or false as shown above.
MODULAR PROGRAMMING
Main Module
Main Module
Perform A
Perform B
,*4 r Perform C V
Perform D
Module D
Independent modules
arc activated by the Module B
mam module.
Each module returns
the control bade to Module A
the main module
Module C
Fig. 10.
processing inside the module. It should have only one entry point and one exit point.
We can easily modify a module without affecting the other modules. Using this
approach the writing, debugging and testing of programs becomes easier than a
monolithic program. A modular program is readable and easily modifiable. Once we
have checked that 411 the modules are working properly, these are linked together
by writing the main module. The main module activates the various modules in a
predetermined order. For example, Figure 10 illustrates this concept: It must be
noted that each module can be further broken into other sub modules.
128
3.5:1 Characteristics of Modular Approach
(i) The problem to be solved is broken down into major components, each of which is
again broken down if required. So the process involves working from the most
general, down to the most specific.
(ii) There is one entry and one exit point for each module.
(iii) In general each module should not be more than half a page long. If not so, it
should be split into two or more sub modules.
(v) The loops are based on the consistent use of WHILE..DO and REPEAT.. UNTIL
loop structures.
(ii) Modules being small units can be easily tested and debugged.
(iv) The large project can be easily finished by dividing the modules to different
programmers.
(v) The complex modules can be handled by experienced programmers and the
simple modules by junior ones.
129
(vii)The unfinished work of a programmer (due to some unavoidable circumstances)
can be easily taken over by someone else.
(x). Modules are quite helpful in clarification of the interfaces between major parts of
the problem.
Computers are basically used to solve complex problems in a systematic and easy
manner. In order to solve a problem systematically, the solution should be written as
a set of sequential steps. Each of these steps specify some ’simple actions that need
to be performed. Thus an algorithm may be defined as a finite and ordered sequence
of steps which when performed lead to the solution of the problem in d definite time.
Ordered sequence implies that the execution takes place in the same manner or
order in which the statements are written i.e., each step of the algorithm is Written in
such a way that the next instruction follows automatically. The ordering_ is provided
by assigning positive integers to the steps. The words BEGIN and END normally
refer to the beginning and end of the algorithm. A-n algorithm must possess following
characteristics:
1. Finiteness. Finiteness implies that the algorithm must have finite number of
steps. Also the time taken to execute all the steps of the algorithm should be
finite and within a reasonable limit.
2.
130
2. Definiteness. By definiteness it is implied that each step of the algorithm must
specify a definite action i.e., the steps should not be vague. Moreover, the steps
should be such that it is possible to execute these manually in a finite length of time,
3. Input. The term input means supplying initial data for an algorithm. This' data
must be present before any "operations can be performed on it. Sometimes no data
is needed "because initial data may be generated within the algorithm. Thus the
algorithm may have no or more inputs. Generally, the initial data, is supplied by a
READ instruction or a. variable can be given initial value using SET instruction.
4. Output. The term output refers to the results obtained when all the steps of the
algorithm have been executed. An algorithm must have at least one output.
The procedure for expressing algorithm is quite simple. The language used to write
algorithms is similar to our day-to-day life language. In addition, some special
symbols are also used which are described below :
131
contains any previous value then that value is destroyed and the new value is
assigned.
(ii) Relational Symbols. The commonly used relational symbols for algorithms are :
(iii) Brackets ({}). The pair of braces is used to write comments for the purpose of
documentation. For example,
The basic control structures needed for writing "good and efficient algorithms are :
(i) Selection M .
(ii) Branching T
(iii) Looping.
132
(I) Selection.
The selection structure is used when we have to perform a given set of instructions if
the given condition is TRUE and an alternative set of instructions if the condition is
FALSE. The basic statement • available for selection is IF-THEN-ELSE.
The syntax is
Begin
s1
s2
sn
End
ELSE
Begin
fl
f2
fn
End
133
For example, consider the following algorithm which FINDS greater among 2
numbers.
BEGIN
STEPS Then
STEP 4 Else
END
(II) Branching. The branching statement is required when we want to transfer the
control of execution from one part or step of the algorithm to another part - or step.
The statement available for branching is GOTO and its syntax is .GOTO n
where n is a positive integer and specifies the step number where the control of
execution is to be transferred.
(iii) Looping. The looping structure is used when a statement or a set of statements
is to be executed a number of times. The following two loop control structures are
commonly used in algorithms :
(a) WHILE-DO
(b) REPEAT-UNT IL
134
STEP 2 S1
STEP 3 S2
STEP N+1 SN
This control loop structure implies that as long as the condition remains true, all the
steps listed between WHILE-DO and END-WHILE are executed again and again. As
soon as the condition becomes false, the execution of the loop stops and control is
transferred to next statement following END-WHILE.
BEGIN
STEP I Set N 1
STEPS Write N
STEPS END-WHILE
END
This algorithm initially sets the value ofN to I. The while statement then checks if the
value ofN <= 10. If the condition is true it executes steps 3 and 4. When the value of
N exceeds 10 the condition becomes false and the control goes to the statement
following END-WHILE which is END statement marking the END of algorithm.
(b) REPEAT-UNTIL. This is similar to WHILE-DO except the fact that the loop is
executed till the condition remains false or condition becomes true. The syntax is :
135
STEP REPEAT
STEP 2 S 1
STEP 3 S2
.STEP N +1 SN
This control loop structure implies that -as long as the condition remains false, all the
steps listed between REPEAT and UNTIL are executed again and again. As soon as
the condition becomes true, the execution of the loop stops and control is transferred
to next statement following UNTIL (condition). For example, consider the, following
'algorithm :
BEGIN
STEP 1 SetN<~ 1
STEP 2 REPEAT
STEP 3 Write N
END
Initially, the value ofN is set to 1. The loop executes till the value ofN exceeds 10.
After this, the control goes to . the next statement following UNTIL (N > 10).
136
(ii) It is easy to debug 'i.e., errors can be easily pointed out.
(iv) It is compatible to computers in the sense that each step of an algorithm can be
easily coded into its equivalent in high level language.
1. I 1
Begin
goto step 51
End .
ELSE
Begin
End
SEND
137
3.6.4 Algorithm :-Binary Search (Always Applicable on Sorted Data) Given an array
A ofN 'elements in ascending order.- This algorithm searches for an element -DATA.
LOW, HIGH, MID denote the lowest, highest and middle position ofa search interval
respectively.
Begin
goto step 6
End
ELSE
Begin
LOW MID i+ I
ELSE
HIGH—MID-1D.
End
138
5. Write " Unsuccessful search "
6. END
Begin
Repeat for J = I ± 1 1+ 9 „ N
Begin
Begin
A[J] A[J]
End
End
2. - End
139
3.6.6 Algorithm : Insertion in a Sorted Array
goto step 6 i
!
I
End
Begain
-AfPOS + 1] <~A[POS]
End
5. All} <—.DATA
6. M<~M+1 7.-
End
Give two array A and B of size M and N respectively having elements in ascending
order. We Want to merge these .two arrays into array C of size M+N, also in
ascending order. I, J and K denote array indices. Assuming the array indices begin
at 1.
140
1.1 = 1
J= 1
K=1
Begin
Begin
C[K] =A[I11=1+1 .
End
ELSE
Begin
C[K] = BUJ
J=J+ 1
End
K=K+ 1
End
3. IF (l> M) THEN
Begin
Repeat while (J 5 N)
141
End
End
ELSE
Begin
End
En
End
142
P! P2 P3
P2i P22
Fig- II.
1. A large problem is divided into a number of smaller problems using this approach.
The decomposition is continued till the subproblems at the lowest level become easy
to solve. So the overall problem solving becomes easy.
4. - The programs become user friendly (that is easy to read and understand) and
easy to maintain and modify.
143
3.8 BOTTOM-UP PROGRAMMING
3.9 SUMMARY
• John vohn Neumann proposed that the programs be stored in memory. This is
called the stored program concept.
• Computers work because they arc fed a series of step-by-step instructions called
programs.
• Some useful techniques of problem solving other than flowcharting are modular
programming, top-down design, and structured programming.
144
« Modular programming is breaking down ofa problem into smaller independent
pieces (modules).
• Probably the most widely known and most often used principle for problem solving
is the divide-and-conquer strategy. It is widely used with searching, selection and
sorting algorithms.
3. Draw a flowchart and write an algorithm for merging two sorted arrays given in
descending order into ascending order.
4. Draw a flowchart for searching an element from a sorted array (ascending order)
having N elements using binary search method.
145
Unit-IV
FUNDAMENTALS OF C
4.1 INTRODUCTION
"C" is the language’s entire name, and it does not "stand" for anything. Developed at
Bell Laboratories in the year 1.972 by Dennis Ritchie, C is a general-purpose,
compiled language that works well for microcomputers and is portable among many
computers. It was originally developed for writing system software. (Most of the Unix
operating system was written using C.) Today it is widely used for writing
applications, including word processing, spreadsheets, games, robotics, and
graphics programs. It is now considered a necessary language for programmers to
know.
Advantages
2.. C includes many low-level features that arc normally available only in assembly or
machine language.
3. C programs are very concise, due to the large number of operators within the
language.
4. C is a weakly typed language and the programs written in it compile into small
object programs that run or .execute efficiently..
6. C has a high degree ofportability—it can be run without change or little change on
a variety of computers. The advantages written above are also the important
characteristics of C language.
146
Disadvantages
3. It is not suited to applications that require a lot of report formatting and data file
manipulation. For learning how to write programs in C, we must first know what
alphabets, numbers and symbols are used, then how using them constants,
variables and keywords are formed, and finally how are these combined to form an
instruction. A program is written using a group of instructions. Figure 1 illustrates this
Constants
'■ .Alphabets Variables
' Digits Keywords Instructions Programs
Special symbols (Reserved words)
A character represents any alphabet, digit or special character used to form words,
numbers and expressions. The C character set can be divided into the following
groups
147
I
— {A?><. (blank)
White Space Characters — Space, Tab, Carriage return, form feed and newline.
The white space characters are ignored by the C compiler in cases where they arc
not the part ofa string constant. We can use white spaces for separation of words but
i
these are not allowed between the characters of reserved words (keywords) and
identifiers (name of some program element).
4.3. CONSTANTS
1. Primary constants .
2. Secondary constants.
C constants
± 1
Primary constants Secondary constants
148
Let us discuss some C constants which are easy to follow at this stage :
• Integer constants
• Floating-Point constants
• Character constants
• String constants
These are whole numbers without any fractional part. The following rules are
followed for constructing integer Constants :
149
1024 3313 275 -12 32767 -5000
If an integer less than - 32768 is given, an underflow error will occur and if the
integer is more than 32767 an overflow error will occur.
Table 1- illustrates the types of integers with their range and format for 16-bit
worldlength:
150
Octal Integer Constants. These are preceded by 0 (digit zero) and consist of
sequence of digits 0 through 7. For example, decimal integer 14 will be written as
016 as octal integer (as 1410 = 168). The following are some valid octal integer
constants:
0235
047
0
0X7
0x5F
OXaef
These have fractional parts to represent quantities like average, height, area etc.
which cannot be represented by integer numbers precisely.
151
[sign] [integer] - [fraction] [exponent]
where the integer part or the fractional part may be omitted but not both.
The f of lowing rules are Ibl lowed for constructing real constants in fractional from
(a) A floating-point constant in fractional form must have at least one digit befbre and
after the decimal point.
The exponent form consists of two parts : mantissa and exponent. These are usually
used when the constant is either too small or too big. But there is no restriction for us
to use exponential form for other floating constants. In exponent form the part before
'e' is called mantissa and the part after ’e' is called exponent. We can write e or E for
separating the mantissa and exponent. Since the decimal point can "float" due to use
of exponent, the number represented in this form gives the floating-point
representation. The following rules are followed for constructing real constants in
exponent form :
152
(c) The mantissa may have either + or- sign.
(e) The exponent must be at least one digit integer (either positive or negative).
Default sign is +.
+ 15.8E5 .05E -3
’A' ,9,
153
Here the last constant represents a blank space. The character constant '9' is
different from the number 9. Each character constant has an ASCII value associated
with it. For example, the following statements will print 65 and A respectively :
printfp/od", TV);
printf(,,%c,,l ‘65').
Arithmetic operations on characters are possible due to the fact that each character
constant associates an integer .value with it.
These character constants represent one character, although they consist of two
characters. These are also known as escape sequences. These arc interpreted at
■ execution time, The values of these characters are implementation-defined.
C uses some characters such as line feed, form feed, tab, newline etc. through
execution characters £.e., which cannot be printed or displayed directly. Table 2
shows some of the escape sequence characters or back slash character constants :
154
‘\a’ Back slash line
T” Alert Presents with a back slash
Double quote Provide an audible alert
Presents with a double quote
"Hello I World"
"Year 2010"
"Sum"
Remember that a character constant (e.g., ’A') is not equivalent to the single
character string constant (e.g., "A") in C language. As mentioned earlier the
equivalent integer value for 'A' is 65 but "A" does not have any such value. We use
strings in C programs for providing suitable messages in output statements.
Character strings are quite useful in certain situations and are discussed later on.
4.4. VARIABLES
In C, a variable is an entity that may be used to store a data value and has a name.
Variable names are names given to 'different memory ‘locations that store different
kind of data. All C variables must be declared in the program before their use. The
value associated with a variable may vary during program execution. For example,
Let 2 be stored in a memory location and a name sum is given to it. On assigning a
new value 7 to the same memory location sum, its earlier contents are overwritten,
since a memory location can store only one value at a time. Figure 3 illustrates this :
155
Memory Memory
sum sum 7
2
sum “ 2 sum = 7
Fig. 3. Illustrating change in. value of a variable.
sum
num
count
average
principal
rate
time
If we want to calculate the sum of two numbers, the variable can be named as 'sum
rather than langura' or some other cryptic (difficult to understand) name.
As seen earlier, the rules for constructing different types of constants arc different
but for constructing variable names in C the rules are same for all types. The
following rules must be followed while naming variables :
(a) A variable name consists of alphabets, digits and the underscore (—) character.
The length of variable should be kept upto 8 characters though your system may
allow upto 40 characters.
156
(b) They must begin with an alphabet. Some systems also recognize an underscore
as the first character.
For example,
"simple interest, avg marks, total salary are valid but these should be written as si
into a marks, tot sal for sure reorganization by the compiler.
As stated, earlier, all variables in a C program must be declared before their use.
The type of the variables must be , specified at the beginning of the program.
into U
float x,y;
char choice;
157
Here, type specifies the data type-such as into, float, char etc. and var 1, var2, yarn
are variable names separated by Commas. Note that the declaration statement must
end with a semicolon (as shown in all the three declaration statements above).
4.5 DATATYPES 1N C
A data type is a finite set of values along with a set of rules for allowed operations. C
supports several different types of data, each of which is stored differently in the
computer's memory. Data types in C are shown with the help of Figure 4.
Data Type
r I
L I
. ‘l
1
Derived void
Fundamental User defined
.•.a ••
float Functions
double —| Unions
Pointers
The fundamental and user defined data types have been discussed below. The
remaining data types will be discussed in the due course.
4.5.1 The Four Fundamental Data Types . Fundamental data types include the
data types at the lowest level i.e., those which are used for actual data
representation in the memory of the computer. All other data types are based on the
fundamental data types. The fundamental data types in C are :
158
int for integers
Since, the above data types are fundamental i.e., at the machine level, the storage
requirement is hardware dependent. -Table 3 shows the storage requirement of the
above data types on a 16-bit machine :
Table 4. Various data types in C-basic data types and qualifier Table 4 represents
the various data types in C-basic . data types and qualifier.
159
Signed int a signed integer
Unsigned int an unsigned integer
Long int a long integer
Short int a short integer
Long double an extended precision floating point number
Signed short int a signed short integer
Usigned short int an unsigned short integer
Singned long int a signed long integer
Usigned long int an unsigned long integer
Generally size qualifiers cannot be used with data types float and char, and sign
qualifiers are not applicable with float, double and long double. Also note that the
precision means the number of significant digits after the decimal point.
Here signed means that the variable can take both + and — values and unsigned
means only + values are allowed. The keywords short means the variable takes
lesser number of bits and long means greater number of bits.
Remember that char or signed char mean the same, int or short or short int or signed
short int mean the same, long or long int or signed long int mean the same. If we use
short, long or unsigned without a basic data type 'specified, the data type is taken as
an int type by the C compilers.
main
160
int i j;
float a, b;
char grade;
short int n;
• double value ;
/* executable statements */
Note. All floating arithmetic computations in C are carried out in double, mode, i
Whenever, afloat appears in an expression, it is changed to double mode. When a I
double has to be converted to float, double is rounded before truncation to float
length.
161
The above statements tell the compiler to recognize number as an alternative to int
and amount to float. Now, the variables can be created using number and amount as
given below:
The significance of typedef is that we can provide suitable names to existing data
types and make the code easier torcad and understand. Using typedef does not
replace the existing standard C data type -name with the new name, rather we can
now use both for creating variables.
It is generally used when we know in advance the finite set of values that a data type
can take on. The syntax for enumerated data type is given below :
Here, identifier represents the user defined enumerated data type and vail, va!2, va]n
are called members or enumerators.
The variables varl, var2, yarn can take only one value out ofvall, val2, vain. For
example, enum months [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov,
Dec]; enum months month!, month2; 1* variables declared of type months
^Enumerated means that all values are listed. The enumerators are automatically
162
. .assigned values starting from 0 to n-1. Thus the first value Jan will have 0, the
second value Feb will have value 1, and so on, lastly the value Dec will have value
11. The assignment, arithmetic and comparison operations are allowed on
enumerated type variables. For example, monthl = Jan; month2 =Jul; printf("%d",
month2-monthl);,. The above output statement will print 6 as Jul has value 6 and Jan
a 0 with it. The following statement will work as well, if (monthl < month2)
else
We can change the default value assignment by assigning the integer values to the
enumerators. For example,
enum months [Jan = 1, Feb, Mar, Apr, May, Jun, Jul, Aug,_Sep, Oct, Nov, Dec);
Now the enumerators will have values from 1 to 12 respectively. The default ordinal
values can be changed for more than one enumerator also. ..We can combine the
definition and declaration of enumerated variables.
For example
enum months {J an, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec) monthl,
month2; The values assigned to the enumerators need not be distinct, increasing or
positive. For example, • enum values {mid = 16383, low = 0, high = 32767);
163
4.8.1 Assignment Expressions and Assignment Statements
For example
Here the variables prin, rate, time used in the expression on the right hand side of=
must be declared with data types and assigned values before the execution of the
above statement. The above statement is an example of an assignment statement.
var_name = expression;
int J s;
i=20;
i=30; .
printf("\nValue ofs =%d\n", s = i + j);
Value of s =50
164
First the values ofi and j are added, assigned to s and then the value ofs is printed.
inti, j
float x, y, avg;
i=55;
J =250
x =14.0
y =30.0
avg = (x + y)/2.0;
For example
int sum = 0;
165
r •
In C, the same value can be assigned to more than one variables of same type using
multiple assignment statement. The syntax ofa multiple assignment statement is
given below :
Here var_nanlel, var name2, var_name3 are variable names and constant is the
value to be assigned. It can be extended for more than three variables also. The
value is assigned from right to left. For example,
int i, j, k, n;
i=j=k::
When the variable itself takes part In the assignment statement and stores the result
in itself, the arithmetic assignment statement comes into picture. For example,
nurril =100;
num2 =250;
Operators are the verbs of .a language that help the user perform computations on
values. C language supports a rich set of operators. Different types of operators
discussed in this UNIT are:
166
1. Arithmetic operators
2. Unary operators'
4. Logical operators
7. Bitwise operators
x —y
+ add 1
-subtract
‘multiply 3
167
The parenthesis( ) are used to clarify complex operations. The operators + and —
can be used as unary plus and unary minus arithmetic operators also. The unary—
negates the Sign of its operand.
x + y, x — y, x y, x/y, x % y, — x * y
Here x and y are operands. The % operator cannot be used on floating point * data
type.
Here x, y and 5 are operands and the symbols —, *, +, 1. are operators. The
precedence of operators for the expression evaluation has been given by using
parenthesis which will over rule the operators precedence. If x = 25 and y =15, then
the value of this expression will be 80.
168
=3 * (1 * (5+ (12/9)))
=3*(1*(5+1))
=3 *(1 *6)
=3*6
=18
These are used to compare two variables or constants. C has the following relational
operators:.
Operator Meaning
Equals
Not equals
< Less than
> Greater than
<= Less than or equals
>= Greater than or equals
Operator Notation in C
169
NOT I
AND &&
OR
Note. The, notation for the operator OR is given by two broken lines. These follow
the same precedence as in other languages - NOT (I) is evaluated &fore AND (cc.-&)
which is evaluated before OR ( I 0. ParenthesesQ ) can: be used to change this
order
For example,
inta= 2,b=3,c = 4;
a < b 1 (true)
c < a 0 (false)
b== c 0 (false)
c>=b 1 (true)
a! = c 1 (true)
a> 1 1 (true)
When a relational operation is carried out, different types of operands (ifpresent) will
be converted appropriately.
Note. Don’t use = for testing equality. The operator for testing equality is = = (two =
signs/together).
170
In C, the-arithmetic operators have higher priority over relational operators.
Relational operators are used with if, while, do while statements to form relational
expressions which help in making useful decisions. These statements are discussed
later on.
For example, ’
int day;
The logical expression given above is true, when both the relational expressions are
true. If either of these or both are false, it evaluates as false.
C has .a class of operators that act upon a single operand to give a new value.
These type of operators are known as unary operators. Unary operators generally
precede their single operands, though some unary operands are written after their
operands.
Perhaps the most common unary operation is unary minus, where a minus sign
precedes a numerical constant, a variable or an expression. (Some programining
languages permit a minus sign to be included as a part of a numeric Constant). In C,
however, all numeric constants are positive. Thus, a negative number is actually an
expression, having the unary minus operator, followed by a positive numeric
171
constant. Note that the unary minus operation is totally different from the arithmetic
operator which means subtraction (—). The subtraction operator requires two
separate operands.
For example
-(a+b)
-3E-7
Two other commonly used unary operators are the increment operator, + +, and the
decrement operator, that operate on integer data only. The increment (++)
operator increments the operand by 1, while the decrement operator (~) decrements
the operand by 1. For example,
intij;
i =10;
j=i++;
printf("%8c1 %8d", i,j);
Here, the output would be 11 10. First i is assigned to j and then i = is incremented
by 1 i.e., post-increment takes place. If we have
inti.j;
i=20;
j=++i;
printf("%8d%8d", i, j);
The output would be 21 21. First i is incremented by 1 and then assignment, takes
place i.e., pre-increment of i. All the three statements given below are identical:
i=i+1; 1 -H-1 + 1 ;
172
All of these increment the value of i by 1. Now, consider the example for (—) operator
int i,
ji = 10;
t. =
printf ("%8d%8d", i,j);
Here the output would be 9 10. First i is assigned to -j and then i is decremented by 1
i.e., post-decrement takes place. If We have
int i; j;
i =20
J=--i;
printfr/oOdyoBd", i, j); _
The output Would be 19 19. First i is decremented by 1 and then assignment takes
place i.e., pre-decrement of i.
it is an unary operator which provides the size, in bytes, of the given operand. The
syntax of sizebf operator is :
sizeof(operand)
Here the operand is a built in or user defined data type or variable. The sizeof
operator always precedes its operand. For example, sizeof (float) returns the value
4.
173
A cast is also considered to be a unary operator. It has been discussed earlier. In
general terms, a reference to the cast operator is written as given below :
(type)
Thus, the unary operators we have discussed so far in_ this book are—, ++, sizeof
and (type). Unary operators have a higher precedence, than arithmetic operators.
Hence, if a unary minus operator acts upon an arithmetic expression that contains
one or more arithmetic operators, the u-nary minus operation will be carried out first
(if parentheses do not enclose the arithmetic expression). Also the associativity of
the unary operators is right-to-left, though consecutive unary operators rarely appear
in simple programs. For example,
int x, y;
x=5
Y=25;
The value of the expression — x + y will be - 5 + 25 = 20. Here the unary minus is
carried out before the addition • operation. If the expression is — (x + y), then it
becomes — (5 + 25). The value of this expression is — (5 + 25) =— 30. In this case,
the addition is performed first and then the unary minus operation. C has several
other unary operators. These will be discussed, as the need arises.
There are -several different assignment operators in C. All of these are used to form
assignment expressions, which assign the value of an expression to an identifier.
The most commonly used assignment operator is = . Assignment expressions which
use this operator are of the following form :
identer= expression
174
where identifier generally represents a variable and expression, represents a
constant, a variable or a more complex expression.
For example
inti =10;
float a = 5.0;
The lvalue is an entity that appears on the left side of an assignment statement,
whereas the value of something that appears on the right side is called an rvalue. -
The lvalue must have storage space associated with it, that is, has memory address.
If the storage space is not assigned to the entity appearing on the left, the
assignment statement will not be compiled.
The following are not values and hence cannot appear on the left side of an
assignment statement:
type names
The function names have memory addresses but are protected bythe C compiler. C
has the following five additional assignment operators :
+=,—=,*=,/=and%=
175
4.15 FUNCTIONS A .function groups a number of program statements into a single
unit and gives it a name. Every C program is a collection of functions. The function
main() is executed- first and it calls the other functions directly or indirectly. It is
necessary that every C program must have the function main(). We may have user
defined fi 1 nction(s) which can be called (invoked) from other parts of the program.
Functions are the building blocks of C programs where all the program activity
occurs.
(i) A complex program can be divided into small subtasks and function sub-programs
can be written for each.
176
(iv) C has the facility of defining a function in terms of itself i.e., recursion. Recursion
suits to some processes but not all. (v) Many functions such as seanf(), printfO, Nl-to
etc. are kept in C library and the compiler of C is written • • for calling any such
function.
In C, functions return an int value by default i.e., when no type has been specified
before the -function name it will always return an int value.
When we place the function prototype above all the functions (including mainO), it is
known as a global prototype. A prototype declared in global environment is available
for all the functions in the program. When we place the function-prototype inside the
definition of another function (i.e, in the local declaration section), the'prototype is.
known as a local prototype. 'Such declarations' are primarily used by the functions
containing them.
It is a good programming style to have global prototypes for adding flexibility and
enhance documentation. Function prototypes are not mandatory (compulsory) in C.
These are desirable, however, because these help in error checking between the
calls to a function and the corresponding function definition.
177
Note. The function prototype is always terminated with a semicolon.
In C, a function must be defined prior to its use in the program. The function
definition contains the code for the function.
If the called function definition appears before the calling function's definition, then
the called function's prototype may be avoided.
A function can be called (i.e., invoked) by specifying its name, followed by a list of
arguments enclosed in parentheses and separated by commas. If ho arguments, an
empty pair of parentheses must "follow the function's name. The function call may
appear by itself, or it may be one of the operands within an "expression (in case it
returns a value). The arguments or parameters appearing in the function call are
known as actual arguments, in contrast to the formal arguments that appear in the
first line of the function definition. In a normal function call, there will be one actual
argument for each formal argument. The actual arguments may be expressed as
constants, single variables or more complex expressions. However, actual
arguments must match I'n number, type and order with their corresponding formal
arguments.
178
Calling Convention
It specifies the order in which arguments (parameters) are passed to a function when
a function is called. There are two possibilities :
max(a, b, c); .
In this call it doesn't matter whether the parameters are passed from left to right or
from right to left. However, in some cases the order of passing parameters becomes
an important thing. For example,
int x =10;
This however is not, the case. Actually, it outputs 8 8 10;, This is because C's calling
convention is from right to left. That is, firstly 10 is passed through the expression
x—and then x is decremented to 9. Then result of------- x is passed. That' is, x is
decremented to 8 and then passed. Finally latest value ofX, i.e., 8, is passed. Thus
in right to left order 10, 8, 8' get passed. Ounce printfo collects them it prints them in
the order in which we have asked it to get them printed (and not the order of
passing). Thus, 8 8 10 gets printed as the result.
Note : We Must include the appropriate header files when the standard library
functions are used. For example, I <&rlio.'h> for all input! output functions and
<inath.h> for all mathematical functions. A successfully compiled C program might
179
have a mismatch in the format specifies and the variables in the list, in such cases
either garbage values get printed or no values are printed by printfO function.
In C programs, functions that have parameters are called in one of the two ways :
• Call by value
• Call by reference
Call by Value
#include<stdio.h>
main()
int a, b, c;
clrscr ();
180
getch(): /* freeze the monitor */
big=x;
if (y>big)
big=Y; -
if (z>big)
big=z;
PROGRAM 1
60 75 40
a= 60 b = 75 c =40
181
x= 60 y = 75 z =40
In the above program, values entered for the variables a, b and c in the main()
function are passed to the function max(). These values get copied into the memory
locations of the arguments x, y and 2 respectively of the function max° when it is
called. This is shown in Figure 5.
Contents of
a b C 4 Actual arguments
60 75 40
60 75 40 /* -
X y Z ■4 Formal arguments
Fig. 5. Example ofcall by vntuc.
Note : If any function is called with different actual argument(s) more than once in a
program, the same set of statements within the function are executed. Without using
function, the same set of statements would have to be 11 coded the required number
of times in-the function mainO.
The scope of local variables is local to the function in which these are defined and
not outside it. The most important point to remember white using arguments is, that
the actual and formal arguments should match in number, type and order. The actual
and formal parameters use different memory locations and any change in formal
arguments is not reflected back in the -calling function using call by value method.
182
Call by Reference
We know that variables are stored somewhere in memory. In case we are able to
pass the location number (also known as address) of the variable to a function, we
obtain the call by reference method. So, we must be familiar with the knowledge of
how to make a 'call by reference'. For this purpose we require at least an elementary
knowledge of a concept called 'pointers’. So, let us know about the basics of pointer,
which will help a lot in understanding call by reference method of calling C functions.
When a function is without arguments (parameters), it does not receive any data
from the calling function nor does the calling function get any data from the called
function. So, we can say that no data exchange takes place in any direction. Such
type of function cannot be used in any expression and it is always coded as a
standalone statement.
void display (void); implies that the function display0 takes no arguments or returns
no value. Now the function definition is
183
{
display();
There are situations when the calling function sends the data to the called function
after validating it (if necessary). Program 1 falls under this category.
Sometimes we may require that the result from the called function is needed by the
calling function for further use. Such type of function assures a high degree of
portability between programs as it provides a two way communication between the
calling and the called functions.
So far in the programs having functions with arguments, different variable names
have been used for actual and formal arguments. Make it clear that the 'actual
argument(s)' and 'formal arguments can have the same name but the compiler would
treat them as different due to their presence in different function.
In all the programs having formal parameters or arguments, the arguments have
been used taking into account the ANSI method which is more common these days.
184
There is another method also known as Kernighan and Ritchie (orjust K and R)
method, which can be used for declaration of formal arguments.
For example
/* function definition £ () */
float f,(x} —
if (x < —3)
return (-3);
return (x);
else
return (3);
4.18 RECURSION
The main advantage of recursion is that it is useful in writing clear, short and simple
programs.
185
Recursion is implemented using C language, by defining a function in terms of itself,
i.e., function invokes itself. A commonly used example of a recursive procedure is
finding the factorial of a number. The factorial of a number n (denoted as n!) is
defined as :
n!=nx(n-1)l
0!= I
Thus, the complete definition ofthe factorial function is : n I =n x (n— 1)! with 0! = 1
Before writing a recursive function for finding factorial, let us code it non-recursively :
#finclude<stdio h>
main ()
int n;
clrscr ();
186
scanf p/od", &n);'
if (n< '0)
else
prod=prod*i;
return (prod);
PROGRAM 2
Factorial of 10 = 3628800
187
Enter the number for finding factorial:
4.19 ARRAYS
Many applications require the processing of multiple data items that share common
properties (e.g., a set of numerical data, represented by a1, a2 an). The
individual data items can be characters, integers, floating-point numbers, and so on.
Earlier we have used C basic data types. C provides the derived data types also,
which are built from the basic integer and floating data types. An array is a C derived
type that can store several values of one type. An array is a collection of
homogeneous (sametype) elements that are referred by a common name. It is also
called a subscripted variable as the array elements are used by the name of an array
and an index or -subscript. Arrays are of two types :
(ii) Multi dimensional array (2 or more). Here we will study one dimensional and two
dimensional arrays.
Here type declares the base type of the array, which is the type of each element of
the array. The array_name
188
specifies the array name by which the array will be referenced and size defines the
number of elements the array will store. For example,
int a [5];
In C the array index always begins with 0. So, a [2] would refer to the third element in
.the array a where 2 is the array index or subscript. The entire array having elements
55, 90, 17, 88 and 36 can be shown as in Figure 6 :
Memory
0 <F-a[0]
1 a [1]
Name of array a <~a{2]
Array index from 0 to 4 2
3 <— a [3]
4 a[4]
.•' f
Since each element in a is an integer, it occupies two bytes. Notice that the first
element has the index 0. Thus, since - thereare five elements, the last one is number
4.
Name of an' array, without subscripts, also refers to the address of the first element.
Thus, a or a[0] imply same 'address. Or, in other words, name of the array is pointer
to the first element of the array. The & operator may be used to obtain the address of
189
an array element. Thus, &a[0] is address of the element a[0]. Array may be declared
either static or auto.
We can initialize array (i.e., give value to each array element) when the array is first
defined. The general syntax of initialization of arrays is given below :
For example
int: a [5]={55,90,17,88,36};
In case we use an explicit array size, but it is not having the number of elements
equal to size of array, the missing elements will be set to 0. If the number of
elements is greater than the specified size, an error message will be displayed.
Consider few more examples ofarray initialization :
Note that the element salary[3] will be initialized to 0 in the last example.
190
4.20.1 Inputting Array" Elements
For reading the array elements (input operation) we must declare the array first
along with the index to be used on the array. Then the array elements can be
inputted as given ahead :
’inta [5], i;
for(i=0;i<5;-i++).
Such an explicit initialization at run time is known as Run Time Initialization, it is.the
duty of the programmer or user to check that the number of elements entered must
not exceed the size of the array.
a [i]
Since i is the loop.variable in the for loop, it starts at 0 and is incremented until it
reaches 4, thereby accessing each element of array a.
For writing the elements (output operation) from the array, use the following method :
191
for (i=0 ; i<5 ; i++)
The following program illustrates the input, output operations on an array and finds
the sum and average of n numbers.
#include<stdio . h>
#define S 10
main ()
int i, n;
clrscr ();
/.
printff'Enter the number of elements in the array <=%d\n",S};
scanf{"%f,&a[i]);
192
/* find the sum */
for (i=0;i<n;i++).
total+=a [i];
avg=total/n;
PROGRAM 3
Enter 8 elements
10 24 30 22 50 42 66 71
Given array is
Sum =315.00
Average =39.38
193
(}) Calling the function by value
In this method we pass values ofarray elements to the function. The following
program illustrates this Concept:
#include<stdio.h>
mainl)
for(i=0;i<n;i++}
194
H
getch (); /* freeze the monitor */
printf("%8d"1value);
PROGRAM 4
18,27. 15. 38 91
18 27 15 38 91
In the above program, we arc passing an individual array clement at a -time to the
function show( ) and getting it printed in the function show( ). Note that since at a
time only one array element is being passed, this element is assigned to formal
parameter value, in the function showQ and printed there.
195
(ii) Calling the Function by Reference
In this method, we pass addresses of individual array elements to the function. The
following program illustrates this concept:
#include<stdio.h>
#define SIZE 10
mainl)
for(i=0;i<n;i++}
196
void show (int value)
printf("%8dM,value);
PROGRAM 5
Enter 5 elements
18 27 15 38 91
18 '27 15 38 91
In the above program, since at a time the address of one array element is being
passed, this address is assigned to formal parameter value in the function show( ).
For printing, the array element in show() we have used Value at address' operator
(*)•
So far we have manipulated arrays with only one dimension. In C we can have
arrays of two or more dimensions. The two dimensional array is also known as a
matrix.
197
A two dimensional array is a grid having rows and columns in which each element is
specified by two subscripts. It is the simplest of multidimensional arrays. For
example,
.An array a[m] [n] is an m by n table having m rows and n columns containing m x n
elements. The size of the array (total number of elements) is obtained by calculating
m x n. Here, a[i][i] denotes the element in the ith row and jth column. Size of the
array is m x n. . The syntax of declaring a two dimensional array in C is as follows :
type variable_nname [number of rows] {number of columns];
4 n columns >•
0,1 2 J n-2 n-1
0
m-2
- m-1
•*
Fig. 7. Illustration oflogical concept ofa two dimensional array.
We can initialize a two dimensional array when the array is first defined. For
example,
198
float amount [ [4] = {
and similarly, others are enclosed by braces and comma separated. The second
dimension size must be specified when we initialize the two-dimensional arrays in
unsized manner but the first dimension size is optional. Figure 8 shows how the
array amount 11141 declared above looks
199
/
Memory
:•
■ If the number of rows in the above array amount. 1 [4] are increased or decreased in
the initialization, the array will also grow or shrink accordingly.
This is equivalent to
We should -note that the braces mark the end of initialization for a "cluster" of
elements within an array. When all the elements are to be initialized to zero, the
following short-cut method may be used.
200
int arr[3]'[51= {0, 01;
For reading the two dimensional array elements (input operation) we 'must declare
the array first along with the indices to be used on the array. Then the array
elements can be inputted as given below :
# define S = 5
printf ("Enter the size of two dimensional array-<= %d*' %d\n", s, S);
for (j=0;j<n;j++)
201
Elements By accessing array elements we are either inputting these or outputting or
performing some other operation on these. The array elements have been accessed
above by using the statements
scanf("%d",&a[i] 0]);
Here, the expression for array element is a[i][jJ Since i and j are the loop variables, i
is set to 0 and j is incremented until it reaches n, then i is incremented to 1 and j
again varies from 0 ton-1, i.e., the inner for loop is again executed n times. This
process continues until i reaches in and the loop terminates. It means the array
elements have been accessed. For writing the elements’ (output operation) from the
array, use the following method :
The statement printf("\n"); after displaying the elements of a particular row, brings the
control to the next line so that the elements can be displayed in matrix form. The
following program illustrates the concept of two dimensional array for finding the
transpose of a square matrix and stores the result in the matrix itself.
#include<stdio • h>
#define SIZE 5
main ()
202
{
do
clrscr ();
203
for (j=0; j<order;j++1
printf" \n");
/* transpose */
for(i=0;i<order-1 ;i++)
temp=a [ [j];
fOr{i=0;i<order;i++)
■ k)
printf ("\n")-
204
getch(); /* freeze the screen until some key is pressed */
PROGRAM 6.
1 23
456
789
Given matrix is
1 23
456
789
Transpose of matrix
1 47
258
369
205
1. Size of an array is fixed. If we do not know the size requirement, maximum size
array is declared which may result in wastage of space. If we need more space at
run time, it is not possible to extend array.
2. The elements must be homogeneous (i.e., all elements are of same type).
A string is a collection of characters enclosed Within quotes. This type of data is very
important and almost all programming languages have provision to handle it. In C, a
string is defined as a character array being terminated by a NULL character i.e., AO'.
Each element of string is stored as one element in the array housing it-. So the
character arrays must he declared one character longer than the size of the string
we wish to store. The last byte stores the string terminator '\0\
4.24.STRING VARIABLE
It is actually any valid C variable name and is declared as an array of characters. For
example, if an array name is used to store a 20 character string, the declaration must
be
char name[21];
The individual characters of the string are accessed using a subscript. The end of
the string can be checked by comparing the character by NULL, 'character. The
NULL character is not a part of the string, it is merely used to mark the end of the
string. In fact, a string not terminated by NULL character is not really a string, but
merely a collection of characters. The general syntax of string declaration is :
206
char name of stringfsize];
When individual array elements are moved then the terminator must be explicitly
specified. But in case of string assignment, the terminator is automatically attached.
The size of the array is optional when we initialize it and in such cases it is calculated
auto-matically. The following program illustrates this concept:
#include<stdio.h>
main()
{•
int i=0;
clrscr ();
207
printf("%c",beok name[i]J;
i++;
PROGRAM 7
MASTERING C PROGRAMS
The while loop in the above program is terminated when a '\0' character is
encountered in the array book_name.
In C, there are two ways to read and write string data. These are :
208
The Input/Output functions for string type data are :
All of these above mentioned functions have been discussed earlier. Let us use
some' of these functions through programming :
The following program reverses the entered string and prints it.
#include<stdi0.h>
#define SIZE 80
main{)
char string[SIZE],ch;
clrscr ();
ch=getchar ();
while{ch!- \n) {
mid=ien/2;
/* reversal of string */
209
for (i=0; i<mid; i++)
cf^stringflen-l-i];'
string[len*1 -i]=string[i];
string[i]=ch;
linclude<stdio.h>
#include<string.h>
#define SIZE 80
maint)
int diff;
clrscr ();
gets {string);
210
I if {cliff= =0) /* if strings are identical */
else
getch();
PROGRAM 12
jaggu-
A file is a bunch of bytes stored on some storage device like magnetic disk or tape
etc. Most of the application Programs process large volume of data which is
permanently stored in files; We can write programs that can read data from file(s)
and write data to file(s). Compilers read source code files and provide executable
files. Database programs and word processors also work with files.
. Data transfer is generally one or both of the two types given below :
211
(ii) Transfer between the program and a file on disk or tape.
Secondary Memory
Data filcs(s)
Accept
I
Data transfer
Accept Store
data
Data transfer
between console
and program
Console
(Keyboard
and
monitor)
^ Keyboard
So far we have used the technique of data communication between the console unit
and the program. Now we are going to describe the storage and retrieval of data
from the files which overcomes the handling of large volume of data from the
keyboard at run time. Some of the problems which may occur when data is entered
from the keyboard are :
(iii) If the same data is to be processed later on, it would be entered afresh
So for fast data processing, enter the data in computer's main memory," correct it (if
required) and store it in a disk file. Now the data from the file can be read directly at
a very high speed. • In some situations the output of a program may become the
212
input of another program(s). So in such cases it is better to store the output of the
program in a disk file which can be read by other program(s) later on.
Unlike other programming languages C does not distinguish between sequential and
random access (direct access) data files. )
The Turbo C provides two different ways of file processing. These are
(ii) System-oriented Input/Output (low-level I/O). We can perform most of the tasks
by either of these, still there are many important differences between these two. The
major differences are given below :
The Standard U/O is very simple and most commonly used way of performing file I/O
in C language. It provides a vide variety of commands. The 1/0 operations, such as
buffering, data conversions etc. take place automatically. It will be the only system
for 1/0 if the G version has only one system for I/O.
213
The System-oriented 110 reads and writes the data to/from files the same way as
MS-DOS. The data cannot be written as individual characters, or as strings, or as
formatted data. Using this approach the data can be written as a buffer full of bytes.
The programmer must set up the buffer for the data, place the appropriate data, into it
before writing, and take it out from the buffer after reading. It is harder to program
than standard I/O but efficient both in terms of operation and the amount of memory
used by the program.
When working with a standard data file (stream oriented data file), first of all a buffer
area (the portion of main memory which can be directly accessed by the I/O devices)
is established, where the information is kept temporarily during transfer between the
computer's memory and the data file. The buffer area helps in fast read/write
operation from/to the data file. The buffer area is associated by writing.
FILE *fptr;
Here,. FILE (use uppercase letters only) is a special structure type defined within a
system include file, namely stdio.h in DOS. It is not a good practice to use the
members of the FILE structure shown below :
typedef struct
I
unsigned istemp; /* Temporary file indicator */
short token; /* Used for validity checking */
} FILE; /* FILE object*/
fptr is a pointer variable that indicates the beginning of the buffer area. It is also
known as a stream pointer or stream.
A data file must be opened before it can be created or processed. The filename is
associated with the buffer area or the.stream. The Mode of file utilization i.e., read
only, write only or read/write both is also specified while opening the data file.
The syntax of library function fopenO used to open a file is given below :
Here, filename represents the name of the data file and mode specifies the purpose
of opening the file. The filename must be in accordance with the rules for naming
files, as per the operating system in use. The valid modes are given in Table 5.
Mode Purpose
r ’ Open for reading only. The file must already exist
w Open for writing only. If the file already exists, its contents will be
destroyed. If it does not exist, it will be created
a Open for appending (i.e., for adding data to the end of the existing file). If it
does not exist, it will be created
r+ Open for both reading and writing. The file must already exist
w+ Open for both reading and writing. If the file exists, its contents are
overwritten
215
a+ Open for both reading and appending. If the file does not exist, it will be
created.
The fopen() function returns a pointer to the beginning of .the buffer area associated
with the file (if possible); otherwise a NULL value is returned which is defined in
stdio.h. The pointer to the structure type FILE is assigned to fptr. While opening the
file in text mode we can use either "r" or "rt'\ but since text mode is the default mode
we generally drop the f from it.
Note. : For opening a file in binary mode, each of the above shown modes can be
suffixed with letter b .
When the processing is over (reading/writing) in a file, it must be closed. The library
function fclose() performs this task. The syntax of fcloseQ function is given below :
fclose(fptr);
Here fptr is the file pointer associated with the file to be closed. If we do not close
file(s) explicitly using the fclose( ) function, most of C compilers will automatically
close the data file(s) at the end of program execution. Closing a file explicitly
performs the following operations :.
(i) Data from buffer is transferred to the file. It may be noted that the buffer used in
the standard 110 is invisible to the programmer.
i
(ii) The area occupied by the file (area consisting of FILE structure and the buffer
itself) is made free so that it may be used by other files.
The fopen() function for opening file for read/write operations may fail due to anyone
of the following reasons :
216
(i) A file for reading may not be present on the disk.
(iii) Write protected disk does not allow storage of data on it.
The following program statements will provide you a clear idea for checking the
successful opening when we open a file for reading.
#include<Stdi0.h>
main()
FILE *fptr;
ifuiptrd *
exitll;
4.30 POINTERS
Pointers are very useful and important feature of C language. A beginner may find it
a little confusing to start with. But once the concept of pointers is clear the user can
write complex code with great ease, using this powerful tool, ‘making C an excellent
language.
217
A pointer is a variable which holds a memory address which is the location of some
other variable in memory. As a pointer is a variable, its value is also stored in
another memory location. Any variable declared in a 0 program has two components
For example,
int x= 547;
Here, the address 4000 is assumed one, it may be some other address also.
Remember that the address of a variable is the address of the first byte occupied by
that variable in memory. Also the values are stored in binary form inside the memory.
218
Let the address of x be assigned to a variable ptr having address 4036. Since the
value of ptr is the address of the variable x, the value of x can be accessed using the
value of ptr or in other words we can say that the variable ptr 'points to1 the variable
X so it is called a 'pointer1. The above concept can be represented as given shown in
Figure 11:
Pointers arc frequently used in C language, as they offer a number of benefits to the
users. They include :
2. Pointers can be used to return multiple values from a function via function
parameters.
4. For saving the storage space by using the pointer arrays for character strings.
6. Dynamic data structures such as structures, linked lists, stacks, queues and trees
can be easily manipulated Using pointers.
219
7. For reducing the size and complexity of programs.
For storing the address of a" variable, we must declare the appropriate pointer
variable for it. The syntax for a pointer declaration is given below :1
Here, type specifies the type of the variable that is to be pointed to by the pointer
ptr_name. * represents the variable ptr_name as a pointer variable and it heeds a
memory location too. For example,
int x = 597;'
The actual address of a variable in memory is not known to us. So the & (address
operator) is needed for returning the address of the variable following it i.e., a
variable name is followed after &. Similarly, the following statements
fvaiue = 40.5;
ch = ’A’;
fptr = afvalue;
cptr = ech;
220
show the pointer initialization, by first declaring the pointer variables and then making
the pointer variables to point to their respective data type variables. A pointer
variable contains garbage until it is initialized. We should not use a pointer before
initializing it.
Remember that the definition for a pointer variable allocates memory only for the
pointer variable, not for the variable to which it is pointing.
Note. The data type of the pointer mast be same as the data type of the variable to
which it points.
int *iptr;
We can initialize a pointer variable while declaring it, as given below : int num = 85; .
int *iptr= &nunl; /* initialization while declaration */ Note that variable limn is first
declared and then its address stored in pointer variable iptr. The 'following program
prints the different types of variables and their addresses. As the memory addresses
are unsigned integers so we can use %u or %lu format for printing the address
values in integer form or %z_: format for printing the address values in hexadecimal
form.
#inc!ude<stdio.h> main()
char ch;
221
int X;
float y;
x=336;
ch */
clrscrl):
printf{"\n\nValue of y = %.2f',y);
222
-t
PROGRAM 13
Value of ch =J
Address of eh is 65489
Value of x = 336
Address of x is 65490
Value of y =12.50'
Address of y is 65492
In C, the value of a variable (once its address has been assigned to a pointer
variable) can be accessed using the unary operator * (asterisk) known as the
indirection operator.
223
int value, num, *iptr;
value = 2607;
iptr = &value;
num = *iptr;
after the execution of the above statements num and value both have 2007. In C, the
pointers and addresses are utilized by means of symbolic names. A statement like
*336 will not work at all. The following program prints the value of variables using the
#include<stdio.h>
main ()
int x, *iptr;
float y, *fptr;
X=336}
y=l2.5; ’ V
cptr=&oh;
224
I
iptr=&x;
fptr=&y;
olrscr ();
PROGRAM 14
225
You may get some other addresses on your system
Value of ch =J
Address of ch is ffcb
Value of X =336
Address of ch is ffcc
Value of y = 12.50
Address of y is ffce
The operation of writing the value or manipulating it by using * as 'a prefix with a
stores the address of another variable which in turn can store address of another
We know that pointers are used for pointing to different data types. A float, pointer
points to float variables, int type pointer points to integer variables: a char type
pointer points to character variables. In C, there is a general purpose pointer that can
point to any data type and is known as void pointer The. void pointer is a generic
pointer that can represent any pointer type. The syntax of its declaration is given
below:
226
void "vptr; /* pointer to void '__'7
using ", the indirection operator. • A suitable typecast is must prior to dereferencing a
dereferencing operator
f*
((type *)vptr
t type cast
In C, the pointer variables can be used in expression like ordinary variables. Never
can add, subtract integers from pointers, 'subtract one pointer from another. For
example
x = ptrl + 5;
Y= Ptrz" 3;
227
The above statements are valid in C. Also the statements given below will work :
ptrl;
x .= *ptr2 / *ptrl;
y = *ptrl;
We can compare pointers using the relational operators of same types. For example,
statement;
if (ptrl == ptr2)
statement;
if (ptrl 1= ptrz)
statement;
Above type of comparisons are quite useful while dealing with arrays and strings.
But, remember that a comparison of pointers that belong to separate and unrelated
variables is meaningless.
I
As stated earlier, a function groups a number of program statements into a single
unit and this unit can be called from other parts of the program. We know that a
In call-by reference method, the addresses of the actual arguments in the calling
function are copied intathe formal arguments of the called function. So the called
function refers to the original values by the address it accepts. Using pointers we can
return more than one value to the calling function, which is not possible ordinarily by
using a return statement. A return statement can return only a single value.
For example, the following program finds the area and perimeter ofa circle using
pointers :
main()
229
clrscr (1:
scanf &radius}; 7 /*
*a=Prr*r;
*p=2*PI*r;
i PROGRAM 15
>
5
230
i
Radius = 5.00
We know that the name of the array holds the address of the first element (index 0)
char name[21];
Here, name holds the address of name[0] and it is a constant pointer to the first
element. So we can make the conclusion that the name of an array is actually a
pointer.
The following program ill» '-'-'ItBS the manipulation of an array using a pointer:
#include<stdio.h>
main ()
char *cptr;
231
clrscr ();
Here, arr as a pointer is constant, that is, it points to the first element of the array of
characters and we cannot change its value but we can make cptr point to any
i #include<stdio.h> • main( {
232
printf *cptr);
PROGRAM 17
4.37 ARRAYOFPOINTERS
In C, we may have an array of pointers also. For declaring an array storing 3 integer
pointers, we may declare : int '*'num[3]; /"" array of3’integer pointers *1 This can be
0 1 2
Array num
■ s r
233
i
/* print array elements being pointed to by an array of pointers
#inciude<stdiO .h>
Mainll
clrscri); 1
/* array initialization */
num[0]=&a;
nun\ [11=&b;
num[2]=&c; /*
• "i
for (1=0; i<3; i++)
234
I
addresses are in Hexadecimal form */
name of an array denotes its base address */ for (i=0 ; i<3; i++)
PROGRAMM 18
235
4.33 POINTERS AND STRINGS.
An array of char pointers is generally better than two dimensional array of characters
(I), Better utilization of memory (less number of bytes taken by an array of pointers).
individual strings are of varying lengths. Therefore, instead of making each row a
fixed number of characters, we can make it a pointer to a string of varying length. For
example,
declares name to be an array of three pointers to' characters, each pointer pointing
naine[ I Pakistan
This declaration allocates only 25 bytes, sufficient to hold all the three strings as
shown in Figure 13 :
236
I
s r i L a n k a \0
P a k i s t a n \0
1 n d a \0
The character arrays with the rows of varying length are called 'ragged arrays 'and
are better handled by pointers. You tan easily manipulate strings using an array of
pointers.
Common bugs related to pointers and memory management are given below :
(i) Problem of dangling pointers. Such a problem occurs when the programmer fails
237
I
(ii) Problem of null pointer assignment. It may happen that the pointer points to
address 0, which is called NULL. For example, if the pointer is a global variable or
local static variable. In such situations if the pointer is not assigned some valid
address then the computer system will display a message "Null pointer. assignment
on termination of program.
(iii) Problem of memory leaks. Another common problem with pointers is that of
memory leak. Memory leak is a situation where the programmer forgets to release
allocated memory at some stage when goes out of scope and there is no way to
reach that memory block. Even use of goto statement might cause unconditional
jump and we may forget to deallocate the memory allocated earlier. Therefore, care
must be taken to release (deallocate) the allocated memory so that it may be reused.
(iv) Problem of allocation failures. We may face problem of allocation failures using
pointers. An allocation • failure is' a situation when the program through inallocO
callocO, or reallocO function request for a block of memory, and the operating system
could not fulfill the request of desired memory which may not be available in the free
storage pool. So, proper measures should be applied in such cases by the
programmer.
4.40 SUMMARY
238
• C language is case sensitive i.e., uppercase and lowercase characters are not
equivalent.
differently within the computer's 'memory. The basic data types are int, char, float
and double. C has four basic types of constants, these are integer constants,
• An escape sequence always begins with a backward slash (\) and is followed by
• The data items that operators act upon are called operands.
• The operators that act upon a single operand to produce a new value are known as
• The sizeof operator returns the size of its operand in bytes" and always precedes
its operand.
239
• A cast is considered to be a unary operator and a reference to the cast operator is
defined task.
• Every C program has one or more functions, one of these must be called main() in
which the program execution begins. Additional functions (if any) are subordinate to
• Function declaration specifies what is the return type of the function and the types
of arguments it accepts.
• Pointers can be used to make a function return more than one value
simultaneously.
• The use of recursion is not necessarily the best way to solve a problem, even
speed.
• An array is like an ordinary variable except that it can store multiple elements of
same type.
240
• While declaring an array, we -need to specify three things, namely, name, type and
size. • Always remember that array subscripts begin at 0 (not 1) and end at size-1..
• Being an array, all the. characters of a string are stored in contiguous memory
locations.
• Some of the .useful standard library functions for string -manipulation are, strlen(),
• When using string functions for copying and concatenating strings be sure that the
target string is capable of storing the resulting string. Otherwise memory overwriting
may occur.
• A pointer is a variable that represents the location {rather than the value) of a data
241
• Do not store the address of a variable of one type into a pointer variable of another
type.
use a pointer variable before it is assigned, the address of a variable. Pointers are
closely associated with arrays and therefore provide an alternative way to access
• An array name is actually a pointer to the array, i.e., the array name represents the
address of the first element in the array. '41 Ordinary variables cannot be assigned
arbitrary addresses (i.e., an expression such as &mun cannot appear on the lefthand
4. What is data type ? Describe the fundamental data types in 'C language.
'i
5. Write a short note on the following :
242
i
n
6. What is an operator ? Describe various types of operators available in C
10. Clearly differentiate between function prototype, function definition and function
call in C. •
11. What is recursion ? While writing any recursive function what thing(s) must be
12. What conditions must be satisfied by the entire elements of 'any given array ? .
13. What are subscripts ? How are they written .'? What restrictions apply to the
14. How are two dimensional arrays defined ? Compare with the manner in which
one dimensional arrays are defined. Also write about how initial values can be
16. Write a C program to print a matrix along with row and column sum.
243
17. Write a C prOgl'&IH to compute the sum of elements on both diagonals ofa
=18). Take 9 4 I care that in case ofa square matrix of odd order the
20. Explain the following string handling functions : (i) strcatO (ii) strcpyO (iii) strcmpo
21. What are pointers ? Why are they needed ? Explain with an example.
244
I
APPENDIX
development and the methods that can be applied at each stage, once there is
and ensuring that the programmers are as correct as possible at the end of program
1. Problem definition
3. .Coding
4. Debugging
5. Testing
6. Documentation
7. Maintenance
245
The programmer works on several stages at the same time—according, debugging,
testing and documentation are often concurrent activities. Let us discuss debugging
Debugging
programs run correctly the first time, so debugging is an important and time-
Verification ensures that the program does what the programmer intends to do.
Validation ensures that the program produces the correct results for a set of ir test
data. There is no clear demarcation line between these stages. The debugging of
observe register contents directly, the primitive debugging aids, the close interaction
timing, and the difficulty of obtaining adequate data for realgtime applications. The
tools that can be used to debug programs with brief descriptions are given below :
2. Logic analysers. A logic analyser is a test instrument that is the digital bus-
oriented version of the oscilloscope. It detects the states of digital signals during
•i
'j
246
Il .
each clock cycle and stores them in the memory. It then displays the information on
halted, in order to examine the current contents of registers, memory locations and
I/O ports.
4. Trace routines. A trace is a program that prints information concerning the status
6. Software interrupts. The software interrupt or trap instruction is frequently used for
debugging purposes. The instruction usually saves the current value of the program
counter and then branches to a specified memory location. That memory location
can be the starting point of a debugging program that lists or displays status
Each program has its own unique errors. Nevertheless, some errors are sufficiently
and memory locations should not be assumed to contain zero at the start of the
program.
247
2. Failure to handle trivial cases, such as an array or table with no elements or only
one element.
5. Jumping on conditions that ha.ve been changed, since they were set to the
desired values.
table or a condition that is never met. Such a failure can cause an endless loop.
7. Confusing addresses and values. Memory location 1000 does not necessarily
8. Confusing numbers and characters. ASCII zero or EBCDIC zero is not the same
as number zero.
Testing
This stage is the validation of the program. Testing ensures that the program
performs correctly the required tasks. Program testing and program debugging are
closely related. Testing is essentially a later stage of debugging in which the program
248
is validated by trying it on a suitable set of test cases. Some of the test cases will
certainly be the ones used in debugging-the all-zeros case, the various special cases
and other obvious cases that must be checked. Program testing is, however, more
than a simple matter of exercising the program a few times. Exhaustive testing of all
possible cases is the best alternative, but this process is usually impractical. Formal
validation methods exist, but are only applicable to very simple programs. Thus
program testing requires a choice of test cases. The Situation is further complicated
by the fact that -many microcomputer programs depend on realtime inputs that are
with a large and complex system. How care the necessary data be generated and
presented to the microcomputer ? Several tools are available to help with this task.
Among the rules that can aid in program testing are the following':
1. Make the test plan part of the program design. Testing should be one of the
2. . Check all trivial and special cases. Often the simplest can lead to the most
3. Select test data on a random basis. Doing so will eliminate any inadvertent bias
caused by the programmer selecting test data. Random number -tables are widely
249
4. Plan and document software testing just like hardware testing. Obviously, testing
can never prove that no errors exist; so good software design, like good hardware
5. Use the maximum and minimum values of all variables as test data. Extreme
6. Use statistical methods in planning and evaluating complex tasks. Methods are
available for selecting data and evaluating the significance of results Optimization of
techniques may suggest good choices for system parameters "and efficient sets or
test data.
There are two goals in preparing a test plan. First, a properly detailed test plan
Second; the test plan is used during program testing to prove the correctness of the
program. During this step, a general approach to the testing of the program is
prepared and documented, indicating the number of tests needed and the purpose of
each test. In addition, all input test data is defined in detail, and all expected results
Program testing includes physically running the tests specified in the test plan as
well as correcting errors found in the code during the testing. This step is complete
when the test results have been reviewed and approved by the project leader.
To build a more consistent history of the time expended to complete each step, the
life of the coding step can be defined. The time used in making coding changes
250
I
needed to correct errors that were detected during the test step, is recorded as test
time. This eliminates the question of where to record those hours and facilitates
allowed to record time in any step that has been previously completed. However, if a
flow is detected, that forces redesign of ali or part of a program, this time can be-
some point in the program development process. It has been experienced that
performing this step before any logic is constructed ensures that a usable and
exhaustive plan for proving the correctness of a program is available when the
coding of the program has been completed. This will most likely provide a more
sensible approach to testing all facets of a program with as few test runs as
possible." If the development of a test plan is postponed until after the program is
coded, it will tend to test only those parts of the program which the programmer has
r
j
I
251
1
■m
v'
• &
,1
■ -r
NOTES: V
f
l ■
i- .
?■
.1
\\
Jft
■&
&
t-'
•:
252
?r
mmmwmssm
•;
■"iiSfMBi
• ! - V . . ;
f J o *■: ■<■■'■■ t '
■A
i|
>\9
:< mziriijE ■ :| ".ITJ I'I
• l c-j rr F3
]
V
DIRECTORATE OF
DISTANCE EDUCATION
t i i
*
<
Swami Vivekanand
SUBHARTI UNIVERSITY
Subhartipuram, NH-58, Delhi-Haridwar Bypass Road,
Meerut, Uttar Pradesh 250005
Phone: 0121-243 9043
Website: www.subhartidde.com, E-mail: [email protected]