Computer Application Commerce
Computer Application Commerce
CLASS - XI
Government of Kerala
DEPARTMENT OF EDUCATION
PLEDGE
Prepared by:
State Council of Educational Research and Training (SCERT)
Poojappura, Thiruvananthapuram 695012, Kerala
Website : www.scertkerala.gov.in e-mail : [email protected]
Phone : 0471 - 2341883, Fax : 0471 - 2341869
Typesetting and Layout : SCERT
© Department of Education, Government of Kerala
Foreword
Dear learners,
The syllabus of Computer Applications for the Commerce
discipline has been revised in view of the fact that computer is
used currently as a tool for various applications, especially in
the field of e-Banking, e-Commerce, e-Governance, etc. Higher
studies and placements, at present, greatly demand human
resources with adequate knowledge in computer applications
and information technology. The syllabus and the text book have
been designed in order to provide options for students completing
the course to pursue higher studies in Computer Applications
and Commerce or make contributions in either of the two.
The text book, designed in accordance with the syllabus for the
academic year 2014 - 15, begins with the concept of data
processing and presents a variety of computer hardware and
software for various applications of the times. Besides, the
concerns and remedies for e-Waste management are also
highlighted. A wide coverage is given for computer network and
Internet technology, underlining the virtues and vices in their
use. An exclusive section on applications of Information
Technology and ICT enabled services are also incorporated
considering their widespread usage and career opportunities.
The syllabus and the textbook also ensure a strong foundation
to construct and enhance the problem solving and programming
skills of the learner. The multi-paradigm programming language
C++ is presented to develop programs which enable computers
to manage different real life applications effectively.
I hope this book will meet all the requirements for stepping to
levels of higher education and pave the way to the peak of
success.
Dr P. A. Fathima
Director
SCERT, Kerala
Textbook Development Team
Joy John Prasanth P. M.
HSST, St. Joseph's HSS, HSST, St. Joseph's Boys' HSS,
Thiruvananthapuram. Kozhikode.
Vinod V. Asees V.
HSST, NSS HSS, Prakkulam, Kollam. HSST, GHSS Velliyode, Kozhikode.
Roy John Rajamohan C.
HSST, St. Aloysius HSS, HSST, Nava Mukunda HSS
Elthuruth, Thrissur, Thirunavaya, Malappuram.
Aboobacker P. Shajan Jos N.
HSST, Govt. GHSS, HSST, St. Joseph's HSS, Pavaratty,
Chalappuram, Kozhikode. Thrissur.
Mustafa Shamsul Haq K. K. Sai Prakash S.
HSST, GHSS Kuthuparamba, HSST, St. Thomas HSS,
Kannur. Poonthura, Thiruvananthapuram.
Experts
Dr Lajish V. L.
Assistant Professor, Dept. of Computer Science, University of Calicut.
Dr Madhu S. Nair
Assistant Professor, Dept. of Computer Science, University of Kerala.
Madhu V. T.
Director, Computer Centre, University of Calicut.
Dr Binu P. Chacko
Associate Professor, Dept. of Computer Science,
Prajyoti Niketan College, Pudukad.
Dr Sushil Kumar R
Associate Professor, Dept. of English, D.B College, Sasthankota.
Dr Vineeth K. Paleri
Professor, Dept. of Computer Science and Engineering, NIT, Kozhikode
Maheswaran Nair V.
Sub Divisional Engineer, Regional Telecom Training Centre, Thiruvananthapuram
Artists
Sudheer Y.
Vineeth V.
Academic Co-ordinator
Dr. Meena S.
Research Officer, SCERT.
C o n t e n t s
Let us do
Check yourself
Information box
Lab activities
Learning outcomes
1
8
1. Fundamentals of Computer
ANITHA MOHAN
A\nX taml≥
FEMALE
ANITHA
9
• Examine a telephone bill, electricity bill or water bill and
identify the data contained in it.
10
1. Fundamentals of Computer
Thus it is clear that data processing proceeds through six stages, as listed below:
(a) Capturing data
(b) Input of data
(c) Storage of data
(d) Processing / manipulating data
(e) Output of information
(f) Distribution of information
The thick arrow marks in Figure 1.5 indicate the
flow of the activities in data processing and the Fig. 1.5 : Stages of data processing
dotted lines specify the flow of activities that are
optional. Let us take a close look at these stages.
a. Capturing data
When we apply for admission to the higher secondary
course, we usually provide details through a
prescribed application form. The authority is actually
collecting the required data for the admission process through the proforma. This is the
first stage in data processing. The proforma, also known as the source document, is so
designed that all relevant data to be recorded in proper order and format. Thus,
preparation of hard copy of source document and data collection are the activities that
take place in this stage. Today, prescribed application forms are not used for collecting
data. Instead, data are directly entered through on-line facility.
b. Input
In the case of seeking admission, we submit the filled up application form to the school.
There the data is extracted and fed into the
computer. Sometimes, we may enter these details
directly into the computer. Feeding data to the
computer for processing is known as input. The
input data is usually stored in computers before it is
processed.
c. Storage
In many cases, the amount of data given to the computers will be large. Besides, the
data entry may not be completed in a single session or a day. In the case of admissions,
the data of lakhs of applicants is input to the computer. It usually takes a few weeks to
complete the data entry. So the data input at different times should be stored then and
there. The processing will start only after the entire data is stored. The information
obtained as a result of processing is also stored in the computer. This stored data and
information can be used in future for various purposes.
11
d. Process
The data stored in computers is retrieved for processing. Various operations like
calculation, classification, comparison, sorting, filtering, summarising etc. are carried
out as part of processing. In the case of admission to the higher secondary course,
Weighted Grade Point Average (WGPA) of each applicant is calculated. Then the
applicants are listed under various categories based on
the descending order of WGPA. Here, school of choice,
course, and performance in various co-curricular
activities are considered. Finally, allotment lists for
schools and allotment slips for applicants are prepared.
e. Output
The information obtained after processing will be
available in this stage. Output stage should provide the
information in such a form that the beneficiary should
be able to take decision or solve the problem. In the
case of admission to the higher secondary course,
allotment slip for the applicant and allotment list for
the school are generated in the desired format as
outputs.
f. Distribution of information
The information obtained in the output stage is
distributed to the beneficiaries. They take decisions or
solve problems according to the information. For
example in higher secondary admission, the allotment
slips are distributed to applicants for joining the school
allotted and allotment lists are issued to the schools for
admitting the eligible applicants. The allotment slips may
be used to prepare admission register or roll list of
classes. The allotment lists may be used to prepare
nominal roll for registering the students for public
examination.
12
1. Fundamentals of Computer
Check yourself
1. Input unit
The collected data and the instructions for their processing are entered into the computer
through the input unit. They are stored in the memory (storage unit). The data may be in
different forms like number, text, image, audio, video, etc. A variety of devices are
13
Fig. 1.7 : Functional units of a computer
available to input the data depending on its nature. Keyboard, mouse, scanner, mic,
digital camera, etc. are some commonly used input devices. In short, the functions
performed by input unit are as follows:
1. Accepts instructions and data from the outside world.
2. Converts these instructions and data to a form acceptable to the computer.
3. Supplies the converted instructions and data to the computer for processing.
2. Central Processing Unit (CPU)
The CPU is the brain of the computer. In a human body, all major decisions are taken
by the brain and other parts of the body function as directed by the brain. Similarly, in
a computer system, all major computations and comparisons are made inside the CPU.
It is also responsible for activating and controlling the operations of other units of the
computer. The functions of CPU are performed by three components - Arithmetic
Logic Unit (ALU), Control Unit (CU) and registers.
a. Arithmetic Logic Unit (ALU)
The actual operations specified in the instructions are carried out in the Arithmetic Logic
Unit (ALU). It performs calculations and logical operations such as comparisons and
decision making. The data and instructions stored in the storage unit are transferred to
the ALU and the processing takes place in it. Intermediate results produced by the
ALU are temporarily transferred back to the storage and are retrieved later when
needed for further processing. Thus there is a data flow between the storage and the
ALU many times before the entire processing is completed.
14
1. Fundamentals of Computer
15
4. Output unit
The information obtained after data processing is supplied to the outside world through
the output unit in a human-readable form. Monitor and printer are the commonly used
output devices. The functions performed by output unit can be concluded as follows:
1. Receives the results produced by the CPU in coded form.
2. Converts these coded results to human-readable form.
3. Supplies the results to the outside world.
Fill up the following table by comparing human beings and the
computer in the context of data processing. In the case of
operations, the organs or components may be specified and for
characteristics, performance may be indicated. You can also add
Let us do
more features.
16
1. Fundamentals of Computer
context concerned to formulate knowledge. Only then problems can be solved and/or
decisions be made appropriately. From the discussions we had so far, computers can
be considered as the best data processing machine. In short, computer may be defined
as an electronic machine designed to accept the data and instructions, performs arithmetic
and logical operations on the data according to a set of instructions and output the
results or information.
1.4.1 Characteristics of computers
We have already recognized some of the characteristics of computers by performing
the learning activity of filling the comparison table given in the Let us do box. As we
know, computers can execute millions of instructions in a second. The results produced
after processing the data are very accurate, but computers do not have adequate
knowledge or intelligence to interpret the results. They only carry out instructions like
an obedient servant. The computer gives correct results only if the data and instructions
given are correct. The term Garbage In Garbage Out (GIGO) is used to mean this
feature. That is, if a wrong input is given to the computer, it will give a wrong output.
Look at Table 1.2 and identify the advantages and limitations of computer.
Computers
Advantages Limitations
Speed: A computer can perform millions of operations in Lack of IQ: Many people
a second or in fraction of second. It can do in a minute, think that computer has
as much work as a man do taking months and years. super human capabilities.
Accuracy: A computer can perform arithmetic operations However this is not true. A
with a very high degree of accuracy. By accuracy, we computer does not have
mean fewer errors in the output and precision with which natural intelligence as
computations are performed. humans have.
Diligence: Since computer is a machine, it can operate Lack of decision making
for long hours untiringly. Unlike human beings, it will not power: Computer cannot
show any emotion or disobey you. Hence computers decide on its own and it
are best suited for routine jobs. does not possess intuitive
capabilities like human
Versatility: Computer can be used to perform many
beings.
different kinds of processing tasks. It is a general purpose
data processing machine.
Huge memory: Computer has enormous memory
capacity. Huge volume of data can be stored in its memory
for processing. The storage capacity can also be increased
as per requirement.
Table 1.2 : Advantages and limitations of computers
17
Check yourself
18
1. Fundamentals of Computer
19
digit is power of 2. Consider an example (1101)2. This binary number can be written in
expanded form as shown below.
Weight 23 22 21 20
Binary Number 1 1 0 1
MSB LSB
= 1×23 + 1× 22 + 0×21 + 1×20
= 1×8 + 1×4 + 0×2 + 1×1
= 8+4+0+1
= 13
The right most bit in a binary number is called Least significant Bit (LSB). The leftmost
bit in a binary number is called Most significant Bit (MSB).
The binary number 1101 is equivalent to the decimal number 13. The number 1101
also exists in the decimal number system. But it is interpreted as one thousand one
hundred and one. To avoid this confusion, base must be specified in all number systems
other than decimal number system. The general format is
(Number)base
This notation helps to differentiate numbers of different bases. So a binary number must
be represented with base 2 as (1101)2 and it is read as “one one zero one to the base
two”.
If no base is given in a number, it will be considered as decimal. In other words, specifying
the base is not compulsory in decimal number.
For fractional numbers, weights are negative powers of 2 (2-1, 2-2, 2-3, ...) for the digits
to the right of the binary point. Consider an example (111.011)2
Weight 22 21 20 2-1 2-2 2-3
Binary Number 1 1 1 0 1 1
MSB (.) LSB
= 1×22 + 1×21 + 1×20 + 0×2-1 + 1×2-2 + 1×2-3
1
= 1×4 + 1×2 + 1×1 + 0× + 1× + 1×
2
= 4 + 2 + 1 + 0 + 0.25 + 0.125
= 7.375
20
1. Fundamentals of Computer
1 0 1 0 1 1 0
1 Weight 82 81 80
8
Octal Number 2 3 6
= 2×82 + 3×81 + 6×80
= 2×64 + 3×8 + 6×1
= 128 + 24 + 6
= 158
For fractional numbers weights are negative powers of 8, i.e. (8-1, 8-2, 8-3, ...) for the
digits to the right of the octal point. Consider an example (172.4)8
Weight 82 81 80 8-1
Octal Number 1 7 2 4
= 1×82 + 7×81 + 2×80 + 4×8-1
= 64 + 56 + 2 + 4×
= 122 + 0.5
= 122.5
21
1.5.4 Hexadecimal number system
A number system which uses 16 symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and
F to form a number is called hexadecimal number system. Base of this number system
is 16 as there are sixteen symbols in this number system. Hence this number system is
also called base-16 number system.
In this system, the symbols A, B, C, D, E and F are used to represent the decimal
numbers 10, 11, 12, 13, 14 and 15 respectively. The hexadecimal digit and their equivalent
decimal numbers are shown below.
Hexadecimal 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
= 2×161 + 13×160 + 4×
= 32 + 13 + 0.25
= 45.25
22
1. Fundamentals of Computer
Table 1.3 shows the base and symbols used in different number systems:
Number System Base Symbols used
Binary 2 0, 1
Octal 8 0, 1, 2, 3, 4, 5, 6, 7
Decimal 10 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Hexadecimal 16 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
Table 1.3 : Number systems with base and symbols
Check yourself
23
1.6.1 Decimal to binary conversion
The method of converting decimal number to binary number is by repeated division. In
this method the decimal number is successively divided by 2 and the remainders are
recorded. The binary equivalent is obtained by grouping all the remainders, with the last
remainder being the Most Significant Bit (MSB) and first remainder being the Least
Significant Bit (LSB). In all these cases the remainders will be either 0 or 1 (binary
digit).
Example:
Find binary equivalent of (80)10.
Find binary equivalent of decimal 2 80 Remainders
number 25.
2 40 0 LSB
2 25 Remainders
2 20 0
2 12 1 LSB
2 10 0
2 6 0
2 5 0
2 3 0
2 2 1
2 1 1
2 1 0
0 1 MSB
0 1 MSB
Hint: Binary equivalent of an odd decimal number ends with 1 and binary of even
decimal number ends with zero.
24
1. Fundamentals of Computer
25
Example: Find octal equivalent of (400)10.
8 400 Remainders
8 50 0
8 6 2 (400)10= (620)8
0 6
1.6.3 Decimal to hexadecimal conversion
The method of converting decimal number to hexadecimal number is also by repeated
division . In this method, the number is successively divided by 16 and the remainders
are recorded. The hexadecimal equivalent is obtained by grouping all the remainders,
with the last remainder being the Most Significant Digit (MSD) and first remainder
being the Least Significant Digit(LSD). Remainders will be 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A,
B, C, D, E or F.
Example: Find hexadecimal equivalent of decimal number 155.
16 155 Remainders
16 9 11 (B) LSD
0 9 MSD (155)10= (9B)16
16 380 Remainders
16 23 12 (C)
16 1 7 (380)10= (17C)16
0 1
1.6.4 Binary to decimal conversion
A binary number can be converted into its decimal equivalent by summing up the product
of each bit and its weight. Weights are some power of 2. (20, 21, 22, 23, ...)
Example: Convert (11011)2 to decimal.
(11011)2 = 1×24 + 1×23 + 0×22 + 1×21 + 1×20 Weight 24 23 22 21 20
= 16 + 8 + 2 + 1 Bit 1 1 0 1 1
= 27 (11011) 2 = (27)10
26
1. Fundamentals of Computer
(1010.11)2 = (10.75)10
27
1.6.5 Octal to decimal conversion
An octal number can be converted into its decimal equivalent by summing up the product
of each octal digit and its weight. Weights are some powers of 8 (80, 81, 82, 83, ...).
Example: Convert (157)8 to decimal. Weight 82 81 80
(157)8 = 1×82 + 5×81 + 7×80 Octal digit 1 5 7
= 64 + 40 +7
= 111 (157)8 = (111)10
Example: Convert (1005)8 to decimal.
Weight 83 82 81 80
(1005)8 = 1×83 + 0×82 + 0×81 + 5×80
= 512+5 Octal digit 1 0 0 5
= 517 (1005)8 = (517)10
1.6.6 Hexadecimal to decimal conversion
An hexadecimal number can be converted into its decimal equivalent by summing up
the product of each hexadecimal digit and its weight. Weights are powers of 16 (160,
161, 162, ...).
Weight 161 160
Example: Convert (AB)16 to decimal.
(AB) = 10×161+11×160 Hexadecimal digit A B
16
= 160 + 11 A = 10 B = 11
= 171 (AB)16 = (171)10
Example: Convert (2D5)16 to decimal.
(2D5)16 = 2×162+13×161+5×160 Weight 162 161 160
= 512+208+5 Hexadecimal digit 2 D 5
= 725 D = 13
(2D5)16 = (725)10
1.6.7 Octal to binary conversion
An octal number can be converted into binary by converting each octal digit to its 3 bit
binary equivalent. Eight possible octal digits and their binary equivalents are listed in
Table 1.6.
Octal digit 0 1 2 3 4 5 6 7
Binary equivalent 000 001 010 011 100 101 110 111
Table 1.6 : Binary equivalent of octal digit
28
1. Fundamentals of Computer
29
1.6.9 Binary to octal conversion
A binary number can be converted into its octal equivalent by grouping binary digits to
group of 3 bits and then each group is converted to its octal equivalent. Start grouping
from right to left.
Example: Convert (101100111)2 to octal.
We can group the given binary number 101100111 from right as shown below.
101 100 111
↓ ↓ ↓
5 4 7
(101100111)2 = (547)8
Example: Convert (10011000011)2 to octal.
We can group the given binary number 10011000011 from right as shown below.
After grouping, if the left 010 011 000 011
most group does not have ↓ ↓ ↓ ↓
3 bits, then add leading 2 3 0 3
zeros to form 3 bit binary. (10011000011)2 = (2303)8
1.6.10 Binary to hexadecimal conversion
A binary number can be converted into its hexadecimal equivalent by grouping binary
digits to group of 4 bits and then each group is converted to its hexadecimal equivalent.
Start grouping from right to left.
Example: Convert (101100111010)2 to hexadecimal.
We can group the given binary number 101100111010 from right as shown below.
1011 0011 1010
↓ ↓ ↓
(101100111010)2 = (B3A)16
B 3 A
Example: Convert (110111100001100)2 to hexadecimal.
We can group the given binary number 110111100001100 from right as shown below.
After grouping, if the left 0110 1111 0000 1100
most group does not have ↓ ↓ ↓ ↓
4 bits, then add leading 6 F 0 C
zeros to form 4 bit binary. (110111100001100)2 = (6F0C)16
30
1. Fundamentals of Computer
31
Table 1.8 summarises the procedures for all types of number conversions that are
discussed in this chapter.
Conversion Procedure
Decimal to Binary Repeated division by 2 and grouping the remainders
Decimal to Octal Repeated division by 8 and grouping the remainders
Decimal to Hexadecimal Repeated division by 16 and grouping the remainders
Binary to Decimal Multiply binary digit by place value(power of 2) and find
their sum
Octal to Decimal Multiply octal digit by place value (power of 8) and find
their sum
Hexadecimal to Decimal Multiply hexadecimal digit by place value (power of 16)
and find their sum
Octal to Binary Converting each octal digit to its 3 bit binary equivalent
Hexadecimal to Binary Converting each hexadecimal digit to its 4 bit binary
equivalent
Binary to Octal Grouping binary digits to group of 3 bits from right to left
Binary to Hexadecimal Grouping binary digits to group of 4 bits from right to left
Octal to Hexadecimal Convert octal to binary and then binary to hexadecimal
Hexadecimal to Octal Convert hexadecimal to binary and then binary to octal
Table 1.8: Procedure for number conversions
1.7 Binary addition
As in the case of decimal number system, arithmetic operations are performed in binary
number system. When we give instruction to add two decimal numbers, the computer
actually adds their binary equivalents. Let us see how
binary addition is carried out. The rules for adding two A B Sum Carry
bits are given in Table 1.9 0 0 0 0
0 1 1 0
Note that a carry bit 1 is created only when two ones
are added. If three ones are added (i.e. 1+1+1), then 1 0 1 0
the sum bit is 1 with a carry bit 1. 1 1 0 1
Table 1.9: Binary addition rules
32
1. Fundamentals of Computer
33
Note: In this method an 8 bit word can represent 28-1 =255 numbers (i.e. -127 to
+127). Similarly, a 16 bit word can represent 216-1 = 65535 numbers (i.e. -32767 to
+32767). So, an n-bit word can represent 2n-1 numbers i.e., –(2n-1-1) to +(2n-1-1).
The integer 0 can be represented in two ways: +0 = 00000000 and –0 = 10000000.
ii) 1’s complement representation
In this method, first find binary equivalent of absolute value of integer. If number of
digits in binary equivalent is less than 8, provide zero(s) at the left to make it 8-bit form.
1’s complement of a binary number is obtained by replacing every 0 with 1 and every
1 with 0. Some binary numbers and the corresponding 1's compliments are given below:
Binary Number 1’s Complement
11001 00110
10101 01010
If the number is negative it is represented as 1’s complement of 8-bit form binary. If the
number is positive, the 8-bit form binary equivalent itself is the 1’s complement
representation.
Example: Represent -119 in 1’s complement form.
Binary of 119 in 8-bit form = (01110111)2
-119 in 1’s complement form = (10001000)2
Example: Represent +119 in 1’s complement form.
Binary of 119 in 8-bit form = (01110111)2
+119 in 1’s complement form = (01110111)2
(No need to find 1’s complement, since the number is positive)
Note: In this representation if first bit (MSB) is 0 then number is positive and if MSB is
1 then number is negative. So 8 bit word can represent integers from -127 (represented
as 10000000) to +127 (represented as 01111111). Here also integer 0 can be
represented in two ways: +0 = 00000000 and -0 = 11111111. An n-bit word can
represent 2n-1 numbers i.e. -(2n-1-1) to +(2n-1-1).
ii) 2’s complement representation
In this method, first find binary equivalent of absolute value of integer and write it in 8-
bit form. If the number is negative it is represented as 2’s complement of 8-bit form
binary. If the number is positive 8-bit form binary itself is the representation. 2’s
complement of a binary number is calculated by adding 1 to its 1’s complement.
For example, let us find the 2’s complement of (10101)2.
1’s complement of (10101)2 = (01010)2
So 2’s complement of (10101)2 = 01010 +
1
= (01011)2
34
1. Fundamentals of Computer
35
To compare the three types of representations let us
consider the following table. For clarity and easy illustration,
4-bits are used to represent the numbers in this table .
36
1. Fundamentals of Computer
In real numbers, binary point keeps track of mantissa part and exponent
part. Since the value of mantissa and exponent varies from number to
number the binary point is not fixed. In other words it floats and
hence such a representation is called floating point representation.
37
memory. For example, ASCII code of A is 65, its binary equivalent in 7-bit is 1000001.
Since there are exactly 128 unique combinations of 7 bits, this 7-bit code can represent
only128 characters.
Another version is ASCII-8, also called extended ASCII, which uses 8 bits for each
character, can represent 256 different characters. For example, the letter A is represented
by 01000001, B by 01000010 and so on. ASCII code is enough to represent all of the
standard keyboard characters.
b. EBCDIC
It stands for Extended Binary Coded Decimal Interchange Code. This is similar to
ASCII and is an 8 bit code used in computers manufactured by International Business
Machine (IBM). It is capable of encoding 256 characters. If ASCII coded data is to be
used in a computer which uses EBCDIC representation, it is necessary to transform
ASCII code to EBCDIC code. Similarly if EBCDIC coded data is to be used in a
ASCII computer, EBCDIC code has to be transformed to ASCII.
c. ISCII
ISCII stands for Indian Standard Code for Information Interchange or Indian Script
Code for Information Interchange. It is an encoding scheme for representing various
writing systems of India. ISCII uses 8-bits for data representation. It was evolved by
a standardisation committee under the Department of Electronics during 1986-88, and
adopted by the Bureau of Indian Standards (BIS). Nowadays ISCII has been replaced
by Unicode.
d. Unicode
Using 8-bit ASCII we can represent only 256 characters. This cannot represent all
characters of written languages of the world and other symbols. Unicode is developed
to resolve this problem. It aims to provide a standard character encoding scheme,
which is universal and efficient. It provides a unique number for every character, no
matter what the language and platform be.
Unicode originally used 16 bits which can represent up to 65,536 characters. It is
maintained by a non-profit organisation called the Unicode Consortium. The Consortium
first published the version 1.0.0 in 1991 and continues to develop standards based on
that original work. Nowadays Unicode uses more than 16 bits and hence it can represent
more characters. Unicode can represent data in almost all written languages of the
world.
1.8.3 Representation of audio, image and video
In the previous sections we have discussed different data representation techniques
and standards used for the computer representation of numbers and characters. While
we attempt to solve real life problems with the aid of a digital computer, in most cases
we may have to represent and process data other than numbers and characters. This
38
1. Fundamentals of Computer
may include audio data, images and videos. We can see that like numbers and characters,
the audio, image and video data also carry information. In this section we will see
different file formats for storing sound, image and video.
Digital audio, image and video file formats
Multimedia data such as audio, image and video are stored in different types of files.
The variety of file formats is due to the fact that there are quite a few approaches to
compressing the data and a number of different ways of packaging the data. For example
an image is most popularly stored in Joint Picture Experts Group (JPEG) file format. An
image file consists of two parts - header information and image data. Information such
as name of the file, size, modified data, file format, etc are stored in the header part. The
intensity value of all pixels is stored in the data part of the file.
The data can be stored uncompressed or compressed to reduce the file size. Normally,
the image data is stored in compressed form. Let us understand what compression is.
Take a simple example of a pure black image of size 400×400 pixels. We can repeat
the information black, black,…., black in all 16,0000(400×400) pixels. This is the
uncompressed form, while in the compressed form black is stored only once and
information to repeat it 1,60,000 times is also stored. Numerous such techniques are
used to achieve compression. Depending on the application, images are stored in various
file formats such as BMP (Bitmap file format), TIFF (Tagged Image File Format), GIF
(Graphics Interchange Format), PNG - (Portable (Public) Network Graphic).
What we said about the header file information and compression is also applicable for
audio and video files. Digital audio data can be stored in different file formats like WAV,
MP3, MIDI, AIFF, etc. An audio file describes a format, sometimes referred to as the
‘container format’, for storing digital audio data. For example WAV file format typically
contains uncompressed sound and MP3 files typically contain compressed audio data.
The synthesized music data is stored in MIDI(Musical Instrument Digital Interface)
files. Similarly video is also stored in different files such as AVI ( Audio Video Interleave)
- a file format designed to store both audio and video data in a standard package that
allows synchronous audio with video simultaneous playback, MP3, JPEG-2, WMV,
etc.
Check yourself
39
Let us sum up
Data processing is a series of activities by which data is converted into information.
The limitations of manual data processing are overcome by electronic data processing
and the computer is the best electronic data processor. A computer has five functional
units such as input unit, storage unit, arithmetic logic unit, control unit and output unit.
Though the data supplied to computers is of different forms, internally these are
represented using bits. Different number systems are associated with computer and
any quantity on one system has an equivalent form in another system. Different types
of coding systems are available to represent characters in computer. Data in the
form of audio, image and video are also stored in binary form and different file
formats are used to represent them.
Learning outcomes
After the completion of this chapter the learner will be able to
• distinguish between data and information.
• identify various stages in data processing.
• list the functional units of a computer and explian the functions of each.
• explain why the computer is the best electronic data processing machine.
• infer the concept of data representation inside computers.
• convert a number from one system to another.
• list the features of various coding systems to represent characters.
Sample questions
Very short answer type
1. What is data?
2. Processed data is known as _______.
3. _________ is the place value of 9 in 29610.
4. Hexadecimal number system uses ______symbols and octal number system uses
________ symbols.
5. Find octal equivalent of the decimal number 55.
6. EBCDIC stands for _______.
7. Name the coding system that can represent almost all characters used in the hu-
man languages in the world.
8. In sign and magnitude form, if the number is negative, sign bit is ______ and if
number is positive, sign bit is ____.
40
1. Fundamentals of Computer
41
22. Convert the following hexadecimal numbers into decimal.
a. 2D16 b. 10116 c. AB16 d. 1F816 e. ABC16
23. Convert the following octal numbers into binary and hexadecimal.
a. 678 b. 1238 c. 1678 d. 7458 e. 10548
24. Convert the following hexadecimal numbers into binary and octal.
a. 7F16 b. 20716 c. AB16 d. 9F816 e. ABC16
25. If (X)2 = (Y)8 = (Z)16 = (28)10, then find X, Y and Z.
26. Arrange the following numbers in descending order
a. (101)16 b. 11010 c. 1110002 d. 2518
27. What are the methods of representing integers in computer memory?
28. Represent the following numbers in sign and magnitude method
a. -19 b. +49 c. -97 d. -127
29. Represent the following numbers in 1's complement method
a. -24 b. +69 c. -100 d. -127
30. Represent the following numbers in 2's complement method
a. -33 b. +71 c. -111 d. -127
31. Represent - 83 in all the three number representation forms.
32. Find out the decimal number which is represented as (10011001)2 in sign and
magnitude method.
33. Explain the method of representing a floating point number in a 32 bit computer.
34. What are the methods of representing characters in computer memory?
35. Write short notes on ASCII and ISCII.
36. Briefly explain the significance of Unicode in character representation.
Long answer type
1. Taking the example of a real life situation like banking, briefly describe the activi-
ties involved in each stage of data processing.
2. With the help of a block diagram, explain the functional units of a computer.
3. Write down the following numbers in expanded notation
a. (1011.101)2 b. (65356)10 c. (A5F)16 d. (67.4)8 e. (763.452)10
4. Briefly explain different methods for representing numbers in computer memory.
5. Briefly explain different methods for representing characters in computer memory.
42
2
Registers are storage locations inside CPU, whose contents can be accessed more
quickly by the CPU than other memory. They are temporary storage areas for instructions
or data. They are not a part of memory; rather they are special additional storage
locations that offer computers the advantage of speed. Registers work under the direction
of the control unit to accept, hold, and transfer instructions or data and perform arithmetic
or logical operations at high speed. It speeds up the execution of programs.
Important registers inside a CPU are:
a. Accumulator: The accumulator is a part of the Arithmetic Logic Unit (ALU).
This register is used to store data to perform arithmetic and logical operation. The
result of an operation is stored in the accumulator.
b. Memory Address Register (MAR): It stores the address of a memory loca-
tion to which data is either to be read or written by the processor.
44
2. Components of the Computer System
45
a. Serial port
A serial port / serial communication port transmits
data one bit at a time. In older computers devices
such as modem, mouse or keyboard were
Fig 2.4: Serial port
connected through serial ports (refer Figure 2.4).
Serial cables are cheaper to make and easier to shield from interference. Since its
speed is too low, they are being replaced by faster ports like PS/2, USB, etc.
b. Parallel port
Parallel ports can transmit several bits of data
simultaneously. It is faster than serial port and is
used to connect a printer or scanner to the
computer. Figure 2.5 shows a parallel port in a Fig. 2.5 : Parallel port
computer system.
c. USB port
USB (Universal Serial Bus) is a connection
that provides high speed data communication
between devices. Due to its high bandwidth
data transfer is faster. It is used for short-
distance communication. USB port is used
for connecting devices like keyboard, mouse,
printer, scanner, flash drive, external hard disk,
Fig. 2.6: USB ports
etc. Figure 2.6 shows the various types of
USB ports. The main advantage of USB ports are:
• USB ports are capable of supplying electric power to external devices. This tech-
nology led to the development of devices like external hard disk, flash drive, dongle,
etc. which draw power from the USB port. It can also be used for power devices
like mobile phones, tablets, laptops, etc.
• USB devices can be connected and disconnected even when the power is on .
d. LAN port
Alternatively referred to as an Ethernet port, network
connection, and network port, the Local Area Network
(LAN) port is a port connection that allows a computer
to connect to a network using a wired connection. The
registered jack RJ45 is a standard type of connector
Fig. 2.7 : LAN port and RJ45
used for connecting cables through LAN ports (refer
Figure 2.7). connector
46
2. Components of the Computer System
e. PS/2 port
Personal System/2 (PS/2) ports are special ports invented
by IBM (International Business Machines) for connecting
the keyboard and mouse (refer Figure 2.8). These types
of ports are too slow and replaced by faster ports like
USB nowadays.
Fig. 2.8: PS/2 port
f. Audio ports
Audio ports are used to connect audio devices like speakers,
microphone, etc. The three small connectors shown in Figure
2.9 are used for connecting:
a. Line in - Sound input (from any audio device like
mobile line out, ipod, etc.)
b. Line out - Sound out (to connect your PC's sound
output to external speakers)
c. Mic in - Microphone input port.
Fig. 2.9: Audio port
g. Video Graphics Array (VGA) port
VGA is a popular display standard developed by IBM. The VGA port is used to
connect a monitor or a projector to a computer. The VGA connector has 15 pins
displayed in three rows as indicated in Figure 2.10. Super VGA (SVGA) was developed
to support 800 × 600 resolution and was later replaced
by Extended Graphics Array (XGA) that supports 1024
by 768 resolution. Regardless of what resolution a monitor
is able to support, they are commonly referred to as VGA. Fig. 2.10 : VGA port
Memory is a place where we can store data, instructions and results temporarily or
permanently. Memory can be classified into two: primary memory and secondary
memory. Primary memory holds data, intermediate results and results of ongoing jobs
temporarily. Secondary memory on the other hand holds data and information
permanently. Before learning more about memory, let us discuss the different memory
measuring units.
47
Binary Digit = 1 Bit 1 MB (Mega Byte) = 1024 KB
1 Nibble = 4 Bits 1 GB (Giga Byte) = 1024 MB
1 Byte = 8 Bits 1 TB (Tera Byte) = 1024 GB
1 KB (Kilo Byte) = 1024 Bytes 1 PB (Peta Byte) = 1024 TB
a. Primary storage
Primary memory is a semiconductor memory that is accessed directly by the CPU. It is
capable of sending and receiving data at high speed. This includes mainly three types of
memory such as RAM, ROM and Cache memory.
i. Random Access Memory (RAM)
RAM refers to the main memory that microprocessor
can read from and write to. Data can be stored and
retrieved at random from anywhere within the RAM,
no matter where the data is. Data or instructions to be
processed by the CPU must be placed in the RAM
(refer Figure 2.12). The contents of RAM are lost
when power is switched off. Therefore, RAM is a
volatile memory. The storage capacity of RAM is Fig. 2.12 : RAM
2 GB and above
The speed of a RAM refers to how fast the data in memory is accessed. It is measured
in Mega Hertz (MHz). When a computer is in use, its RAM contains the following:
1. The operating system software.
2. The application software currently being used.
3. Any data that is being processed.
ii. Read Only Memory (ROM)
ROM is a permanent memory that can perform only read
operations and its contents cannot be easily altered. ROM
is non-volatile; the contents are retained even after the
power is switched off. ROM is used in most computers
to hold a small, special piece of 'boot up' program known
as Basic Input Output System (BIOS).This software runs
when the computer is switched on or 'boots up'. It checks
the computer's hardware and then loads the operating Fig. 2.13 : ROM chip
system. It is slower than RAM. Figure 2.13 shows a
typical ROM chip.
48
2. Components of the Computer System
RAM ROM
• It is faster than ROM • It is a slower memory
• It stores the operating system, • It stores the program required to boot
application programs and data when the the computer initially
computer is functioning. • Usually allows reading only.
• It allows reading and writing. • It is non-volatile, i.e. its contents are
• It is volatile, i.e. its contents are lost retained even when the device is
when the device is powered off. powered off.
Table 2.1 : Comparison of RAM and ROM
iii. Cache memory
Cache memory is a small and fast memory between the processor and RAM (main
memory). Frequently accessed data, instructions, intermediate results, etc. are stored
in cache memory for quick access. When the processor needs to read from or write to
a location in RAM, it first checks whether a copy of that data is in the cache. If so, the
processor immediately reads the cache, which is much faster than reading from RAM.
Cache is more expensive than RAM, but it is worth using it in order to maximise system
performance. Commonly used cache memories and their capacities are Level 1 Cache
(128 KB), Level 2 Cache (1 MB), Level 3 Cache (8 MB) and Level 4 Cache (128
MB).
b. Secondary or Auxiliary memory
Secondary memory is of permanent nature. Unlike the contents of RAM, the data
stored in these devices does not vanish when power is turned off. Secondary memory
is much larger in size than RAM, but is slower. It stores programs and data but the
processor cannot access them directly. Secondary memory is also used for transferring
data or programs from one computer to another. It also acts as a backup. The major
categories of storage devices are magnetic, optical and semiconductor memory.
49
i. Magnetic storage devices
Magnetic storage devices use plastic tape or metal/plastic disks coated with magnetic
materials. Data is recorded magnetically in these devices. Read/write heads are used to
access data from these devices. Some of the popular magnetic storage devices are
magnetic tapes, floppy disks, hard disks, etc.
Magnetic Tape
Magnetic tape is a backup device that can store huge volume of data. The cost per unit
volume of a magnetic tape is less compared to other magnetic storage devices.
It is a recording medium consisting of a thin tape with a coating of fine magnetic material.
It can be used for recording analog or digital data. Data is stored in frames across the
width of the tape with a read/write head. The frames are grouped into blocks or records
which are separated from other blocks by gaps as shown in Figure 2.14.
50
2. Components of the Computer System
51
once and read many times where in CD-RW (CD-Rewritable) disks can be erased
and rewritten at any time.
Digital Versatile Disk (DVD)
Digital Versatile Disk is an optical storage media similar to CD-ROM, but with a higher
storage capacity. This is achieved by using smaller spots to record data. Recording and
reading of data is done using DVD drive. Here also red laser beam is used for doing
these operations. The capacity of a DVD varies from 4.37 GB to 15.9 GB. There are
three major types of DVDs: DVD-ROM, DVD-RW and DVD-RAM.
DVD-ROM : DVD-Read Only Memory functions in the same way as
CD-ROM
DVD-RW : DVD-Rewritable disks can be erased and rewritten at any time.
DVD-RAM : DVD Random Access Memory disks can be recorded and erased
repeatedly. These are compatible only with devices manufactured
by companies that support the DVD-RAM format. It is compa-
rable to DVD-Rewritable disk, but have higher lifetime and can be
erased more often than a DVD-RW.
A normal DVD known as DVD-5 stores 4.37 GB data where as a dual layer double
side DVD known as DVD-18 can store 15.9 GB.
Blu-ray DVD
Blu-ray is an optical disk format developed to enable recording, rewriting and playback
of High Definition (HD) video as well as storing huge amounts of data. CD and DVD
technologies use red laser to read and write data while blu-ray format uses a blue-violet
laser. Hence it has the name Blu-ray. The benefit of using a blue-violet laser is that it has
a shorter wavelength than a red laser, which makes it possible to focus the laser spot
with greater precision. This allows data to be packed more tightly. Therefore it is possible
to store more data on the disk even though it is of the same size of a CD/DVD. The
format offers more than five times the storage capacity of traditional DVDs and can
hold up to 25 GB on a single-layer disc and 50 GB on a dual-layer disc.
iii. Semiconductor storage (Flash memory)
Flash drives use EEPROM chips for data storage. They do not contain any moving
parts and hence they are shockproof. Flash memory is faster and durable when compared
to other types of secondary memory. The different variants of flash memories are available
today.
52
2. Components of the Computer System
53
To see how registers, primary memory and second storage work together,
let us use the analogy of making a salad. In our kitchen we have:
• A refrigerator where we store vegetables for the salad.
• A counter where we place all vegetables before putting them on the cutting
board for chopping.
• A cutting board on the counter where we chop vegetables.
• A recipe that details what
vegetables to chop.
• The corners of the cutting board
are kept free for partially chopped
piles of vegetables that we intend
to chop more or to mix with other
partially chopped vegetables.
• A bowl on the counter where we
mix and store the salad.
• Space in the refrigerator to put the
mixed salad after it is made.
The process of making the salad is then: bring the vegetables from the fridge to the
counter top; place some vegetables on the chopping board according to the recipe;
chop the vegetables, possibly storing some partially chopped vegetables temporarily
on the corners of the cutting board; place all the vegetables in the bowl and keep it
back in the fridge if not served on the dinner table.
In this context the refrigerator serves as secondary (hard disk) storage. It can
store high volumes of vegetables for long periods of time. The counter top functions
like the computer's motherboard - everything is done on the counter (inside the
computer). The cutting board is the ALU - the work gets done there. The recipe is
the control unit - it tells you what to do on the cutting board (ALU). Space on the
counter top is the equivalent of RAM - all required vegetables must be brought from
the fridge and placed on the counter top for fast access. Note that the counter top
(RAM) is faster to access than the fridge (disk), but cannot hold as much, and
cannot hold it for long periods of time. The corners of the cutting board where we
temporarily store partially chopped vegetables are equivalent to the registers. The
corners of the cutting board are very fast to access for chopping, but cannot hold
much. The salad bowl is like a cache memory, it is for storing chopped vegetables to
be temporarily removed from the corners of the cutting board (as there is too much)
or the salad waiting to be taken back to the fridge (putting data back on a disk) or
to the dinner table (outputting the data to an output device).
54
2. Components of the Computer System
Check yourself
55
QWERTY design. QWERTY gets its name from the first six letters across in the upper-
left-hand corner of the keyboard as shown in Figure 2.22.
Keyboards can be classified as wired and wireless. Wired keyboards are connected to
the CPU through a serial, PS/2 port or a USB port. Wireless keyboards are connected
to the computer through infrared (IR), radio frequency (RF) or bluetooth connections.
Portable flexible keyboards are also available now. New generation keyboards like
laser keyboards that project the keyboard layout to any surface are being developed.
ii. Mouse
A mouse is a small hand-held device used to indicate the position of a cursor or its
movement on a computer display screen by rolling it over a mouse pad / flat surface. A
mouse has one or more buttons and possibly a scroll wheel. Scroll wheel is used for
scrolling the screen vertically or horizontally. The different types of mouse are ball,
optical and laser mouse. Ball mouse works on the
principle of the movement of the ball, whereas optical
mouse uses LED and laser mouses use laser beams for
sensing the movement. Laser mouse has more precise
movements when compared to other types of mouse.
Wired mouse uses serial, PS/2 and USB ports to
Fig. 2.23 : Mouse
communicate, whereas a wireless mouse communicates
with the computer via radio waves.
iii. Light pen
A light pen is a pointing device shaped like a pen. The tip of the light pen contains a
light-sensitive element which when placed against the screen, detects the light from the
56
2. Components of the Computer System
57
objects in a video game or to make menu selections by the movement of a cursor
displayed on the screen. It has a button on the top that is used to select the option
pointed by the cursor.
viii. Microphone
A microphone can be attached to a computer to input sound. It accepts sound which is
analogue in nature as input and converts it to digital format. The digitised sound can be
stored in the computer for processing or playback. A
computer loaded with speech recognition software like
the one preinstalled in Windows 7, can convert what a
person has said into text, which can be saved for word
processing. A voice recognition program can process
the input and convert it into machine-recognisable
Fig. 2.29 : Microphone
commands.
ix. Scanner
Scanners can capture information, like pictures or text, and convert it into a digital
format that can be edited using a computer. The quality of the image depends on the
resolution of the scanner. The resolution of the image scanned is expressed in Dots Per
Inch (DPI). The higher the DPI, the better the resolution.
The different variants of scanners are flat bed, sheet feed
and hand held scanner. A sheet feed scanner can scan a
single sheet, whereas flat bed can scan even from a book,
but they are not portable. A hand held scanner is portable
but the scanning action is not smooth as the scanner is moved
manually. Fig. 2.30 : Scanner
Optical Character Recognition (OCR) software is used to recognise the printed text in
an image scanned and convert it into proper text format, which can be edited by a text
editor. Advanced OCR system can read printed text in a large variety of fonts but has
difficulty with hand written text. Accurate OCR SDK, Hindi OCR software, Akshara
Malayalam OCR, etc. are examples of OCR softwares.
x. Optical Mark Reader (OMR)
OMR technology scans a printed form and reads
predefined positions, and records the marks on the
form. This technology is useful for applications in which
large number of hand-filled forms need to be
processed quickly with great accuracy, such as Fig. 2.31 : Optical Mark
objective type tests and questionnaires. Reader
58
2. Components of the Computer System
59
like fingerprints, retina, iris patterns, etc., to identify, verify and
authenticate the identity of the user. The three major types of
biometric sensors are semiconductor sensor, optical sensor and
ultrasound sensor. Figure 2.37 shows a finger print sensor.
Fig. 2.37: Biometric
xiv. Smart card reader
sensor
A smart card is a plastic card that stores and transacts
data. The data card may contain a memory or a
microprocessor. Memory cards simply store data, while a
microprocessor card, on the other hand, can add, delete
and manipulate information in its memory. The smart card
is used in most banking, healthcare, telephone calling,
electronic cash payments and other applications. Fig. 2.38: Smart card reader
Smart card readers are used to access data in a smart card. It can be contact type or
contactless. A contact type of reader requires physical contact with the cards, which is
made by inserting the card into the reader. A contactless type of reader works with a
radio frequency that communicates when the card comes close to the reader. Many
contactless readers are designed specifically for toll gate payment in transportation
applications and person identity applications.
xv. Digital camera
A digital camera can take pictures and videos and
convert them into digital format. Pictures or videos
taken using a digital camera are stored inside its
memory and can be transferred to a computer by
connecting the camera to it. Fig. 2.39 : Digital Camera
The quality of the lens, the density of Charge Couple Device (CCD), resolution (measured
in megapixel), optical zoom and the software used in the camera determines the quality
of the picture. Each picture is made up of thousands of tiny pixels (picture elements)
and the camera stores the data about the color of each dot. The quality of the picture is
determined by the number of pixels in each picture. Digital cameras have resolutions
ranging from 2 mega pixel to 24 megapixels and optical zoom ranging
from 3x to 60x.
Web camera is a compact and less expensive version of a digital
camera. It is used in computers for video calling, video chatting, etc.
It does not have an internal memory. Applications like Skype, Yahoo
Messenger, etc. use webcam to capture images. Now, laptops also
Fig. 2.40 : Web come with an inbuilt web camera.
Camera
60
2. Components of the Computer System
b. Output devices
Output devices are devices that print/display output from a computer. Outputs generated
by the output devices may be hardcopy output or softcopy output. Hardcopy outputs
are permanent outputs which can be used at a later date or when required. They produce
a permanent record on paper. The common output devices that produce hardcopy
outputs are printers and plotters. Softcopy outputs are electronic and are available on
the screen in a digital form. They do not produce a permanent record. A common
softcopy output device is the Visual Display Unit (VDU).
i. Visual Display Unit (VDU)
A Visual Display Unit (VDU) is an output device that visually conveys text, graphics
and video information. Information shown on a display device is called softcopy because
the information exists electronically and is displayed for a temporary period of time.
Display devices include Cathode Ray Tube (CRT) monitors, Liquid Crystal Display
(LCD) monitors, Thin Film Transistor (TFT) monitors, Light Emitting Diode (LED)
monitors, gas plasma monitors.
Some of the characteristics of a VDU are size, resolution, pixel-pitch and response
time. VDUs are available in different sizes. The size of a monitor is measured diagonally
across the screen, in inches. The resolution of the monitor is the maximum number of
pixels it can display horizontally and vertically (such as 800 × 600 or 1024 × 768 or
1600 × 1200). The pixel spacing on the screen is called the dot pitch. A screen with
smaller dot pitch produces sharper images. Response time refers to the time taken for
a pixel to turn from a state of brightness to a state of darkness and then back again.
Monitors, with lesser response time provide better movie viewing experience.
Cathode Ray Tube (CRT) monitor
The Cathode Ray Tube (CRT) monitor resembles television sets of the past. Two types
of CRT monitors are available, monochrome and color. A monochrome monitor displays
characters and images in a single colour on a dark
background. Another variation of monochrome monitor
capable of displaying different shades of grey is called a
grey scale monitor. A colour monitor uses three different
basic colours such as red, blue and green to display 16
to 1 million different colours. These monitors are
preferred by some graphic artists for their accurate
colour rendering and by some gamers for faster response
to rapidly changing graphics. Fig. 2.41: CRT monitor
61
Flat panel monitor
Flat panel displays are thinner, lighter in weight, consume less power and emit less heat
compared to CRT monitors. Flat panel monitors are most commonly used in computers,
especially in laptops. Different types of flat panel monitors are LCD Monitors, LED
Monitors, Plasma Monitors and OLED Monitors.
Liquid Crystal Display (LCD) Monitors: LCD displays
consists of liquid crystals sandwiched between two plastic
plates. These crystals rearrange to form an image when an
electric current is passed through them. A light source at the
back of this plate makes the picture visible. This light source
Fig. 2.42: LCD monitor can be fluorescent lamp or LED.
Light Emitting Diode (LED) Monitors: LED monitors use LED directly behind the
liquid crystal display (LCD) in order to light up the screen. This technique is very effective
and gives each area of the screen its own light, which can be on or off. LED screens can
produce massive contrast ratio making the difference between the lights and the blacks
appear almost perfect. This technology is expensive. The advantage of using LED is
better color quality, clarity, wider viewing angle, faster refresh rates and power savings.
Plasma Monitors: A flat-panel display consists of sandwiching neon/xenon gas between
two sealed glass plates with parallel electrodes deposited on their surfaces. When a
voltage pulse is passed between two electrodes, the gas lights up as different colours,
creating images on a monitor. Plasma monitors provide high resolution but are expensive.
Organic Light Emitting Diode (OLED) Monitors: The panel of OLED is made
up of millions of tiny LEDs. The O in OLED stands for organic, which means there is
carbon in the light emitting layer of the panel. OLED screens are thinner and lighter than
LCDs and LEDs. They can produce better quality images and have a better viewing
angle. OLEDs consume less power, but are very expensive.
LCD projector
An LCD projector is a type of video projector for
displaying video, images or computer data on a large
screen or other flat surface. It is a modern equivalent
of the slide projector or overhead projector. A beam
of high-intensity light travels through thousands of
shifting pixels in an LCD display. This beam of light
then passes through a lens which projects and focuses
the image on the surface. Fig. 2.43 : LCD projector
62
2. Components of the Computer System
ii. Printer
Printers are used to produce hardcopy output. Based on the technology used, they can
be classified as impact or non-impact printers. Impact printers use the typewriting or
printing mechanism where a hammer strikes the paper through a ribbon in order to
produce output. Dot-matrix printers fall under this category. Non-impact printers do
not touch the paper while printing. They use different technologies to print characters
on paper. Inkjet, Laser and Thermal printers fall under this category of printers.
Two factors that determine the quality of a printer are its resolution and speed. Resolution
is measured in terms of DPI. Speed is measured in terms of number of characters
printed in a unit of time and is represented as characters per second (cps), lines per
minute (lpm), or pages per minute (ppm).
Dot Matrix Printer (DMP)
Dot matrix printers use small electromagnetically activated
pins in the print head and an inked ribbon, to produce images
by impact. The most commonly used printer heads consists
of 9 pins. Certain printers use 24 pins for better print quality.
These printers are slow and noisy, and are not commonly
used for personal use. The Dot Matrix Printers are widely Fig. 2.44: DMP Printer
used at cash counters in shops due to their low printing cost
and for the reason that we get carbon copies from them.
Inkjet printer
Inkjet printers form the image on the page by spraying tiny
droplets of ink from the print head. The printer needs several
colours of ink (cyan, yellow, magenta and black) to make
colour images. Some photo-quality ink jet printers have more
colours of ink. Ink jet printers are inexpensive, but the cost Fig. 2.45: Inkjet Printer
of ink cartridges makes it a costly affair in the long run.
Laser printer
A laser printer produces good quality output. The image to
be printed is transferred to a drum using a laser beam. The
toner powder from the toner cartridge is then sprayed on
the drum. The toner powder sticks onto the portions traced
on the drum by the laser beam. It is transferred to a paper
by rolling the paper over the drum. Through heating the
powder is fused on to the paper. Fig. 2.46: Laser printer
63
Monochrome and colour laser printers are available. Colour laser printers use multiple
colour toner cartridges to produce colour output and are expensive. Laser printers are
faster and their speed is rated in pages per minute (ppm).
Thermal printer
Thermal printing produces a printed image by selectively heating
heat-sensitive thermal paper when it passes over the thermal
print head. The coating turns black in the areas where it is heated,
producing an image. Thermal printers print quiet and faster than
dot matrix printers. They are also smaller, lighter and consume
less power, making them ideal as portable printers. Thermal Fig. 2.47 :
printers are popular as printers at Point-of-Sale terminals. Thermal printer
Dot Matrix
Features Laser Printers Inkjet Printers Thermal Printers
Printers
Printing Ink powder Liquid ink Heat sensitive Ink soaked
material used paper ribbon
How it prints? It fuses the It sprays liquid Thermal paper is Pins are pushed
powder on the ink on paper passed over the against ribbon
through
paper through microscopic thermal print on paper.
heating. nozzles. head.
64
2. Components of the Computer System
iii. Plotter
A plotter is an output device used to produce hardcopies of graphs and designs on the
paper. A plotter is typically used to print large-format graphs or maps such as construction
maps, engineering drawings and big posters. It is used in the design of cars, ships,
aircrafts, buildings, highways etc. Plotters are of two types: Drum plotters and Flatbed
plotters.
Drum plotter
A drum plotter is also known as roller plotter. It consists
of a drum or roller on which a paper is placed and the
drum rotates back and forth to produce the graph on
the paper. It also consists of a drawing arm that holds a
set of coloured ink pens or pencils. The drawing arm
moves side to side as the paper is rolled back and forth
through the roller. In this way, a perfect graph or map is
created on the paper. Fig.2.48: Drum plotter
Flatbed plotter
A flatbed plotter is also known as table plotter. It plots on
paper that is spread and fixed over a rectangular flatbed
table. The flatbed plotter uses two drawing arms, each of
which holds a set of coloured ink pens or pencils. The
drawing arms move over the stationary paper and draw
the graph on the paper. Flatbed plotter is very slow in
Fig.2.49: Flatbed plotter
drawing or printing graphs. The large and complicated
drawing can take several hours to print.
iv. Three dimensional (3D) printer
A 3D printer is a new generation output device used to print 3D objects. It can produce
different kinds of objects in different materials, using the same printer. A 3D printer can
print anything from ceramic cups to plastic toys, metal
machine parts, stoneware vases, fancy chocolate cakes,
etc.
The 3D printing process turns the object to be printed into
thousands of horizontal tiny little layers. It then prints these
layers from the bottom to top, layer by layer. These tiny
layers stick together to form a solid object. Fig.2.50: 3D Printer
65
v. Audio output device
The audio output is the ability of the computer to produce
sound. Speakers are the output device that produces sound.
It is connected to the computer through audio ports. The
speaker produces sound by the movement of the diaphragm
in the speaker, forward and backward according to the
electrical signals coming out of the audio port. For high quality
sound reproduction computers use 2.1 (3 speakers), 5.1 (5
speakers) and 7.1 (7 speakers) speaker systems. Fig.2.51: Speakers
2.2 e-Waste
e-Waste refers to electronic products nearing the end of their "useful life". Electronic
waste may be defined as discarded computers, office electronic equipment, entertainment
devices, mobile phones, television sets and refrigerators. The used electronics which
are destined for reuse, resale, salvage, recycling or disposal are also considered as
e-Waste.
Nowadays electronics is part of modern life - desktops, laptops, cell phones, refrigerators,
TVs and a growing number of other gadgets. Every year we buy new, updated
equipments to satisfy our needs. More than 300 million computers and one billion cell
phones are produced every year. All of these electronics goods become obsolete or
unwanted, often within two or three years of purchase. This global mountain of waste is
expected to continue growing at 8% per year.
Rapid changes in technology, changes in media, falling prices and planned obsolescence
have resulted in a fast-growing surplus of electronic waste around the globe. It is estimated
that 50 million tons of e-Waste are produced each year. Only 15-20% of e-Waste is
recycled, the rest of these materials go directly into landfills and incinerators. Sale of
electronic products in countries such as India and China and across continents such as
Africa and Latin America are set to rise sharply over the next 10 years.
2.2.1 Why should we be concerned about e-Waste?
Electronic waste is not just waste. It contains some toxic substances such as mercury,
lead, cadmium, brominated flame retardants, etc. The toxic materials can cause cancer,
reproductive disorders and many other health problems, if not properly managed. It
has been estimated that e-Waste may be responsible for upto 40% of the lead found in
landfills.
66
2. Components of the Computer System
67
management options be adopted by government, industries and the public to handle the
bulk e-Waste.
Realising the growing concern over e-Waste, Central Pollution Control Board (CPCB)
of Government of India has formulated "The e-Waste (Management & Handling) Rules,
2011" and are effective from 01-05-2012. These rules shall apply to every producer,
consumer, collection centre, dismantler and recycler of e-Waste involved in the
manufacture, sale and processing of electrical and electronic equipment or components.
The implementation and monitoring of these guidelines shall be done by the State Pollution
Control Boards concerned.
Government of Kerala has introduced strict measures for safe collection and disposal
of e-Waste through a government order. The government has defined the role of
manufacturers, local bodies and the Pollution Control Board (PCB) in safe disposal of
e-Waste. Under the Extended Producer Responsibility, manufacturers of electrical and
electronic goods will be required to take back used products from consumers directly
or through agents or introduce buyback arrangement. They will also have to supply the
e-Waste to authorised recycling units. Consumers have been directed to return used
products of known brands to the manufacturers or deposit them at the collection
centresset up by local bodies.The PCB will be required to identify agencies for recycling
or disposal of e-Waste and organise awareness programmes on e-Waste disposal.
2.2.3 e-Waste disposal methods
The following disposal methods can be used for disposing e-Waste.
a. Reuse: It refers to second-hand use or usage after the equipment has been
upgraded or modified. Most of the old computers are passed on to relatives/
friends or returned to retailers for exchange or for money. Some computers are
also passed on to charitable institutions, educational institutions, etc. Inkjet
cartridges and laser toners are also used after refilling. This method reduces the
volume of e-Waste generation.
b. Incineration: It is a controlled and complete combustion process in which the
waste is burned in specially designed incinerators at a high temperature in the
range of 900 to 1000 degree Celsius.
c. Recycling of e-Waste: Recycling is the process of making or manufacturing
new products from a product that has originally served its purpose. Monitors,
keyboards, laptops, modems, telephone boards, hard drives, compact disks,
mobiles, fax machines, printers, CPUs, memory chips, connecting wires and cables
can be recycled.
d. Land filling: It is one of the most widely used, but not recommended methods
for disposal of e-Waste. In this method soil is excavated from the trenches made
and waste material is buried in it, which is covered by a thick layer of soil.
68
2. Components of the Computer System
69
• Use Liquid Crystal Display (LCD) monitors rather than Cathode Ray Tube (CRT)
monitors.
• Use hardware/software with Energy Star label.
• Dispose e-Waste according to central, state and local regulations.
• Employ alternative energy sources like solar energy.
The environmentally responsible and eco-friendly use of computers and their resources
is known as green computing.
How to make computers green?
The features that are important in making a computer greener include size, efficiency
and materials. Smaller computers are greener because they use fewer materials and
require less electricity to run. Efficient use of energy is
also an important component of a green computer.
Smaller computers such as laptops are more energy-
efficient than bigger models and LCD screens use much
less energy than the older CRT models. The use of
hazardous materials such as lead and mercury should be
minimised.
To promote green computing the following four
complementary approaches are employed:
Green design: Designing energy-efficient and eco-friendly computers, servers, printers,
projectors and other digital devices.
Green manufacturing: Minimising waste during the manufacturing of computers and
other components to reduce the environmental impact of these activities.
Green use: Minimising the electricity consumption of computers and peripheral devices
and using them in an eco-friendly manner.
Green disposal: Reconstructing used computers or appropriately disposing off or
recycling unwanted electronic equipment.
Check yourself
70
2. Components of the Computer System
2.4 Software
Software is a general term used to denote a set of programs that help us to use computer
system and other electronic devices efficiently and effectively. If hardware is said to
form the body of a computer system, software is its mind.
There are two types of software:
• System software
• Application software
2.4.1 System software
It is a set of one or more programs designed to control the operations of a computer.
They are general programs designed to assist humans in the use of computer system by
performing tasks such as controlling the operations, move data into and out of a computer
system and to do all the steps in executing application programs. In short, system
software supports the running of other software, its communication with other peripheral
devices. It helps the users to use computer in an effective manner. It implies that system
software helps to manage resources of the computer. Figure 2.53 depicts how system
software interfaces with user and hardware.
71
System software is a set of system programs which aids in the execution of a general
user's computational requirements on a computer system. The following are the
components of system software.
a. Operating system
b. Language processors
c. Utility software
a. Operating system
Operating system is a set of programs that acts as an interface between the user and
computer hardware. The primary objective of an operating system is to make the
computer system convenient to use. Operating system provides an environment for
user to execute programs. It also helps to use the computer hardware in an efficient
manner.
Operating system controls and co-ordinates the operations of a computer. It acts as the
resource manager of the computer system. Operating system is the most important
system software. It is the first program to be loaded from hard disk in the computer
and it resides in the memory till the system is shut down. It tries to prevent errors and
the improper use of computer.
Major functions of an operating system
The major functions of an Operating System are process management, memory
management, file management, security management and command interpretation.
72
2. Components of the Computer System
i. Process management
By the term process we mean a program in execution. The process management module
of an operating system takes care of the allocation and de-allocation of processes and
scheduling of various system resources to the different requesting processes.
ii. Memory management
Memory management is the functionality of an operating system which handles or
manages primary memory. It keeps track of each and every memory location to ensure
whether it is allocated to some process or free. It calculates how much memory is to be
allocated to each process and allocates it. It de-allocates memory if it is not needed
further.
iii. File management
The file management module of an operating system takes care of file related activities
such as organising, naming, storing, retrieving, sharing, protection and recovery.
iv. Device management
Device management module of an operating system performs the management of devices
attached to the computer. It handles the devices by combining both hardware and
software techniques. The OS communicates with the hardware device via the device
driver software.
Examples of various operating systems are DOS, Windows, Unix, Linux, Mac OS X,
etc.
b. Language processors
We know that natural languages are the medium of communication among human beings.
Similarly, in order to communicate with the computer, the user also needs to have a
language that should be understood by the computer. Computer languages may be
broadly classified into low level languages and high level languages.
Low-level languages are described as machine-oriented languages. In these languages,
programs are written using the memory and registers available on the computer. Since
the architecture of computer differs from one machine to another, there is separate low
level programming language for each type of computer. Machine language and assembly
language are the different low level languages.
73
Machine language: We know that a computer can understand only special signals,
which are represented by 1s and 0s. These two digits are called binary digits. The
language, which uses binary digits, is called machine language. Writing a program in
machine language is definitely very difficult. It is not possible to memorise a long string
of 0s and 1s for every instruction.
Assembly language: Assembly language is an intermediate-level programming language.
Assembly languages use mnemonics. Mnemonic is a symbolic name given to an operation.
For example ADD for addition operation, SUB for subtraction operation, etc. It is
easier to write computer programs in assembly language as compared to machine
language. It is machine dependent and programmer requires knowledge of computer
architecture.
High Level Languages (HLL): These are like English languages and are simpler to
understand than the assembly language or machine language. High level language is not
understandable to the computer. A computer program written in a high level language is
to be converted into its equivalent machine language program. So these languages require
a language translator (compilers or interpreters) for conversion. Examples of high level
programming languages are BASIC, C, C++, Java, etc.
Need for language processor
The programs consisting of instructions to the computer, written in assembly language
or high level language are not understood by the computer. We need language processors
to convert such programs into low level language, as computer can only understand
machine language. Language processors are the system programs that translate programs
written in high level language or assembly language into its equivalent machine language.
Types of language processors
l Assembler: Assembly languages require a translator known as assembler for
translating the program code written in assembly language to machine language.
Because computer can interpret only the machine code instruction, the program
can be executed only after translating. Assembler is highly machine dependent.
l Interpreter: Interpreter is another kind of language processor that converts a
HLL program into machine language line by line. If there is an error in one line, it
reports and the execution of the program is terminated. It will continue the
translation only after correcting the error. BASIC is an interpreted language.
74
2. Components of the Computer System
c. Utility software
Utility software is a set of programs which help users in system maintenance tasks and
in performing tasks of routine nature. Some of the utility programs with their functions
are listed below:
• Compression tools: Large files can be compressed so that they take less
storage area. These compressed files can be decompressed into its original form
when needed. Compression of files is known as zipping and decompression is
called unzipping. WinZip, WinRAR, etc. are examples of compression tools.
• Disk defragmenter: Disk defragmenter is a program that rearranges files on a
computer hard disk. The files are arranged in such a way that they are no longer
fragmented. This enables the computer to work faster and more efficiently.
75
• Backup software: Backup means duplicating the disk information so that in an
event of disk failure or in an event of accidental deletion, this backup may be
used. Backup utility programs facilitates the backing up of disk.
• Antivirus software: A computer virus is a program that causes abnormality in
the functioning of a computer. Antivirus software is a utility program that scans the
computer system for viruses and removes them. As new viruses are released fre-
quently, we have to make sure that latest antivirus versions are installed on the
computer. Most of the antivirus programs provide an auto-update feature which
enables the user to download profiles of new viruses so as to identify and inacti-
vate them. Norton Antivirus, Kaspersky, etc. are examples of antivirus programs.
2.4.2 Application software
Software developed for specific application is called application software. It includes
general purpose software packages and specific purpose software. GIMP, Payroll
System, Airline Reservation System, Tally, etc. are examples of application software.
a. General purpose software packages
General purpose software are used to perform operations in a particular application
area. Such software is developed keeping in mind the various requirements of its users.
They provide a vast number of features for its users. General purpose software is
classified as word processors, spreadsheet software, presentation software, database
software and multimedia software.
• Word processing software: Word Processing software is designed for creating
and modifying documents. It helps to create, edit, format and print textual matters
easily. Formatting features include different font settings, paragraph settings, bul-
lets and numbering, alignments and more. In addition to this it can check spelling
and grammar in the document, insertion of pictures, charts and tables. We can
specify headers and footers for every page in the document. The most popular
examples of this type of software are MS Word, Open Office Writer, etc.
• Spreadsheet software: Spreadsheet software allows users to perform calcula-
tions using spreadsheets. They simulate paper worksheets by displaying multiple
cells that make up a grid. It also allows us to insert drawing objects in the worksheet
and create different types of charts for graphical representation of numerical data.
Microsoft Excel, Open Office Calc, Lotus 1-2-3 and Apple Numbers are some
examples of spreadsheet software.
76
2. Components of the Computer System
77
Check yourself
78
2. Components of the Computer System
GIMP: It stands for GNU Image Manipulation Program. It is an image editing software.
It can be used for retouching photographs, creating and editing images. It supports
graphic files of different formats and allows converting from one format to another.
Mozilla Firefox: It is one of the most popular web browsers created by the Mozilla
Corporation. It provides added security features for safe browsing.
OpenOffice.org: It is a complete office suite that contains word processor (Writer) to
prepare and format documents, spreadsheets (Calc) and presentations (Impress). It
works on both Linux and Windows platforms.
2.6 Freeware and shareware
Freeware refers to copyrighted computer software which is made available for use free
of charge for an unlimited period.
The term shareware refers to commercial software that is distributed on a trial basis. It
is distributed without payment and with limited functionality. Shareware is commonly
offered in a downloadable format on the Internet. The distribution of this kind of software
aims at giving the users a chance to analyse the software before purchasing it. Some
shareware works for a limited period of time only.
Table 2.6 highlights a comparison between freeware and shareware:
Freeware Shareware
Freeware refers to software that anyone Sharewares give users a chance to try the
can download from the Internet and use software before buying it.
for free.
All the features are free. All features are not available.
To use all the features of the software, user
has to purchase it.
Freeware programs can be distributed free Shareware may or may not be distributed
of cost. freely. In many cases, author's permission
is needed to distribute the shareware.
Table 2.6 : Comparison of Freeware and Shareware
79
2.7 Proprietary software
Proprietary software is a computer program that is an exclusive property of its developer
or publisher and cannot be copied or distributed without licensing agreements. It is sold
without any access to source code and is therefore not possible to change or improve
by the user. Some examples of proprietary software are Microsoft Windows Operating
System, MS Office, Mac OS, etc.
2.8 Humanware or Liveware
Humanware or liveware refers to humans who use computer. It was used in computer
industry as early as 1966 to refer to computer users, often in humorous contexts by
analogy with software and hardware. It refers to programmers, systems analysts,
operating staff and other personnel working in a computer system (refer Table 2.7).
80
2. Components of the Computer System
Check yourself
Let us sum up
A computer system consists of hardware and software. Hardware refers to the
visible and tangible parts of computer. Processor, motherboard, peripheral and ports,
memory devices, input/output devices, etc. belong to hardware components of
computer. Memory is classified into primary and secondary memories. Primary
storage consists of RAM, ROM and cache. Seciondary storage devices are further
classified into magnetic storage, optical storage and semi conductor storage devices.
There are variety of input devices which include keyboard, mouse, light pen, touch
screen, graphic tablet, touchpad, joystick, microphone, scanner, OMR, barcode
reader, biometric sensor, smart card reader, digital camera, etc. Similarly, there are
output devices like visual display units, printers, plotters, audio output devices, etc.
The used electronics which are destined for reuse, resale, salvage, recycling or disposal
are considered as e-Waste. There are different methods for e-Waste disposal which
include re-use, incineration, recycling, land filling, etc. Green computing is the study
and practice of environmentally sustainable computing or IT.
Software refers to the intangible or invisible part of the computer which is a set of
programs that help us to use computer system and other electronic devices efficiently
and effectively. Software is classified into system software and application software.
System software include operating system, language processors and utility software.
Application software is further divided into general purpose software and specific
purpose software. Free and open source software are available which give freedom
to use, copy, distribute, examine, change and improve the software. The term freeware
refers to software that can be downloaded from the Internet and use for free.
Shareware give users a chance to try the software before buying it. There is one
more component associated with computer, the humanware. It refers to humans
who use computer at various level.
81
Learning outcomes
After the completion of this chapter the learner will be able to
• explain the basic organisation of computer system.
• list the use of different types of input and output devices.
• distinguish between system software and application software.
• identify the importance of e-Waste disposal.
• identify the importance of green computing concept.
• classify the different types of software.
• list the functions of operating system.
• use word processor, electronic spreadsheets and presentation software.
• classify the different types of computer languages.
• list the use of different types of utility software.
• promote open source software.
• explain the term humanware or liveware.
Sample questions
Very short answer type
1. What are the components of a digital computer?
2. Write the main functions of central processing unit.
3. What are the different types of main memory?
4. What is the advantage of EEPROM over EPROM?
5. When do we use ROM?
6. What is an input device? List few commonly used input devices.
7. What do you mean by an output device? List few commonly used output devices.
8. What is a storage device? List few commonly used storage devices.
9. What is the role of ALU?
10. What is a control unit?
82
2. Components of the Computer System
11. What are registers? Write and explain any two of them.
12. Differentiate Hard copy and Soft copy.
13. What is e-Waste?
14. What is operating system?
15. What is a language processor?
16. Mention the categories of computer languages.
17. What is disk defragmenter?
18. What is proprietary software?
19. What do you mean by open source software?
Short answer type
1. Briefly explain any three input devices.
2. Compare CRT with LED monitor.
3. Differentiate RAM and ROM.
4. List and explain e-Waste disposal methods.
5. Enumerate the steps that can be taken for the implementation of green computing
philosophy.
6. What do you mean by customized software? Give examples.
7. Distinguish between low level and high level languages.
8. Differentiate compiler and interpreter.
9. Describe the use of electronic spreadsheets.
10. What is utility software? Give two examples.
11. Categorise the software given below into operating system, application packages
and utility programs.
Linux, Tally, WinZip, MS-Word, Windows, MS-Excel
12. Differentiate between freeware and shareware.
13. What are the four freedoms which make up free and open source software?
14. What do you mean by humanware? Give any two examples.
83
Long answer type
1. Describe in detail the various units of the Central Processing Unit.
2. Briefly explain various types of memory.
3. Explain the classification of printers.
4. "e-Waste is hazardous to our health and environment." Justify the statement. List
and explain the methods commonly used for e-Waste disposal.
5. Define the term green computing. List and explain the approaches that you can
adopt to promote green computing concepts at all possible levels.
6. List and explain various categories of software.
7. Describe the use of various utility softwares.
8. Define the term 'operating system'. List and explain the major functions of operat-
ing system.
9. List and explain general purpose application software with examples.
84
3. Principles of Programming and Problem Solving
3
1
85
statement. It tells the computer what operation it should perform. A computer can execute
(carry out the task contained in) an instruction only if the task is specified precisely and
accurately. As we learnt in the previous chapter, there are programmers who develop
computer programs for solving problems. Once the program is developed and stored
permanently in a computer, we can ask the computer to execute it as and when required.
We should be cautious about the clarity of the logic of the solution and the format of
instructions while designing a program, because computer does not possess common
sense or intuition. As human beings we use judgments based on experience, often on
subjective and emotional considerations. Such value oriented judgments often depend
on what is called "common sense". As opposed to this, a computer exhibits no emotion
and has no common sense. That is why we say that computer has no intelligence of its
own.
In a way, computer may be viewed as an 'obedient servant'. Being obedient without
exercising 'common sense' can be very annoying and unproductive. Take the instance
of a master who sent his obedient servant to a post office with the instruction "Go to the
post office and buy ten 5 rupees stamps". The servant goes to the post office with the
money and does not return even after a long time. The master gets worried and goes in
search of him to the post office and found the servant standing there with the stamps in
his hand. When the angry master asks the servant for an explanation, the servant replies
that he was ordered to buy ten 5 rupees stamps but not to return with them!
3.2 Approaches in problem solving
A problem may be solved in different ways. Even the approach may be different. In our
life, we may seek medical treatment for some diseases. We can consult an allopathic,
ayurvedic or homoepathic doctor. Each of their approaches may be different, though all
of them are solving the same problem. Similarly in problem solving also different
approaches are followed. Let us discuss the two popular designing styles of problem
solving – Top down design and Bottom up design.
3.2.1 Top down design
Look at Figure 3.1. If you are asked to draw this picture,
how will you proceed? It may be as follows:
1. Draw the outline of the house.
2. Draw the chimney
3. Draw the door
Fig. 3.1 : Lay-out of a House
4. Draw the windows
86
3. Principles of Programming and Problem Solving
While drawing the door in Step 3, Similarly the windows may be drawn
the procedure may be as follows: as follows:
3.1 Outline of the door 4.1 Outline of the window
3.2 Shading 4.2 Shading
3.3 Handle 4.3 Horizontal and Vertical lines
The procedure described above may be summarised as follows:
The whole problem (here drawing the picture) is broken down into smaller tasks. Thus
four tasks are identified to solve the problem. Some of these tasks (here steps 3 and 4
for drawing the door and windows) are further subdivided. Thus any complex problem
can be solved by breaking it down into different tasks and solving each task by performing
simpler activities. This concept is known as top down design in problem solving.
87
3.2.2 Bottom up design
Consider the case of constructing a house. We do not follow the top down design, but
the bottom up design. The foundation will be the first task and roofing will be the last
task. Breaking down of tasks is carried out here too. It is true that some tasks can be
carried out only after the completion of some other tasks. However roofing which is the
main task will be carried out only after the completion of bottom level tasks.
Similarly in programming, once the overall procedure or task is broken down into
component parts (modules) and each component module is further sub divided until the
lowest level of detail has been reached, we start solving from the lowest module onwards.
The solution for the main module will be developed only after designing specific solutions
to its sub modules. This style of approach is known as bottom up design for problem
solving. Here again, it is desirable that the sub problems (subprograms) should be
independent of each other.
88
3. Principles of Programming and Problem Solving
89
Method
Step 1 : Break the eggs and pour the contents in a vessel
and stir.
Step 2 : Mix chopped onion, green chilies and salt with the
stirred egg.
Step 3 : Place a pan on the stove and light the stove.
Step 4 : Pour the oil in the pan and wait till it gets heated.
Step 5 : Pour the mixture prepared in step 2 into the pan
and wait till the side is fried.
Step 6 : Turn over to get the other side fried well.
Step 7 : Take it out after some seconds.
Result
An omlette is ready to be served with pepper powder.
The recipe given above has the following properties:
1. It begins with a list of ingredients required for making the omlette. These may be
called the inputs.
2. A sequence of instructions is given to process the inputs.
3. As a result of carrying out the instructions, some outputs (here, omlette) are ob-
tained.
The instructions given to process the inputs are, however, not precise. They are
ambiguous. For example, the interpretation of "till the side is fried" in step 5 and "fried
well" in step 6 can vary from person to person. Due to such imprecise instructions,
different persons following the same recipe with the same inputs can produce omlettes
which differ in size, shape and taste.
The above ambiguities should be avoided while writing
steps to solve the problems using the computer.
a. Algorithm
Mathematicians trace the origin of the word algorithm
to the name of a famous Arab mathematician, Abu Jafar
Mohammed Ibn Musaa Al-Khowarizmi. The word
'algorithm' is derived from the last part of his name Al-
Khowarizmi. In computer terminology an algorithm may
be defined as a finite sequence of instructions to solve a Fig.3.4 : Abu Jafar
Mohammed Ibn Musaa Al-
problem. It is a step-by-step procedure to solve a Khowarizmi (780 - 850)
90
3. Principles of Programming and Problem Solving
problem, where each step represents a specific task to be carried out. However, in
order to qualify as an algorithm, a sequence of instructions must possess the following
characteristics:
(i) It should begin with instruction(s) to accept inputs. These inputs are processed by
subsequent instructions. Sometimes, the data to be processed will be given along
with the problem. In such situations, there will be no input instruction at the begin-
ning of the algorithm.
(ii) Use variables to refer the data, where variables are user-defined words consisting
of alphabets and numerals that are similar to those used in mathematics. Variables
must be used for inputting data and assigning values or results.
(iii) Each and every instruction should be precise and unambiguous. In other words,
the instructions must not be vague. It must also be possible to carry them out. For
example, the instruction "Catch the day" is precise, but cannot be carried out.
(iv) Each instruction must be sufficiently basic such that it can, in principle, be carried
out in finite time by a person with paper and pencil.
(v) The total time to carry out all the steps in the algorithm must be finite. As algorithm
may contain instructions to repetitively carry out a group of instructions, this re-
quirement implies that the number of repetitions must be finite.
(vi) After performing the instructions given in the algorithm, the desired results (out-
puts) must be obtained.
To gain insight into algorithms, let us consider a simple example. We have to find the
sum and average of any three given numbers. Let us write the procedure for solving this
problem. It is given below:
Step 1: Input three numbers.
Step 2: Add these numbers to get the sum
Step 3: Divide the sum by 3 to get the average
Step 4: Print sum and average
Though the procedure is correct, while preparing an algorithm, we have to follow any
of the standard formats. Let us see how the procedure listed above can be written in an
algorithm style.
Example 3.1: Algorithm to find the sum and average of three numbers
Let A, B, C be variables for the input numbers; and S, Avg be variables for sum and
average.
91
Step 1: Start
Step 2: Input A, B, C
Step 3: S=A+B+C
Step 4: Avg = S / 3
Step 6: Stop
The above set of instructions qualifies as an algorithm for the following reasons:
• It has input (The variables A, B and C are used to hold the input data).
• The processing steps are precisely specified (Using proper operators in Steps 3
and 4) and can be carried out by a person using pen and paper.
• Each instruction is basic (Input, Print, Add, Divide) and meaningful.
• It produces two outputs such as sum (S) and average (Avg).
• The beginning and termination points are specified using Start and Stop.
Types of instructions
As we know, a computer can perform only limited types of operations. So we can use
only that many instructions to solve problems. Before developing more algorithms, let
us identify the types of instructions constituting the algorithm.
• Computer can accept data that we input. So, we can use input instructions. The
words Input, Accept or Read may be used for this purpose.
• Computer gives the results as output. So we can use output instructions. The
words Print, Display or Write may be used for this purpose.
• Data can directly be stored in a memory location or data may be copied from one
location to another. Similarly, results of arithmetic operations on data can also be
stored in memory locations. We use assignment (or storing) instruction for this,
similar to that used in mathematics. Variables followed by the equal symbol ( = )
can be used for storing value, where variables refer to memory locations.
• A computer can compare data values (known as logical operation) and make
decisions based on the result. Usually, the decision will be in the form of selecting
or skipping a set of one or more statements or executing a set of instructions
repeatedly.
92
3. Principles of Programming and Problem Solving
b. Flowcharts
An idea expressed in picture or diagram is preferred to text form by people. In certain
situations, algorithm may be difficult to follow, as it may contain complex tasks and
repetitions of steps. Hence, it will be better if it could be expressed in pictorial form.
The pictorial representation of an algorithm with specific symbols for instructions and
arrows showing the sequence of operations is known as flowchart. It is primarily used
as an aid in formulating and understanding algorithms. Flowcharts commonly use some
basic geometric shapes to denote different types of instructions. The actual instructions
are written within these boxes using clear and concise statements. These boxes are
connected by solid lines with arrow marks to indicate the flow of operation; that is, the
exact sequence in which the instructions are to be executed.
Normally, an algorithm is converted into a flowchart and then the instructions are
expressed in some programming language. The main advantage of this two-step approach
in program writing is that while drawing a flowchart one is not concerned with the
details of the elements of programming language. Hence he/she can fully concentrate
on the logic (step-by-step method) of the procedure. Moreover, since a flowchart
shows the flow of operations in pictorial form, any error in the logic of the procedure
can be detected more easily than in a program. The algorithm and flow chart are always
a reference to the programmer. Once these are ready and found correct as far as the
logic of the solution is concerned, the programmer can concentrate on coding the
operations following the constructs of programming language. This will normally ensure
an error-free program.
Flowchart symbols
The communication of program logic through flowcharts is made easier through the use
of symbols that have standardised meanings. We will only discuss a few symbols that
are needed to indicate the necessary operations. These symbols are standardized by
the American National Standards Institute (ANSI).
1. Terminal
As the name implies, it is used to indicate the beginning (START) and
ending (STOP) in the program logic flow. It is the first symbol and
the last symbol in the flowchart.
It has the shape of an ellipse. When it is used as START, an exit flow
will be attached. But when it is used as a STOP symbol, an entry
flow will be attached.
93
2. Input / Output
The parallelogram is used as the input/output symbol. It denotes the
function of an input/output device in the program. All the input/output
instructions are expressed using this symbol. It will be attached with
one entry flow and one exit flow.
3. Process
A rectangle is used to represent the processing step. Arithmetic
operations such as addition, subtraction, multiplication, division as
well as assigning a value to a variable are expressed using this symbol.
Assigning a value to a variable means moving data from one memory
location to another (e.g. a=b) or moving the result from ALU to memory
location (e.g. a=b+5) or even storing a value to a memory location
(e.g. a=2). Process symbol also has one entry flow and one exit flow.
4. Decision
The rhombus is used as decision symbol and is used to indicate a
point at which a decision has to be made. A branch to one of two or
more alternative points is possible here. All the possible exit paths will
be specified, but only one of these will be selected based on the result
of the decision. Usually this symbol has one entry flow and two exit
flows - one towards the action based on the truth of the condition and
the other towards the alternative action.
5. Flow lines
Flow lines with arrow heads are used to indicate the flow of operation,
that is, the exact sequence in which the instructions are to be executed.
The normal flow is from top to bottom and left to right. But in some
cases, it can be from right to left and bottom to top. Good practice
also suggests that flow lines should not cross each other and such
intersections should be avoided wherever possible.
6. Connector
When a flowchart becomes bigger, the flow lines start criss-
crossing at many places causing confusion and reducing
comprehension of the flowchart. Moreover, when the
flowchart becomes too long to fit into a single page the use
of flow lines becomes impossible. Whenever a flowchart
94
3. Principles of Programming and Problem Solving
• Effective analysis: The whole program can be analysed effectively through the
flowchart as it clearly specifies the flow of the steps constituting the program.
• Effective synthesis: If a problem is divided into different modules and the solu-
tion for each module is represented in flowcharts separately, they can finally be
placed together to visualize the overall system design.
95
Limitations of flowcharts
In spite of their many obvious advantages, flowcharts have some limitations:
• Flowcharts are very time consuming and laborious to draw with proper symbols
and spacing, especially for large complex algorithms.
• Owing to the symbol-string nature of flowcharting, any change or modification in
the logic of the algorithm usually requires a completely new flowchart.
• There are no standards determining the amount of detail that should be included in
a flowchart.
Now let us develop algorithms and draw flowcharts for solving various problems.
96
3. Principles of Programming and Problem Solving
Example 3.3: Find the height of the taller one among two students
Here, two numbers representing the height of two students are to be input. The larger
number is to be identified as the result. We know that a comparison between these
numbers is to be made for this. The algorithm is given below:
Step 1: Start
Step 2: Input H1, H2
Step 3: If H1 > H2 Then
Step 4: Print H1
Step 5: Else
Step 6: Print H2
Step 7: End of If
Step 8: Stop
97
The working of selection construct is as shown
in Figure 3.10. The flow of control comes to
the condition; it will be evaluated to True or Yes
Condition True Block
False. If the condition is True, the instructions
given in the true block will be executed and
No
false block will be skipped. But if the condition
False Block
is False, the true block will be skipped and the
false block will be executed. Now let us solve Fig. 3.10 : Flowchart of selection
another problem.
Example 3.4: To input the scores obtained in 3 unit-tests and find the
highest score
Here we have to input three numbers representing the scores and find the largest number
among them. The algorithm is given below and flowchart is shown in Figure 3.11.
Step 1: Start
Step 2: Input M1, M2, M3
Step 3: If M1>M2 And M1>M3 Then
Step 4: Print M1
Step 5: Else If M2 > M3 Then
Step 6: Print M2
Step 7: Else
Step 8: Print M3
Step 9: End of If
Step 10: Stop
98
3. Principles of Programming and Problem Solving
99
Step 3: Repeat Steps 4 and 5 While (N<=100)
Step 4: Print N
Step 5: N=N+1
Step 6: Stop
100
3. Principles of Programming and Problem Solving
becomes false. The loop that checks the condition before executing the body is called
entry-controlled loop. There is another style of looping construct. In this case, the
condition will be checked only after the execution of loop-body and update instruction.
Such a loop is called exit-controlled loop.
Example 3.6: To print the sum of the first N
natural numbers
Here we have to input the value of N. The sum of
numbers from 1 to the input number N is to be found
out. Let S be the variable to store the sum. Figure
3.16 shows the flowchart of this algorithm
Step 1: Start
Step 2: Input N
Step 3: A = 1, S = 0
Step 4: Repeat Steps 5 and 6 While (A <= N)
Step 5: S=S+A
Step 6: A=A+1
Step 7: Print S
Fig. 3.16 :
Step 8: Stop Flowchart for
the sum of first N
This algorithm uses an entry-controlled loop. In the natural numbers
next example we can see an algorithm that uses exit-
controlled loop for problem solving.
101
Entry controlled loop Exit controlled loop
• Condition is checked before the • Condition is checked after the
execution of the body execution of the body
• Body may never be executed. • Body will surely be executed at least
once.
• Suitable when skipping of the body from • Suitable when normal execution of
being executed is required the body is to be ensured.
Table 3.1 : Comparison of loops
Let us practice with more algorithms and flowcharts for solving the problems that are
given as learning activities.
Develop an algorithm and draw the flowcharts for the following
problems:
1. To print all even numbers below 100 in the descending order.
Let us do 2. To find the sum of odd numbers between 100 and 200.
3. To print the multiplication table of a given number.
4. To find the factorial of a number.
5. To input a number and check whether it is prime or not.
102
3. Principles of Programming and Problem Solving
written in HLL into machine language. The program written in any HLL is known as
source code.
Hence, to be a programmer we have to be well-versed in any HLL such as BASIC,
COBOL, Pascal, C++ etc. to express the instructions in a program. Each language has
its own character set, vocabulary, grammar (we call it syntax) to write programs. Once
the program is written using a language, it should be saved in a file (called source file),
and then proceed to the next phase of programming.
3.3.4 Translation
While selecting a language for developing source code, certain criteria such as volume
of data, complexity in process, usage of files, etc. are to be considered. Once a language
is selected and the source code is prepared, it should be translated using the concerned
language processor. Translation is the process of converting a program written in high
level language into its equivalent version in machine language. The compiler or interpreter
is used for this purpose. During this step, the syntax errors of the program will be
displayed. These errors are to be corrected by opening the file that contains the source
code. The source code is again given for compilation (translation). This process will be
continued till we get a message such as "No errors or warnings" or "Successful
compilation". Now we have a program fully constituted by machine language instructions.
This version of the source code is known as object code and it will be usually stored in
a file by the compiler itself.
103
line number of the statement having errors and give hints about the nature of the error.
In the case of interpreters, the syntax errors will be detected and displayed during
execution. The programmer's efficiency in using the language decides the time and effort
for the debugging process. The object program will be generated only if all the syntax
errors are rectified.
The second type of error, named logical error, is due to improper planning of the
program's logic. The language processor successfully translates the source code into
machine code if there are no syntax errors. During the execution of the program, computer
actually follows the program instructions and gives the output as per the instructions.
But the output may not be correct. This is known as logical error. When a logical error
occurs, all you know is that the computer is not giving the correct output. The computers
do not tell us what is wrong. It should be identified by the programmer or user. In order
to determine whether or not there is a logical error, the program must be tested. So, let
us move on to the next stage of programming.
3.3.6 Execution and testing
As we have seen in the previous section, the program is said to be error-free only when
logical errors are also rectified. Hence when the compiled version of the program is
formed, it should be executed for testing. The purpose of testing is to determine whether
the results are correct. The testing procedure involves running the program to process
the test data that will produce 'known results'. That is, the
operations involved in the program should be done manually
and the output thus obtained should be compared with the
one given by the computer. The accuracy of the program
logic can be determined by this testing. While selecting the
test data, we should ensure that all aspects of the program
logic will be tested. Hence the selection of proper test
data is important in program testing.
Till now, we have discussed incorrect outputs due to incorrect logic. But there is a
chance of another type of error, which will interrupt the program execution. This may
be due to the inappropriate data that is encountered in an operation. For example
consider an instruction A= B/C. This statement causes interruption in execution if the
value of C happens to be zero. In such a situation, the error messages may be displayed
by the error-handling function of the language. These errors are known as Run-time
error. These errors can be rectified by providing instructions for checking the validity
of the data before it gets processed by the subsequent instructions in the program.
104
3. Principles of Programming and Problem Solving
3.3.7 Documentation
A computerised system cannot be considered to be complete until it is properly
documented. In fact documentation is an on-going process that starts in the problem-
study phase of the system and continues till its implementation and operation. We can
write comments in the source code as part of documentation. It is known as internal
documentation. It helps the debugging process as well as program modification at a
later stage. The logic that we applied in the program may not be remembered when we
go through our own program at a later stage. Besides, the program written by one
person may need to be modified by some other person in future. If the program is
documented, it will help to understand the logic we applied, the reason why a particular
statement has been used and so on. However, the documentation part of the program
will not be considered by the language processor when you give the program for
translation.
Writing comments in programs is only a part of documentation. Another version of
documentation is the preparation of system manual and user manual. These are hard
copy documents that contain functioning of the system, its requirements etc. and the
procedure for installing and using the programs. While developing software for various
applications, these manuals are mandatory. This kind of documentation is known as
external documentation.
Now you have analysed the problem, derived the logic of the solution, expressed in a
flow chart, developed the code in a programming language, translated it after removing
the syntax errors, checked the accuracy of the output after removing all the possible
logical and run-time errors, and we have documented the program.
Check yourself
1. What is an algorithm?
2. Pictorial representation of algorithm is known as ______.
3. Which flow chart symbol is always used in pair?
4. Which flow chart symbol has one entry flow and two exit flows?
5. Program written in HLL is known as ________.
6. What is debugging?
7. What is an object code?
105
3.4 Performance evaluation of algorithms
We have developed algorithms for solving various problems. You may think that some
of these problems would have been solved by following a different logic. Of course, it is
true that the same problem can be solved by different sets of instructions. But an efficient
programmer is the one who develops algorithms that require minimum computer resources
for execution and give results with high accuracy in lesser time. The performance of an
algorithm is evaluated based on the concept of time and space complexity. The algorithm
which will be executed faster with minimum amount of memory space is considered as
the best algorithm for the problem.
Algorithm-1 Algorithm-2
106
3. Principles of Programming and Problem Solving
The algorithm in Example 3.4 has three comparison operations and one logical operation
altogether. All these operations are to be carried out only when the largest value is in
M3 (the third variable). To identify the speed of execution in each case, let us assume
that 1 second is required for one comparison operation. We can see that fastest result
will be in 3 seconds and slowest in 4 seconds. So the average speed is 3.5 seconds.
Now let us analyse Algorithm-1 in Table 3.3. There are three If statements, each with
three comparison operations. If we follow the assumptions specified above, we can
see that the result will be obtained in 9 seconds, irrespective of the values in the variables.
So the average speed is 9 seconds. But the Algorithm-2 in Table 3.3 uses two If
structures. The algorithm shows that whatever be the values in the variables, the time
required for comparison will be 2 seconds. Thus the average speed is 2 seconds. So,
we can say that the Algorithm-2 is better than the other two.
Let us consider one more case where loop is involved. The two algorithms given in
Table 3.4 find the sum of all even numbers and sum of all odd numbers between 100
and 200.
Algorithm-1 Algorithm-2
Step 1: Start Step 1: Start
Step 2: N = 100, ES = 0 Step 2: N = 100, ES = 0, OS = 0
Step 3: Repeat Steps 4 to 6 Step 3: Repeat Steps 4 to 8
While (N <= 200) While (N <= 200)
Step 4: If Remainder of N/2 = 0 Then Step 4: If Remainder of N/2 = 0 Then
Step 5: ES = ES + N Step 5: ES = ES + N
Step 6: N=N+1 Step 6: Else
Step 7: Print ES Step 7: OS = OS + N
Step 8: N = 100, OS = 0 Step 8: N = N + 1
Step 9: Repeat Steps 10 to 12 Step 9: Print ES
While (N <= 200) Step 10: Print OS
Step 10: If Remainder of N/2 = 1 Then Step 11: Stop
Step 11: OS = OS + N
Step 12: N=N+1
Step 13: Print OS
Step 14: Stop
107
Let us sum up
Program is a sequence of instructions written in a computer language. The process
of programming proceeds through some stages. Preparation of algorithms and
flowcharts help develop the logic. The program written in HLL is known as source
code and it is to be converted into machine language. The resultant code is known
as object code. The errors occurred in a program has to be removed through a
process known as debugging. The translated version is executed by the computer.
Proper documentation of the program helps us to modify it at a later stage. While
solving problems different logics may be applied, but the performance is measured
in terms of time and space complexity.
Learning outcomes
Sample questions
Very short answer type
1. What is an algorithm?
2. What is the role of a computer in problem solving?
3. What is the use of connector in a flow chart?
4. What do you mean by logical errors in a program?
Short answer type
1. What is a computer program? How do algorithms help to write programs?
2. Write an algorithm to find the sum and average of 3 numbers.
3. Draw a flowchart to display the first 100 natural numbers.
4. What are the limitations of a flow chart?
5. What is debugging?
6. What is the need of documentation for a program?
Long answer type
1. What are the characteristics of an algorithm?
2. What are the advantages of using a flowchart?
3. Briefly explain different phases in programming.
108
4. Getting Started with C ++
4
1
109
Dr. Bjarne Stroustrup developed C++ at AT&T Bell
Laboratories in Murray Hill, New Jersey, USA. Now
he is a visiting Professor at Columbia University and
holder of the College of Engineering Chair in Computer
Science at Texas A&M University. He has received numerous
honors. Initial name of this language was 'C with classes'. Later it Bjarne
was renamed to C++, in 1983. Stroustrup
set. It is a set of valid symbols, called characters that a language can recognize. A
character represents any letter, digit, or any other symbol. The set of valid characters in
a language which is the fundamental units of that language, is collectively known as
character set. The character set of C++ is categorized as follows:
(i) Letters : ABCDEFGHIJKLMNOPQRSTU
VWXYZ
abcdefghijklmnopqrstuvwxyz
(ii) Digits : 0123456789
(iii) Special characters : + - */ ^ \ ( ) [ ] { } = < > . ’ “
$ , ; : % ! & ? _ (underscore) # @
(iv) White spaces : Space bar (Blank space), Horizontal Tab (à),
Carriage Return (↵ ) , Newline, Form feed
(v) Other characters : C++ can process any of the 256 ASCII
characters as data or as literals.
Spaces, tabs and newlines (line breaks) are called white spaces. White
space is required to separate adjacent words and numbers.
4.2 Tokens
After learning the alphabet the second stage is learning words constituted by the alphabet
(or characters). The term ‘token’ in the C++ language is similar to the term ‘word’ in
natural languages. Tokens are the fundamental building blocks of the program. They
are also known as lexical units. C++ has five types of tokens as listed below:
1. Keywords
2. Identifiers
3. Literals
4. Punctuators
5. Operators
110
4. Getting Started with C ++
4.2.1 Keywords
The words (tokens) that convey a specific meaning to the language compiler are called
keywords. These are also known as reserved words as they are reserved by the
language for special purposes and cannot be redefined for any other purposes. The set
of 48 keywords in C++ are listed in Table 4.1. Their meaning will be explained in due
course.
asm continue float new signed try
auto default for operator sizeof typedef
break delete friend private static union
case do goto protected struct unsigned
catch double if public switch virtual
char else inline register template void
class enum int return this volatile
const extern long short throw while
Table 4.1 : Keywords of C++
4.2.2 Identifiers
We usually assign names to places, people, objects, etc. in our day to day life, to
identify them from one another. In C++ we use identifiers for this purpose. Identifiers
are the user-defined words that are used to name different program elements such as
memory locations, statements, functions, objects, classes etc. The identifiers of memory
locations are called variables. The identifiers assigned to statements are called labels.
The identifiers used to refer a set of statements are called function names.
While constructing identifiers certain rules are to be strictly followed for their validity in
the program. The rules are as follows:
• Identifier is an arbitrary long sequence of letters, digits and underscores ( _ ).
• The first character must be a letter or underscore ( _ ).
• White space and special characters are not allowed.
• Keywords cannot be used as identifiers.
• Upper and lower case letters are treated differently, i.e. C++ is case sensitive.
Examples for some valid identifiers are Count, Sumof2numbers, _1stRank,
Main, Average_Height, FOR
111
The following are some invalid identifiers due to the specified reasons:
Sum of Digits → Blank space is used
1styear → Digit is used as the first character
First.Jan → Special character ( . ) is used
for → It is a keyword
Identify invalid identifiers from the following list and give reasons:
Data_rec, _data, Idata, datal, my.file,
Let us do asm, switch, goto, break
4.2.3 Literals
Consider the case of the Single Window System for the admission of Plus One students.
You may have given your date of birth in the application form. As an applicant, your
date of birth remains the same throughout your life. Once they are assigned their initial
values, they never change their value. In mathematics, we know that the value of π is a
constant and the value of gravitational constant ‘g’ never changes, i.e. it remains 9.8m/
s2. Like that, in C++, we use the type of tokens called literals to represent data items
that never change their value during the program run. They are often referred to as
constants. Literals can be divided into four types as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
Integer literals
Consider the numbers 1776, 707, -273. They are integer constants that identify integer
decimal values. The tokens constituted only by digits are called integer literals and
they are whole numbers without fractional part. The following are the characteristics of
integer literals:
• An integer constant must have at least one digit and must not contain any decimal
point.
• It may contain either + or – sign as the first character, which indicates whether the
number is positive or negative.
112
4. Getting Started with C ++
In addition to decimal numbers (base 10), C++ allows the use of octal
numbers (base 8) and hexadecimal numbers (base 16) as literals
(constants). To express an octal number we have to precede it with a
0 (zero character) and in order to express a hexadecimal number we
have to precede it with the characters 0x (zero, x). For example, the integer constants
75, 0113 and 0x4B are all equivalent to each other. All of these represent the same
number 75 (seventy-five), expressed as a base-10 numeral, octal numeral and
hexadecimal numeral, respectively.
113
A real constant in exponential form consists of two parts: mantissa and exponent. For
instance, 5.8 can be written as 0.58×101 = 0.58E1 where mantissa part is 0.58 (the
part appearing before E) and exponential part is 1 (the part appearing after E). The
number E1 represents 101. The rules for writing a real constant in exponential form are
given below:
• A real constant in exponent form has two parts: a mantissa and an exponent.
• The mantissa must be either an integer or a valid fractional form.
• The mantissa is followed by a letter E or e and the exponent.
• The exponent must be an integer.
The following are valid real constants.
52.0 107.5 -713.8 -.00925
453.E-5 1.25E08 .212E04 562.0E09
152E+8 1520E04 -0.573E-7 -.097
Some invalid real constants are given along with the reason:
58,250.262 (Comma is used), 5.8E (No exponent part), 0.58E2.3 (Fractional number
is used as exponent).
Classify the following into valid and invalid real constants and
justify your answer:
77, 00,000 7.0 3.14 -5.0E5.4 +53.45E-6
+532.67. .756E-3 -0.528E10 1234.56789 34,56.24
Let us do 4353 +34/2 5.6E 4356 0
Character literals
When we want to store the letter code for gender usually we use ’f’ or ‘F’ for Female
and ‘m’ or ‘M’ for Male. Similarly, we may use the letter ‘y’ or ‘Y’ to indicate Yes and
the letter ‘n’ or ‘N’ to indicate No. These are single characters. When we refer a single
character enclosed in single quotes that never changes its value during the program run,
we call it a character literal or character constant.
Note that x without single quote is an identifier whereas ‘x’ is a character constant. The
value of a single character constant is the ASCII value of the character. For instance,
the value of ‘c’ will be 99 which is the ASCII value of ‘c’and the value of ‘A’ will be the
ASCII value 65.
114
4. Getting Started with C ++
C++ represents Octal Number and Hexadecimal Number with the help
of escape sequences. The \0n and \xHn represent a number in the
Octal Number System and the Hexadecimal Number System
respectively.
Some invalid character constants are also given with the reason for invalidity:
A (No single quotes), ‘82’ (More than one character), “K” (Double quotes instead of
single quotes), ‘\g’ (Invalid escape sequence or Multiple characters).
String literals
Nandana is a student and she lives in Bapuji Nagar. Here, “Nandana” is the name of a
girl and “Bapuji Nagar” is the name of a place. These kinds of data may need to be
processed with the help of programs. Such data are considered as string constants and
they are enclosed within double quotes. A sequence of one or more characters enclosed
115
within a pair of double quotes is called string constant. For instance, "Hello
friends", "123", "C++", "Baby\'s Day Out", etc. are valid string constants.
4.2.4 Punctuators
In languages like English, Malayalam, etc. punctuation marks are used for grammatical
perfection of sentences. Consider the statement: Who developed C++? Here ‘?’ is
the punctuation mark that tells that the statement is a question. Similarly at the end of
each sentence we put a full stop (.). In the same way C++ also has some special
symbols that have syntactic or semantic meaning to the compiler. These are called
punctuators. Examples are: # ; ‘ “ ( ) [ ] { }
The purpose of each punctuator will be discussed in due course.
4.2.5 Operators
When we have to add 5 and 3, we express it as 5 + 3. Here + is an operator that
represents the addition operation. Similarly, C++ has a rich collection of operators. An
operator is a symbol that tells the compiler about a specific operation. They are the
tokens that trigger some kind of operation. The operator is applied on a set of data
called operands. C++ provides different types of operators like arithmetic, relational,
logical, assignment, conditional, etc. We will discuss more about operators in the next
chapter.
116
4. Getting Started with C ++
Fig. 4.1: Edit window of Geany IDE for Ubuntu Linux 12.04
117
name for the opened edit area. If we use Geany 1.24 on Windows OS, the opening
window will be as shown in Figure 4.2. We can see that both of these are quite the same.
118
4. Getting Started with C ++
119
d. Running/Executing the program
Running the program is the process by which a computer carries out the instructions of
a computer program. To run the program, choose Build menu and select Execute
option. The program can also be executed by pressing the function key F5. The output
will be displayed in a new window as shown in Figure 4.5.
120
4. Getting Started with C ++
Let us sum up
C++ was developed by Bjarne Stroustrup in early 1980s. C++ has its own character
set. Tokens are the smallest unit of a program and are constituted by one or more
characters in C++. There are five types of tokens namely keywords, identifiers,
literals, punctuators and operators. Programs are written in computer with the help
of an editor. Software like GCC and Geany IDE provide facilities to enter the source
code in the computer, compile it and execute the object code.
Learning outcomes
Sample questions
Very short answer type
1. What are the different types of characters in C++ character set?
2. What is meant by escape sequences?
3. Who developed C++?
4. What is meant by tokens? Name the tokens available in C++.
5. What is a character constant in C++ ?
6. How are non-graphic characters represented in C++? Give an example.
7. Why are the characters \ (slash), ' (single quote), " (double quote) and ? (question
mark) typed using escape sequences?
8. Which escape sequences represent newline character and null character?
121
9. An escape sequence represents ______ characters.
10. Which of the following are valid character/string constants in C++?
'c' 'anu' "anu" mine 'main's' " "
'char '\ \'
11. What is a floating point constant? What are the different ways to represent a
floating point constant?
12. What are string-literals in C++? What is the difference between character con-
stants and string literals?
13. What is the extension of C++ program file used for running?
14. Find out the invalid identifiers among the following. Give reason for their invalidity
a) Principal amount b) Continue c) Area
d) Date-of-join e) 9B
15. A label in C++ is ________.
a) Keyword b) Identifier c) Operator d) Function
16. The following tokens are taken from a C++ program. Fill up the given table by
placing them at the proper places
( int, cin, %, do, =, "break", 25.7, digit)
Keywords Identifiers Literals Operators
122
5. Data Types and Operators
123
From the above cases, we can infer that data can be of different types like character,
integer number, real number, string, etc. In the last chapter we saw that any valid character
of C++ enclosed in single quotes represents character data in C++. Numbers without
fractions represent integer data. Numbers with fractions represent floating point data
and anything enclosed in double quotes represents a string data. Since the data to be
dealt with are of many types, a programming language must provide ways and facilities
to handle all types of data. C++ provides facilities to handle different types of data by
providing data type names. Data types are the means to identify the nature of the data
and the set of operations that can be performed on the data.
In Chapter 3, we used variables to refer data in algorithms. Variables are also used in
programs for referencing data. When we write programs in the C++ language, variables
are to be declared before their use. Data types are necessary to declare these variables.
124
5. Data Types and Operators
five fundamental data types in C++ are char, int, float, double and void.
Among these, int and char come under integral data type as they can handle only
integers. The numbers with fractions (real numbers) are generally known as floating
type and are further divided into float and double based on precision and range.
125
recognises the character through its ASCII code. Character data is stored in the memory
with the corresponding ASCII code. As ASCII codes are integers and need to be
stored in one byte (8 bits), the range of char data type is from -128 to +127.
float data type (for floating point numbers)
Numbers with a fractional part are called floating point numbers. Internally, floating
point numbers are stored in a manner similar to scientific notation. The number 47281.97
is expressed as 0.4728197×105 in scientific notation. The first part of the number,
0.4728197 is called the mantissa. The power 5 of 10 is called exponent. Computers
typically use exponent form (E notation) to represent floating point values. In E notation,
the number 47281.97 would be 0.4728197E5. The part of the number before the E is
the mantissa, and the part after the E is the exponent. In C++, the keyword float is
used to denote such numbers. GCC allows 4 bytes of memory for numbers belonging
to float data type. The numbers of this data type has normally a precision of 7 digits.
double data type (for double precision floating point numbers)
In some cases, floating point numbers require more precision. Such numbers are
represented by double data type. The range of numbers that can be handled by
float type is extended by this data type, because it consumes double the size of
float data type. In C++, it is assured that the range and precision of double will be
at least as big as float. GCC reserves 8 bytes for storing a double precision value.
The precision of double data type is generally 15 digits.
void data type (for null or empty set of values)
The data type void is a keyword and it indicates an empty set of data. Obviously it
does not require any memory space. The use of this data type will be discussed in the
next chapter. Table 5.1 shows the size and range of the fundamental data types of C++
based on GCC. The size of fundamental data types decreases in the order double,
float, int and char.
126
5. Data Types and Operators
The values listed above are only sample values to give you a general
idea of how the types differ. The values for any of these entries may
be different on your system
5.4 Variables
Memory locations are to be identified to refer data. Variables are the names given to
memory locations. These are identifiers of C++ by which memory locations are
referenced to store or retrieve data. The size and nature of data stored in a variable
depends on the data type used to declare it. There are three important aspects for a
variable.
i. Variable name
It is a symbolic name (identifier) given to the memory location through which the content
of the location is referred to.
ii. Memory address
The RAM of a computer consists of collection of cells each of which can store one byte
of data. Every cell (or byte) in RAM will be assigned a unique address to refer it. All the
variables are connected to one or more memory locations in RAM. 1001 1002 1003 1004
The base address of a variable is the starting address of the allocated
18
memory space. In the normal situation, the address is given implicitly
by the compiler. The address is also called the L-value of a variable. Num
Fig 5.2 : Memory
In Figure 5.2 the base address of the variable Num is 1001. representation
of a Variable
iii. Content
The value stored in the location is called content of the variable. This is also called the
R-value of the variable. Type and size of the content depends on the data type of the
variable.
Figure 5.2 shows the memory representaion of a variable. Here the variable name is
Num and it consumes 4 bytes of memory at memory addresses 1001, 1002, 1003 and
1004. The content of this variable is 18. That is L-value of Num is 1001 and R-value is
18.
5.5 Operators
Operators are tokens constituted by predefined symbols that can trigger computer to
carry out operations. The participants of an operation are called operands. An operand
may be either a constant or a variable.
127
For example, a+b triggers an arithmetic operation in which + (addition) is the operator
and a, b are operands. Operators in C++ are classified based on various criteria.
Based on number of operands required for the operation, operators are classified into
three. They are unary, binary and ternary.
Unary operators
A unary operator operates on a single operand.
Commonly used unary operators are unary+ Variable Unary + Unary-
(positive) and unary- (negative). These are used x +x -x
to represent the signs of a number. If we apply 8 8 -8
unary+ operator on a signed number, the existing
0 0 0
sign will not change. If we apply unary- operator
on a signed number, the sign of the existing -9 -9 9
number will be negated. Examples of the use of Table 5.2 : Unary operators
unary operators are given in Table 5.2.
Some other examples of unary operators are increment (++) and decrement (--)
operators. We will discuss these operators later in this chapter.
Binary operators
Binary operators operate on two operands. Arithmetic operators, relational operators,
logical operators, etc. are the commonly used binary operators.
Ternary operator
Ternary operator operates on three operands. The typical example is the conditional
operator (?:).
The operations triggered by the operators mentioned above will be discussed in detail
in the coming sections and some of them will be dealt with in Chapter 7. Based on the
nature of the operation, operators are classified into arithmetic, relational, logical, input/
output, assignment, short-hand, increment/decrement, etc.
128
5. Data Types and Operators
Check yourself
129
5.5.2 Relational operators
Relational operators are used for comparing numeric data. These are binary operators.
The result of any relational operation will be either True or False. In C++, True is
represented by 1 and False is represented by 0. There are six relational operators in
C++. They are < (less than), > (greater than), == (equal to), <= (less than or equal to),
>= (greater than or equal to) and != (not equal to). Note that equality checking requires
two equal symbols (==). Some examples for the use of various relational operators
and their results are shown in Table 5.5:
130
5. Data Types and Operators
131
Item Description
a=b The value of variable b is stored in a
a=3 The constant 3 is stored in variable a
Table 5.9 : Assignment operator
We discussed the relational operator == in Section 5.5.2. See the difference between
these two operators. The = symbol assigns a value to a variable, whereas == symbol
compares two values and gives True or False as the result.
5.6 Expressions
An expression is composed of operators and operands. The operands may be either
constants or variables. All expressions can be evaluated to get a result. This result is
known as the value returned by the expression. On the basis of the operators used,
expressions are mainly classified into arithmetic expressions, relational expressions and
logical expressions.
5 2 7 2 5 7 1
6 3 9 2 12 7 0
Table 5.10 : Integer expressions and their results
Note that all the above expressions produce integer values as the results.
Floating point expressions (Real expressions)
An arithmetic expression that is composed of only floating point data is called floating
point or real expression and it returns a floating point result after performing all the
132
5. Data Types and Operators
operations given in the expression. Table 5.11 shows some real expressions and their
results, assuming that x and y are floating point variables.
x y x + y x / y -x + x * y 5 + x / y x * x / y
It can be seen that all the above expressions produce floating point values as the results.
In an arithmetic expression, if all the operands are constant values, then it is called
Constant expression. The expression 20+5/2.0 is an example. The constants like
15, 3.14, 'A' are also known as constant expressions.
We know that arithmetic operators have a higher priority than relational operators. So
when arithmetic expressions are used on either side of a relational operator, arithmetic
operations will be carried out first and then the results are compared. The table contains
some expressions in which both arithmetic and relational operators are involved. Though
they contain mixed type of operators, they are called relational expressions since the
final result will be either True or False.
5.6.3 Logical expressions
Logical expressions combine two or more relational expressions with logical operators
and produce either True or False as the result. A logical expression may contain constants,
variables, logical operators and relational operators. Let us see some examples in Table
5.13.
133
x y x>=y && x==20 x==5||y==0 x==y && y+2==0 !(x==y)
Check yourself
5.7 Statements
Can you recollect the learning hierarchy of a natural language? Alphabet, words, phrases,
sentences, paragraphs and so on. In the learning process of C++ language we have
covered character set, tokens and expressions. Now we have come to the stage where
we start communication with the computer sensibly and meaningfully with the help of
statements. Statements are the smallest executable unit of a programming language.
C++ uses the symbol semicolon ( ; ) as the delimiter of a statements. Different types of
statements used in C++ are declaration statements, assignment statements, input
statements, output statements, control statements, etc. Each statement has its own
purpose in a C++ program. All these statements except declaration statements are
executable statements as they possess some operations to be done by the computer.
Executable statements are the instructions to the computer. The execution of control
statements will be discussed in Chapter 7. Let us discuss the other statements.
134
5. Data Types and Operators
135
The left hand side (LHS) of an assignment statement must be a variable. During execution,
the expression at the right hand side (RHS) is evaluated first. The result is then assigned
(stored) to the variable at LHS.
Assignment statement can be chained for doing multiple assignments at a time. For
instance, the statement x=y=z=13; assigns the value 13 in three variables in the order
of z, y and x. The variables should be declared before this assignment. If we assign a
value to a variable, the previous value in it, if any, will be replaced by the new value.
136
5. Data Types and Operators
The tokens cin and cout are not keywords. They are predefined
words that are not part of the core C++ language, and you are allowed
to redefine them. They are defined in libraries required by the C++
language standard. Needless to say, using a predefined identifier for
anything other than its standard meaning can be confusing and dangerous and such
practices should be avoided. The safest and easiest practice is to treat all predefined
identifiers as if they were keywords.
137
Cascading of I/O operators
Suppose you want to input three values to different variables, say x, y and z. You may
use the following statements:
cin>>x;
cin>>y;
cin>>z;
But these three statements can be combined to form a single statement as given below:
cin>>x>>y>>z;
The multiple use of input or output operators in a single statement is called cascading
of I/O operators. In the use of cascading of input operators, the values input are
assigned to the variables from left to right. In the example cin>>x>>y>>z; the first
value is assigned to x, the second to y and the third to z. While entering values to the
variables x, y and z during execution the values should be separated by Space bar,
Tab or Carriage return.
Similarly, if you want to display the contents of different variables (say x, y, z) use the
following statement:
cout<<x<<y<<z;
If variables, constants and expressions appear together for output operations, the above
technique can be applied as in the following example:
cout<<"The number is "<<z;
While cascading output operators, the values for the output will be retrieved from right
to left. It is to be noted that both << and >> operators cannot be used in a single
statement.
Let us sum up
Data types are means to identify the type of data and associated operations handling
it. Each data type has a specific size and a range of data. Data types are used to
declare variables. Different types of operators are available in C++ for various
operations. When operators are combined with operands (data), expressions are
formed. There are mainly three types of expressions - arithmetic, relational and
logical. Statements are the smallest executable unit of a program. Variable declaration
statements define the variables in the program and they will be allocated memory
space. The executable statements like assignment statements, input statements, output
statements, etc. help giving instructions to the computer.
138
5. Data Types and Operators
Learning outcomes
After the completion of this chapter the learner will be able to
• identify the various data types in C++.
• choose appropriate variables.
• experiment with various operators.
• apply the various I/O operators.
• write various expressions and statements.
Sample questions
Very short answer type
1. What are data types? List all predefined data types in C++?
2. What is the use of void data type?
3. What is a constant?
4. What is dynamic initialisation of variables?
5. Define operators.
6. What is meant by a unary operation?
7. What is declaration statement?
8. What is the input operator ">>" and output operator "<<" called ?
9. What will be the result of a = 5/3 if a is (i) float (ii) int ?
10. Write an expression that uses a relational operator to return true if the variable
total is greater than or equal to final.
11. Given that i =4, j =5, k =2 what will be the result of following expressions?
(i) j <k (ii) j <j (iii) j <= k (iv) i == j (v) i == k
(vi) j > k (vii) j >= i (viii) j! = i (ix) j! = k (x) j <= k
12. What will be the order of evaluation for following expressions?
(i) i+5>=j-6 (ii) s+10<p-2+2*q
15. What will be the result of the following if ans is 6 initially?
(i) cout <<ans = 8 ; (ii) cout << ans == 8
139
Short answer type
1. What is a variable? List the two values associated with a variable.
2. Explain logical operators.
3. Find out the errors, if any, in the following C++ statements
(i) cout<< "a=" a; (v) cin >> "\n" >> y ;
(ii) m=5, n=l2;015 (vi) cout >> \n "abc"
(iii) cout << "x" ; <<x; (vii) a = b + c
(iv) cin >> y (viii) break = x
4. What is the role of relational operators? Distinguish between == and =.
140
6. Introduction to Programming
Key concepts
• Structure of C++ Program We have familiarized ourselves with the IDE
o Pre-processor directives used for C++ program. In the last chapter we
discussed how operations can be expressed in
o Header files
C++. We also learnt different types of
o A sample C++ program statements in C++ to give instructions to the
• Stylistic guidelines for computer. We are now in a position to solve
variables and comments simple problems by using these statements. But
• Variable initialization
a set of statements alone does not constitute a
program. A C++ program has a typical
• Use of const access modifier
structure. In this chapter we discuss the
• Type modifiers structure of C++ programs and we write
• More operators programs accordingly. More operators are
introduced for making the programs compact
o Arithmetic assignment
and the execution faster.
o Increment and decrement
6.1 Structure of a C++ program
o Precedence of operators
C++ program is a collection of one or more
• Type conversions
functions. A function means a set of instructions
o Implicit type conversion to perform a particular task referred to by a
o Explicit type conversion name. Since there can be many functions in a
C++ program, they are usually identified by
unique names. The most essential function
needed for every C++ program is the main()
function. Let us look at the structure of a simple
C++ program.
141
#include <headerfile>
using namespace identifier;
int main()
{
statements;
:
:
:
return 0;
}
The first line is called preprocessor directive and the second line is the namespace
statement. The third line is the function header which is followed by a set of statements
enclosed by a pair of braces. Let us discuss each of these parts of the program.
6.1.1 Preprocessor directives
A C++ program starts with pre-processor directives. Preprocessors are the compiler
directive statements which give instruction to the compiler to process the information
provided before actual compilation starts. Preprocessor directives are lines included in
the code that are not program statements. These lines always start with a # (hash)
symbol. The preprocessor directive #include is used to link the header files available
in the C++ library by which the facilities required in the program can be obtained. No
semicolon (;) is needed at the end of such lines. Separate #include statements
should be used for different header files. There are some other preprocessor directives
such as #define, #undef, etc.
6.1.2 Header files
Header files contain the information about functions, objects and predefined derived
data types and are available along with compiler. There are a number of such files to
support C++ programs and they are kept in the standard library. Whichever program
requires the support of any of these resources, the concerned header file is to be included.
For example, if we want to use the predefined objects cin and cout, we have to use
the following statement at the beginning of the program:
#include <iostream>
The header file iostream contains the information about the objects cin and cout.
Eventhough header files have the extension .h, it should not be specified for GCC.
But the extension is essential for some other compilers like Turbo C++ IDE.
6.1.3 Concept of namespace
A program cannot have the same name for more than one identifier (variables or functions)
in the same scope. For example, in our home two or more persons (or even living
142
6. Introduction to Programming
beings) will not have the same name. If there are, it will surely make conflicts in the
identity within the home. So, within the scope of our home, a name should be unique.
But our neighbouring home may have a person (or any living being) with the same name
as that of one of us. It will not make any confusion of identity within the respective
scopes. But an outsider cannot access a particular person by simply using the name;
but the house name is also to be mentioned.
The concept of namespace is similar to a house name. Different identifiers are associated
to a particular namespace. It is actually a group name in which each item is unique in its
name. User is allowed to create own namespaces for variables and functions. We can
use an identifier to give a name to the namespace. The keyword using technically tells
the compiler about a namespace where it should search for the elements used in the
program. In C++, std is an abbreviation of 'standard' and it is the standard namespace
in which cout, cin and a lot of other objects are defined. So, when we want to use
them in a program, we need to follow the format std::cout and std::cin. This
kind of explicit referencing can be avoided with the statement using namespace std; in
the program. In such a case, the compiler searches this namespace for the elements
cin, cout, endl, etc. So whenever the computer comes across cin, cout, endl
or anything of that matter in the program, it will read it as std::cout, std::cin or
std::endl.
The statement using namespace std; doesn't really add a function, it is the
#include <iostream> that "loads" cin, cout, endl and all the like.
6.1.4 The main() function
Every C++ program consists of a function named main(). The execution starts at
main() and ends within main(). If we use any other function in the program, it is
called (or invoked) from main(). Usually a data type precedes the main() and in
GCC, it should be int.
The function header main() is followed by its body, which is a set of one or more
statements within a pair of braces { }. This structure is known as the definition of the
main() function. Each statement is delimited by a semicolon (;). The statements may
be executable and non-executable. The executable statements represent instructions to
be carried out by the computer. The non-executable statements are intended for compiler
or programmer. They are informative statements. The last statement in the body of
main() is return 0;. Even though we do not use this statement, it will not make
any error. Its relavance will be discussed in Class XII.
C++ is a free form language in the sense that it is not necessary to write each statement
in new lines. Also a single statement can take more than one line.
143
6.1.5 A sample program
Let us look at a complete program and familiarise ourselves with its features, in detail.
This program on execution will display a text on the screen.
#include<iostream>
using namespace std;
int main()
{
cout<<"Hello, Welcome to C++";
return 0;
}
The program has seven lines as detailed below:
Line 1: The preprocessor directive #include is used to link the header file
iostream with the program.
Line 2: The using namespace statement makes available the identifier cout in
the program.
Line 3: The header of the essential function for a C++ program, i.e., int main().
Line 4: An opening brace { that marks the beginning of the instruction set (program).
Line 5: An output statement, which will be executed when we run the program, to
display the text "Hello, Welcome to C++" on the monitor. The header
file iostream is included in this program to use cout in this statement.
Line 6: The return statement stops the execution of the main() function. This
statement is optional as far as main() is concerned.
Line 7: A closing brace } that marks the end of the program.
6.2 Guidelines for coding
A source code looks good when the coding is legible, logic is communicative and
errors if any are easily detectable. These features can be experienced if certain styles
are followed while writing program. Some guidelines are discussed below to write
stylistic programs:
Use suitable naming convention for identifiers
Suppose we have to calculate the salary for an employee after deductions. We may
code it as: A = B - C;
where A is the net salary, B the total salary and C total deduction. The variable names
A, B and C do not reflect the quantities they denote. If the same instruction is expressed
as follows, it would be better:
Net_salary = Gross_salary - Deduction;
144
6. Introduction to Programming
The variable names used in this case help us to remember the quantity they possess.
They readily reflect their purpose. This kind of identifiers are called mnemonic names.
The points given below are to be remembered in the choice of names:
• Choose good mnemonic names for all variables, functions and procedures.
e.g. avg_hgt, Roll_No, emp_code, SumOfDigits, etc.
• Use standardised prefixes and suffixes for related variables.
e.g. num1, num2, num3 for three numbers
• Assign names to constants in the beginning of the program.
e.g. float PI = 3.14;
Use clear and simple expressions
Some people have a tendency to reduce the execution time by sacrificing simplicity.
This should be avoided. Consider the following example. To find out the remainder
after division of x by n, we can code as: y = x-(x/n)*n;
The same thing is achieved by a simpler and more elegant piece of code as shown
below:
y = x % n;
So it is better to use simpler codes in programming to make the program more simple
and clear.
Use comments wherever needed
Comments play a very important role as they provide internal documentation of a program.
They are lines in code that are added to describe the program. They are ignored by the
compiler. There are two ways to write comments in C++:
Single line comment: The characters // (two slashes) is used to write single line
comments. The text appearing after // in a line is treated as a comment by the C++
compiler.
Multiline comments: Anything written within /* and */ is treated as comment so
that the comment can take any number of lines.
But care should be taken that no relevant code of the program is included accidently
inside the comment. The following points are to be noted while commenting:
• Always insert prologues, the comments in the beginning of a program that
summarises the purpose of the program.
• Comment each variable and constant declaration.
• Use comments to explain complex program steps.
145
• It is better to include comments while writing the program itself.
• Write short and clear comments.
Relevance of indentation
In computer programming, an indent style is a convention governing the indentation of
blocks of code to convey the program's structure, for good visibility and better clarity.
An indentation makes the statements clear and readable. It shows the levels of statements
in the program.
The usages of these guidelines can be observed in the programs given in a later section
of this chapter.
6.3 Variable initialisation
In the last chapter we discussed the significance of variables in programs. A variable is
associated with two values: L-value (its address) and R-value (its content). When a
variable is declared, a memory location with an address will be allocated and it is the L-
value of the variable. What will its content be? It is not blank or 0 or space! If the
variable is declared with int data type, the content or the R-value will be any integer
within the allowed range. But this number cannot be predicted or will not always be the
same. So we call it garbage value. When we store a value into the variable, the existing
content will be replaced by the new one. The value can be stored in the variable either
at the time of compilation or execution. Supplying value to a variable at the time of its
declaration is called variable initialisation. This value will be stored in the respective
memory location during compile-time. The assignment operator (=) is used for this. It
can be done in two ways as given below:
data_type variable = value;
OR data_type variable(value);
The statements: int xyz=120; and int xyz(120); are examples of variable
initialisation statements. Both of these statements declare an integer variable xyz and
store the value 120 in it as shown in Figure 6.1.
More examples are:
float val=0.12, b=5.234;
char k='A';
Fig 6.1: Variable initialisation
A variable can also be initialised during the execution of the program and is known as
dynamic initialisation. This is done by assigning an expression to a variable as shown in
the following statements:
float product = x * y;
float interest= p*n*r/100.0;
146
6. Introduction to Programming
In the first statement, the variable product is initialised with the product of the values
stored in x and y at runtime. In the second case, the expression p*n*r/100.0 is
evaluated and the value returned by it will be stored in the variable interest at
runtime.
Note that during dynamic initialisation, the variables included in the expression at the
right of assignment operator should have valid data, otherwise it will produce unexpected
results.
6.4 const - The access modifier
It is a good practice to use symbolic constants rather than using numeric constants
directly. For example, we can use symbolic name like pi instead of using
22.0/7.0 or 3.14. The keyword const is used to create such symbolic constants
whose value can never be changed during execution.
Consider the statement: float pi=3.14;
The floating point variable pi is initialised with the value 3.14. The content of pi can
be changed during the execution of the program. But if we modify the declaration as:
const float pi=3.14;
the value of pi remains constant (unaltered) throughout the execution of the program.
The read/write accessibility of the variable is modified as read only. Thus, the const
acts as an access modifier.
During software development, larger programs are developed using
collaborative effort. Several people may work together on different
portions of the same program. They may share the same variable. In
these situations, there may be occasions where one may modify the
content of the variable which will adversely affect other person's coding. In these
situations we have to keep the content of variables unaffected by the activity of
others. This can be done by using const.
147
permitted to a data type by altering the memory size and/or sign of values. Important
modifiers are signed, unsigned, long and short.
The exact sizes of these data types depend on the compiler and computer you are
using. It is guaranteed that:
• a double is at least as big as a float.
• a long double is at least as big as a double.
Each type and their modifiers are listed in Table 6.1 (based on GCC compiler) with
their features.
Name Description Size Range
long 10 bytes
Long double precision -3.4 × 10+/-4932 to +3.4 ×10+/-4932 With
double floating point number approximately 19 significant digits
Table 6.1 : Data type and type modifiers
The values listed above are only sample values to give you a general
idea of how the types differ. The values for any of these entries may
be different on your system.
We discussed the operators in C++ for the commonly used operations. There are
some special operators in C++ which make programs more condensed. They combine
two operations together. We will discuss a few of them which combine assignment and
148
6. Introduction to Programming
149
Consider the variables a, b, c and d with values a=10, b=5. If an operation specified
as c=++a, the value of a will be 11 and that of c will also be 11. Here the value of a is
incremented by 1 at first and then the changed value of a is assigned to c. That is why
both the variables get the same value. Similarly, after the execution of d=--b the value
of d and b will be 4.
Postfix form of increment/decrement operators
When increment/decrement operation performed in postfix form, the operator is placed
after the operand. The current value of the variable is used for the remaining operation
and after that the increment/decrement operation is carried out. So, this method is often
called use, then change method.
Consider the same variables used above with the same initial values. After the operation
performed with c=a++, the value of a will be 11, but that of c will be 10. Here the
value of a is assigned to c at first and then a is incremented by 1. That is, before
changing the value of a it is used to assign to c. Similarly, after the execution of
d=b-- the value of d will be 5 but that of b will be 4.
6.6.3 Precedence of operators
Let us consider the case where different operators are used with the required operands.
We should know in which order the operations will be carried out. C++ gives priority
to the operators for execution. During execution, a pair of parentheses is given the first
priority. If the expression is not parenthesised, it is evaluated according to some
precedence order. The order is given in Table 6.3. In an expression, if the operations of
same priority level occur, the precedence of execution will be from left to right in most
of the cases.
Consider the variables with the values: a=3, b=5, c=4, d=2, x
After the operations specified in the following:
x = a + b * c - d;
the value in x will be 21. Here * (multiplication) has higher priority than + (addition)
and - (subtraction). Therefore the variables b and c are multiplied, then that result is
added to a. From that result, d is subtracted to get the final result.
It is important to note that the operator priority can be changed in an expression as per
the need of the programmer by using parentheses ( ).
For example, if a=5, b=4, c=3, d=2 then the result of a+b-c*d will be 3.
Suppose the programmer wants to perform subtraction first, then addition and
multiplication, you need to use proper parentheses as (a+(b-c))*d. Now the output
will be 12. For changing operator priority, brackets [] and braces {} cannot be used.
150
6. Introduction to Programming
Priority Operations
1 ( ) parentheses
2 ++, --, ! , Unary+ , Unary –, sizeof
3 * (multiplication), / (division), % (Modulus)
4 + (addition), - (subtraction)
5 < (less than), <= (less than or equal to), > (greater than), >= (greater
than or equal to)
6 == (equal to), != (not equal to)
7 && (logical AND)
8 || (logical OR)
9 ? : (Conditional expression)
10 = (Assignment operator), *=, /=, %=, +=, -= (arithmetic assignment
operators)
11 , (Comma)
151
For example, consider the expression 5 / 2 * 3 + 2.5 which gives the result
8.5. The evaluation steps are as follows:
Step 1: 5 / 2 à 2 (Integer division)
Step 2: 2 * 3 à 6 (Integer multiplication)
Step 3: 6 + 2.5 à 8.5 (Floating point addition, 6 is converted into 6.0)
6.7.2 Explicit type conversion (Type casting)
Unlike implicit type conversion, sometimes the programmer may decide the data type
of the result of evaluation. This is done by the programmer by specifying the data type
within parentheses to the left of the operand. Since the programmer explicitly casts a
data to the desired type, it is also known as explicit type conversion or type casting.
Usually, type casting is applied on the variables in the expressions. The data type
compatibility is to be seriously considered in assignment statements where expressions
are involved.
Type compatibility in assignment statement
During the execution of an assignment statement, if the data type of the RHS expression
is different from that of the LHS variable, there are two possibilities.
• The size of the data type of the variable at LHS is higher than that of the variable
or expression at RHS. In this case data type of the value at RHS is promoted
(type promotion) to that of the variable at LHS. Consider the following code
snippet:
int a=5, b=2;
float p, q;
p = b;
q = a / p;
Here the data type of b is promoted to float and 2.0 is stored in p. So when the
expression a/p is evaluated, the result will be 2.5 due to the type promotion of a. So,
q will be assigned with 2.5.
• The second possibility is that the size of the data type of LHS variable is smaller
than the size of RHS value. In this case, the higher order bits of the result will be
truncated to fit in the variable location of LHS. The following code illustrates this.
float a=2.6;
int p, q;
p = a;
q = a * 4;
152
6. Introduction to Programming
Here the value of p will be 2 and that of q will be 10. The expression a*4 is evaluated
to 10.4, but q being int type it will hold only 10.
Programmer can apply the explicit conversion technique to get the desired results when
there are mismatches in the data types of operands. Consider the following code segment.
int p=5, q=2;
float x, y;
x = p/q;
y = (x+p)/q;
After executing the above code, the value of x will be 2.0 and that of y will be 3.5. The
expression p/q being an integer expression gives 2 as the result and is stored in x as
floating point value. In the last statement, the pair of parentheses gives priority to x+p
and the result will be 7.0 due to the type promotion of p. Then the result 7.0 will be the
first operand for the division operation and hence the result will be 3.5 since q is converted
into float. If we have to get the floating point result from p/q to store in x, the
statement should be modified as x=(float)p/q; or x=p/(float)q; by applying
type casting.
Program Gallery
Let us write programs to solve some problems following the guidelines. Program 6.1
displays a message.
Program 6.1: To display a message
153
Program 6.2: To find the sum of two numbers
#include <iostream>
using namespace std;
int main()
{ //Program begins
/* Two variables are declared to read user inputs
and the variable sum is declared to store the result */
int num1, num2, sum;
cout<<"Enter two numbers: ";//Used as prompt for input
cin>>num1>>num2; //Cascading facility to get two numbers
sum=num1+num2; //Assignment statement to store the sum
/* The result is displayed with proper message.
Cascading of output operator is utilized */
cout<<"Sum of the entered numbers = "<<sum;
return 0;
}
A sample output of Program 6.2 is given below:
Enter two numbers: 5 7 User inputs separated by spaces
Sum of the entered numbers = 12
Run Program 6.2 with some other inputs like 5.2 and 2.7 and
check whether you get correct answer. If not, discuss with your
friends to identify the problem and find solution.
Let us do
Let's consider another problem. A student is awarded the scores in three Continuous
Evaluation activities. The maximum score of an activity is 20. Find the average score of
the student.
Program 6.3: To find the average of three CE scores
#include <iostream>
using namespace std;
int main()
{
int score_1, score_2, score_3;
float avg;//Average of 3 numbers may be a floating point
cout << "Enter the three scores: ";
cin >> score_1 >> score_2 >> score_3;
154
6. Introduction to Programming
155
A sample output of Program 6.4 is shown below:
Enter the radius of a circle: 2.5
Area of the circle = 19.642857
Perimeter of the circle = 15.714285
The last two output statements of Program 6.4 display both the results in separate lines.
The escape sequence character '\n' brings the cursor to the new line before the last
output statement gets executed.
Let's develop yet another program to find simple interest. As you know, principal amount,
rate of interest and period are to be input to get the result.
Program 6.5: To find the simple interest
#include <iostream>
using namespace std;
int main()
{
float p_Amount, n_Year, i_Rate, int_Amount;
cout<<"Enter the principal amount in Rupees: ";
cin>>p_Amount;
cout<<"Enter the number of years of deposit: ";
cin>>n_Year;
cout<<"Enter the rate of interest in percentage: ";
cin>>i_Rate;
int_Amount = p_Amount * n_Year * i_Rate /100;
cout << "Simple interest for the principal amount "
<< p_Amount
<< " Rupees for a period of " << n_Year
<< " years at the rate of interest " << i_rate
<< " is " << int_Amount << " Rupees";
return 0;
}
156
6. Introduction to Programming
The last statement in Program 6.5 is an output statement and it spans over five lines. It
is a single statement. Note that there is no semicolon at the end of each line. On execution
the result may be displayed in two lines depending on the size and resolution of the
monitor of your computer.
Program 6.6 solves a conversion problem. The temperature in degree Celsius will be
the input and the output will be its equivalent in Fahrenheit.
Program 6.6: To convert temperature from Celsius to Fahrenheit
#include <iostream>
using namespace std;
int main()
{
float celsius, fahrenheit;
cout<<"Enter the Temperature in Celsius: ";
cin>>celsius;
fahrenheit=1.8*celsius+32;
cout<<celsius<<" Degree Celsius = "
<<fahrenheit<<" Degree Fahrenheit";
return 0;
}
Program 6.6 gives a sample output as follows:
Enter the Temperature in Celsius: 37
37 Degree Celsius = 98.599998 Degree Fahrenheit
We know that each character literal in C++ has a unique value called its ASCII code.
These codes are integers. Let us write a program to find the ASCII code of a given
character.
Program 6.7: To find the ASCII code of a character
#include <iostream>
using namespace std;
int main( )
{
char ch;
int asc;
cout << "Enter the character: ";
cin >> ch;
asc = ch;
cout << "ASCII of "<<ch<<" = " << asc;
return 0;
}
157
A sample output of Program 6.7 is given below:
Enter the character A
ASCII of A = 65
Let us sum up
C++ program has a typical structure and it must be followed while writing programs.
Stylistic guidelines shall be followed to make the program attractive and communicative
among humans. While declaring variables, they can be initialised with user supplied
values. The value thus assigned cannot be changed if we use const access modifier
in the variable initialization statement. Type modifiers help handling a higher range of
data and are used with data types to declare variables. There are some special
operators in C++ for performing arithmetic and assignment operations together.
Type conversion methods are available in C++ and are used to get desired results
from arithmetic expressions.
Learning outcomes
After the completion of this chapter the learner will be able to
• list and choose appropriate data type modifiers.
• experiment with various operators.
• apply the various I/O operators.
• identify the structure of a simple C++ program.
• identify the need for stylistic guidelines while writing a program.
• write simple programs using C++ IDE.
Lab activity
1. Write a program that asks the user to enter the weight in grams, and then display
the equivalent in Kilogram.
2. Write a program to generate the following table
2013 100%
2012 99.9%
2011 95.5%
2010 90.81%
2009 85%
158
6. Introduction to Programming
Use a single cout statement for output. (Hint: Make use of \n and \t)
3. Write a short program that asks for your height in Meter and Centimeter and
converts it to Feet and inches. (1 foot = 12 inches, 1 inch = 2.54 cm).
4. Write a program to find area of a triangle.
5. Write a program to compute simple interest and compound interest.
6. Write a program to : (i) print ASCII code for a given digit. (ii) print ASCII code
for backspace. (Hint : Store escape sequence for backspace in an integer vari-
able).
7. Write a program to accept a time in seconds and convert into hrs: mins: secs
format. For example, if 3700 seconds is the input, the output should be 1hr: 1 min:
40 secs.
Sample questions
Very short answer type
1. What is dynamic initialisation of variables?
2. What is type promotion?
3. What do you mean by type casting? What is type cast operator?
159
10. Identify the errors in the following code segments
i. int main ( ) { cout << "Enter two numbers"
cin >> num >> auto
float area = Length * breadth ; }
ii. #include <iostream>
using namespace;
int Main()
{ int a, b
cin <<a >>b
max = a % b
cout > max
}
11. Comments are a useful and an easy way to enhance readability and understand-
ability of a program. Justify this statement with examples.
160
7. Control Statements
161
in other situations. The computer has to take the required decision in this respect. For
this, we have to provide appropriate conditions which will be evaluated by the computer.
It will then take a decision on the basis of the result. The decision will be in the form of
selecting a particular statement for execution or skipping some statements from being
executed. The statements provided by C++ for the selected execution are called decision
making statements or selection statements. if and switch are the two types of
selection statements in C++.
7.1.1 if statement
The if statement is used to select a set of statements for execution based on a condition.
In C++, conditions, otherwise known as test expressions are provided by relational or
logical expressions. The syntax (general form) of if statement is as follows:
162
7. Control Statements
Program 7.1 accepts the score of a student and displays the text “You have passed”
only if he/she has passed. (assume that 18 is the minimum for pass).
Program 7.1: To display ‘You have Passed’ if score is 18 or more
#include <iostream>
using namespace std;
int main()
{
int score ;
cout << "Enter your score: ";
cin >> score;
if (score >= 18) Body of if
cout << "You have Passed";
return 0;
}
The following is a sample output of program 7.1:
Enter your score : 25
You have passed
In Program 7.1, the score of a student is entered and stored in the variable score. The
test expression compares the value of score with 18. The body of if will be executed
only if the test expression evaluates to True. That means, when the score is greater than
or equal to18, the output “You have Passed” will be displayed on the screen.
Otherwise, there will be no output.
Note that, the statement block associated with if is written after a tab space. We call
it indentation. This is a style of coding which enhances the readability of the source
code. Indentation helps the debugging process greatly. But it has no impact on the
execution of the programme.
Consider the following C++ program segement. It checks whether a given character is
an alphabet or a digit.
char ch; Logical expression is evaluated
cin >> ch; Only a single
if (ch >= ‘a’ && ch <= ‘z’) statement. No
cout <<"You entered an alphabet"; need of braces { }
if (ch >= ‘0’ && ch <= ‘9’)
{ More than
cout<< "\nYou entered a digit"; one statement;
Must be
cout<< "\nIt is a decimal number"; enclosed in
} braces { }
163
7.1.2 if...else statement
Consider the if statement in Program 7.1:
if (score >= 18)
cout << "You have Passed";
Here, the output is obtained only if the score is greater than or equal to 18. What will
happen if the score entered is less than 18? It is clear that there will be no output.
Actually we don't have the option of selecting another set of statements if the test
expression evaluates to False. If we want to execute some actions when the condition
becomes False, we introduce another form of if statement, if..else. The syntax is:
if (test expression)
{
statement block 1;
}
else
{
statement block 2;
}
Here, if the t e s t
expression evaluates to
True, only the statement
block 1 is executed. If
the test expression
evaluates to False,
statement block 2
is executed. The flowchart
shown in Figure 7.2
explains the execution of Fig 7.2: Flowchart of if - else
if…else statement.
The following code segment illustrates the working of if...else statement.
This statement is executed only when
score is 18 or more (Test expression
if (score >= 18)
returns True)
cout << "Passed";
This statement is executed only when
else
score is less than 18 (Test expression
cout << "Failed"; returns False)
164
7. Control Statements
Let us write a program to input the heights of two students and find the taller.
Program 7.2: To find the taller student by comparing their heights
#include <iostream>
using namespace std;
int main()
{
int ht1, ht2;
cout << "Enter heights of the two students: ";
cin >> ht1 >> ht2;
if (ht1 > ht2) //decision making based on condition
cout << "Student with height "<<ht1<<" is taller";
else
cout << "Student with height "<<ht2<<" is taller";
return 0:
}
When program 7.2 is executed, one of the output statements will be displayed. The
selection depends upon the relational expression ht1>ht2. The following are sample
outputs:
Output 1:
Enter heights of the two students: 170 165
Student with height 170 is taller
Output 2:
Enter heights of the two students: 160 171
Student with height 171 is taller
In the first output, we input 170 for ht1 and 165 for ht2. So, the test expression
(ht1>ht2) is evaluated to True and hence the statement block of if is selected and
executed. In the second output, we input 160 for ht1 and 171 for ht2. The test
expression, (ht1>ht2) is evaluated and found False. Hence the statement block of
else is selected and executed.
In if...else statement, either the code associated with if (statement block1) or
the code associated with else (statement block 2 ) is executed.
Let us see another program that uses an arithmetic expression as one of the operands in
the test expression. Program 7.3 uses this concept to check whether an input number is
even or odd.
165
Program 7.3: To check whether a given number is even or odd
#include <iostream>
using namespace std;
int main()
{
int num;
cout<<"\nEnter the number: ";
cin >> num;
if (num%2 == 0)
cout << "The given number is Even";
else
cout << "The given number is Odd";
return 0;
}
Some sample outputs of Program 7.3 are shown below:
Output 1:
Enter the number: 7
The given number is Odd
Output 2:
Enter the number: 10
The given number is Even
In this program, the expression (num%2) finds the remainder when num is divided by
2 and compares it with the value 0. If they are equal, the if block is executed, otherwise
the else block is executed.
1. Write a program to check whether a given number is a non-
zero integer number and is positive or negative.
2. Write a program to input enter a single character for sex and
print out the gender.
Let us do If the input character is ‘M’ display “Male". If the input is ‘F’
display “Female”
3. Write a program to input your age and check whether you are
eligible to cast vote (the eligibility is 18 years and above).
7.1.3 Nested if
In some situations there may arise the need to take a decision within if block. When
we write an if statement inside another if block, it is called nesting. Nested means
one inside another.
166
7. Control Statements
In this code fragment, if the value of score is greater than or equal to 60, the flow of
control enters the statement block of outer if. Then the test expression of the inner if
is evaluated (i.e. whether the value of age is greater than or equal to18). If it is evaluated
to True, the code displays the message, "You are selected for the
course!". Then the program continues to execute the statement following the outer
if statement. An if statement, inside another if statement is termed as a nested if
statement. The following is an expanded form of nested if.
if (test expression 1)
{ It will be executed if both the test
if (test expression 2) expressions are True.
statement 1;
else It will be executed if test
statement 2; expression 1 is True, but test
} expression 2 is False.
else
It will be executed if test
{
expression 1 is False. The test
body of else ; expression 2 is not evaluated.
}
The important point to remember about nested if is that an else statement always
refers to the nearest if statement within the same block. Let us discuss this case with
an example. Consider the following program segment:
cout<<"Enter your scores in Computer Science exam: ";
cin>>score;
if (score >= 18)
cout<<"You have passed";
if(score >= 54)
cout<<" with A+ grade !";
else
cout<<"\nYou have failed";
167
If we input the value 45 for score, the output will be as follows:
You have passed
You have failed
We know that this is logically not correct. Though the indentation of the code is proper,
that doesn't matter in execution. The second if statement will not be considered as
nested if, rather it is counted as an independent if with an else block. So, when
the first if statement is executed, the if block is selected for execution since the test
expression is evaluated to True. It causes the first line in the output. After that, while
considering the second if statement, the test expression is evaluated to False and
hence the second line in the output is obtained. So to get the correct output, the code
should be modified as follows:
cout<<"Enter your scores in Computer Science exam: ";
cin>>score;
if (score >= 18) Nesting is enforced by putting a
{ pair of braces
cout<<"You have passed";
if(score >= 54)
cout<<" with A+ grade !";
}
It is now associated with the outer if
else
cout<<"\nYou have failed";
If we input the same value 45 as in the case of previous example, the output will be as
follows:
You have passed
Program 7.4 uses nested if to find the largest among three given numbers. In this
program, if statement is used in both the if block and else block.
168
7. Control Statements
if (x > y)
{
if (x > z)
cout << "The largest number is: " << x;
else
cout << "The largest number is: " << z;
}
else
{
if (y > z)
cout << "The largest number is: " << y;
else
cout << "The largest number is: " << z;
}
return 0;
}
Check yourself
169
The general form of else if ladder is:
if (test expression 1)
statement block 1;
else if (test expression 2)
statement block 2;
else if (test expression 3)
statement block 3;
...............
else
statement block n;
At first, the test expression 1 is evaluated and if it is True, the statement
block 1 is executed and the control comes out of the ladder. That means, the rest of
the ladder is bypassed. If test expression 1 evaluates to False, then the test
expression 2 is evaluated and so on. If any one of the test expressions evaluates to
True, the corresponding statement block is executed and control comes out of the
ladder. If all the test expressions are evaluated to False, the statement block n
after the final else is executed. Observe the indentation provided in the syntax and
follow this style to use else if ladder.
Let us illustrate the working of the else if ladder by writing a program to find the
grade of a student in a subject when the score out of 100 is given. The grade is found
out by the criteria given in the following table:
Score Grade
80 or more A
From 60 To 79 B
From 40 To 59 C
From 30 To 39 D
Below 30 E
170
7. Control Statements
In program 7.5, initially the test expression score>=80 is evaluated. Since the input is
75 in Output 1, the test expression is evaluated to False, and the next test expression
score>=60 is evaluated. Here it is True, and hence "B Grade" is displayed and
the remaining part of the else if ladder is bypassed. But in the case of Output 2, all
the test expressions are evaluated to False, and so the final else block is executed
which makes "E Grade" as the output.
Let us write a program to check whether the given year is a leap year or not. The input
value should be checked to know whether it is century year (year divisible by 100). If
it is a century year, it becomes a leap year only if it is divisible by 400 also. If the input
value is not a century year, then we have to check whether it is divisible by 4. If it is
divisible, the given year is a leap year, otherwise it is not a leap year.
Program 7.6: To check whether the given year is leap year or not
#include <iostream>
using namespace std;
int main()
{
int year ;
cout << "Enter year (in 4-digits): ";
cin >> year;
171
if (year % 100 == 0)// Checks for century year
{ A century year is leap year
if (year % 400 == 0)
only if it is divisible by 400
cout << "Leap Year\n" ;
else
cout<< "Not a leap year\n" ;
}
else if (year % 4 == 0) Non - century year is leap
cout << "Leap Year\n" ; year only if it is divisible by 4
else
cout<< "Not a leap year\n" ;
}
Let us see some sample outputs of Program 7.6:
Output 1:
Enter year (in 4-digits): 2000
Leap Year
Output 2:
Enter year (in 4-digits): 2014
Not a leap Year
Output 3:
Enter year (in 4-digits): 2100
Not a leap Year
Output 4:
Enter year (in 4-digits): 2004
Leap Year
We write one more program to illustrate the use of else if ladder. Program 7.7
allows to input a number between 1 and 7 to denote the day of a week and displays the
name of the corresponding day. The input 1 will give you "Sunday" as output, 2 will give
"Monday" and so on. If the input is outside the range 1 to 7, the output will be "Wrong
input".
Program 7.7: To display the name of the day for a given day number
#include <iostream>
using namespace std;
int main()
{
int day;
cout << "Enter day number (1-7): ";
cin >> day;
if (day == 1)
cout<<"Sunday" ;
else if (day == 2)
172
7. Control Statements
cout<<"Monday" ;
else if (day == 3)
cout<<"Tuesday" ;
else if (day == 4)
cout<<"Wednesday" ;
else if (day == 5)
cout<<"Thursday" ;
else if (day == 6)
cout<<"Friday" ;
else if (day == 7)
cout<<"Saturday" ;
else
cout<<"Wrong input" ;
return 0;
}
Check yourself
173
The syntax of switch statement is given below:
switch (expression)
{
case constant_1 : statement block 1;
break;
case constant_2 : statement block 2;
break;
case constant_3 : statement block 3;
break;
:
:
case constant_n-1 : statement block n-1;
break;
default : statement block n;
}
In the syntax switch, case, break and default are keywords. The expression
is evaluated to get an integer or character constant and it is matched against the constants
specified in the case statements. When a match is found, the statement block associated
with that case is executed until the break statement or the end of switch statement
is reached. If no match is found, the statements in the default block get executed.
The default statement is optional and if it is missing, no action takes place when all
matches fail. The break statement, used inside switch, is one of the jump statements
in C++. When a break statement is encountered, the program control goes to the
statements following the switch statement.
Program 7.7 can be written using switch statement. It enhances the readability and
effectiveness of the code. Observe the modification in Program 7.8.
Program 7.8: To display the day of a week using switch statement
#include <iostream>
using namespace std;
int main()
{ int day;
cout << "Enter a number between 1 and 7: ";
cin >> day;
switch (day)
{
case 1: cout << "Sunday";
break;
case 2: cout << "Monday";
break;
case 3: cout << "Tuesday";
break;
174
7. Control Statements
175
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u': cout<<"Given character is a vowel";
break;
default : cout<<"Given character is not a vowel";
}
return 0;
}
176
7. Control Statements
That is the following code fragment may be used instead of else if ladder.
switch(score/10)
{
case 10 :
case 9 : case 8 : cout<< "A Grade"; break;
case 7 : case 6 : cout<< "B Grade"; break;
case 5 : case 4 : cout<< "C Grade"; break;
case 3 : cout<< "D Grade"; break;
default : cout<< "E Grade";
}
Let us have comparison between switch and else if ladder as indicated in table
7.1
switch statement else if ladder
• Permits multiple branching. • Permits multiple branching.
• Evaluates conditions with equality • Evaluate any relational or logical
operator only. expression.
• Case constant must be an integer or a • Condition may include range of values
character type value. and floating point constants.
• When no match is found, default • When no expression evaluates to True,
statement is executed. else block is executed.
• break statement is required for exit • Program control automatically goes out
from the switch statement. after the completion of a block.
• More efficient when the same variable • More flexible and versatile compared
or expression is compared against a set to switch.
of values for equality.
Table 7.1: Comparison between switch and else if ladder
7.1.6 The conditional operator ( ? : )
As we mentioned in Chapter 5, C++ has a ternary operator. It is the conditional operator
(?:) consisting of symbols ? and : (a question mark and a colon). It requires three
operands to operate upon. It can be used as an alternative to if...else statement.
Its general form is:
Test expression ? True_case code : False_case code;
The Test expression can be any relational or logical expression and True_case
code and False_case code can be constants, variables, expressions or statement.
177
The operation performed by this operator is shown below with the help of an if
statement.
if (Test expression)
{
True_case code;
}
else
{
False_case code;
}
The conditional operator works in the same way as if...else works. It evaluates
the Test expression and if it is True, the True_case code is executed. Otherwise,
False_case code is executed. Program 7.10 illustrates the working of conditional
operator.
Program 7.10: To find the larger number using conditional operator
#include <iostream>
using namespace std;
int main()
{
int n1, n2;
cout << "Enter two numbers: ";
cin>> n1 >> n2 ;
(n1>n2)? cout<<n1<<" is larger" : cout<<n2<<" is larger";
}
The last statement of the program may be called conditional statement as it uses
conditional operator. This statement may be replaced by the following code segment:
int big = (n1>n2) ? n1 : n2;
cout << big << " is larger";
If the test expression evaluates to True, the value of n1 will be assigned to big, otherwise
that of n2. Here conditional operator is used to construct a conditional expression. The
value returned by this expression will be assigned to big.
Check yourself
178
7. Control Statements
179
conditions, a variable like the counter will be used to construct a loop. This variable is
generally known as loop control variable because it actually controls the execution of
the loop. In Chapter 3, we discussed four elements of a loop. Let us refresh them:
1. Initialisation: Before entering a loop, its control variable must be initialised.
During initialisation, the loop control variable gets its first value. The initialisation
statement is executed only once, at the beginning of the loop.
2. Test expression: It is a relational or logical expression whose value is either True
or False. It decides whether the loop-body will be executed or not. If the test
expression evaluates to True, the loop-body gets executed, otherwise it will not
be executed.
3. Update statement: The update statement modifies the loop control variable by
changing its value. The update statement is executed before the next iteration.
4. Body of the loop: The statements that need to be executed repeatedly constitute
the body of the loop. It may be a simple statement or a compound statement.
We learnt in Chapter 3 that loops are generally classified into entry-controlled loops
and exit-controlled loops. C++ provides three loop statements: while loop, for
loop and do...while loop. Let us discuss the working of each one in detail.
180
7. Control Statements
The initialisation of the loop control variable takes place first. Then the test
expression is evaluated. If it returns True the body of the loop is executed. That is
why while loop is called an entry controlled loop. Along with the loop body, the
loop control variable is updated. After completing the execution of the loop body, test
expression is again evaluated. The process is continued as long as the condition is True.
Now, let us consider a code segment to illustrate the execution of while loop.
int k=1; Initialization before loop begins
while(k<=3 ) Test expression
{
cout << k << ‘\t’; Body of loop
++k;
} Updation inside the loop body
In this code segment, the value 1 is assigned to the variable k (loop control variable) at
first. Then the test expression k<=3 is evaluated. Since it is True, the body of the loop
is executed. That is the value of k is printed as 1 on the screen. After that the update
statement ++k is executed and the value of k becomes 2. The condition k<=3 is
checked again and found to be True. Program control enters the body of the loop and
prints the value of k as 2 on the screen. Again the update statement is executed and the
value of k is changed to 3. Since the condition is still True, body is executed and 3 is
displayed on the screen. The value of k is again updated to 4 and now the test expression
is evaluated to be False. The control comes out of the loop and executes the next
statement after the while loop. In short, the output of the code will be:
1 2 3
Imagine what will happen if the initial value of k is 5? The test expression is evaluated to
False in the first evaluation and the loop body will not be executed. This clearly shows
that while loop controls the entry into the body of the loop.
Let us see a program that uses while loop to print the first 10 natural numbers.
Program 7.11: To print the first 10 natural numbers
#include <iostream>
using namespace std;
int main()
{ Initialisation of loop variable
int n = 1;
while(n <= 10) Test expression
{
cout << n << " "; Body of loop
++n;
}
Updating loop variable
}
181
The output of Program 7.11 will be as follows:
1 2 3 4 5 6 7 8 9 10
Program 7.12 uses while loop to find the sum of even numbers upto 20. This program
shows that the loop control variable can be updated using any operation.
Program 7.12: To find the sum of even numbers upto 20
#include <iostream>
using namespace std;
int main()
{
int i, sum = 0;
i = 2;
while( i<= 20)
{
sum = sum + i; Updating of loop control variable by
i = i + 2; adding 2 to the current value
}
cout<<"\nsum of even numbers up to 20 is: "<<sum;
return 0;
}
Let us do Modify Program 7.12 to find the sum of the first N natural
numbers.
If we put a semi colon (;) after the test expression of while statement,
there will not be any syntax error. But the statements within the
following pair of braces will not be considered as loop body. The
worst situation is that, if the test expression is evaluated to be True,
neither the code after the while loop will be executed nor the program will be
terminated. It is a case of infinite loop.
182
7. Control Statements
initialisation takes place and then the test expression is evaluated. If its
result is True, body-of-the-loop is executed, otherwise the program control goes
out of the for loop. After the execution of the loop body, update expression is
executed and again test expression is evaluated. These three steps (test, body, update)
are continued until the test expression is evaluated to False.
The loop segment used in Program 7.11 can be replaced with a for loop as follows:
for (n=1; n<=10; ++n)
cout << n << " ";
The steps 1 and 2 in the execution sequence of the for loop just
mentioned before are given below. Write down the remaining
steps.
Let us do Step 1: N =1, Condition is True, 1 is displayed, N becomes 2
Step 2: Condition is True, 2 is displayed, N becomes 3
Step 3: ……………
This code is executed in the same way as in the case of while loop.
Let us write a program using for loop to find the factorial of a number. Factorial of a
number, say N, represented by N! is the product of the first N natural numbers. For
example, factorial of 5 (5!) is calculated by 1 × 2 × 3 × 4 × 5 = 120.
183
Program 7.13: To find the factorial of a number using for loop
#include <iostream>
using namespace std;
int main()
{
int n, i, fact=1;
cout<<"Enter number to find the factorial: ";
cin>>n; Initialisation; Test Expression; Updation
for (i=1; i<=n; ++i)
fact = fact * i ; Loop body
cout << "Factorial of " << n << " is " << fact;
}
The following is a sample output of program 7.13
Enter number to find the factorial: 6
Factorial of 6 is 720
Another program is given below which gives the class average of scores obtained in
Computer Applications. Program 7.14 accepts the value for n as the number of students,
then reads the score of each student and prints the average score.
Program 7.14: To find the average score of n students
#include <iostream>
using namespace std;
int main()
{
int i, sum, score, n;
float avg; Initialisation contains
cout << "How many students? "; two expressions
cin >> n ;
for(i=1, sum=0; i<=n; ++i)
{
cout << "Enter the score of student " << i <<": ";
cin >> score;
sum = sum + score; Explicit type conversion
}
avg = (float)sum / n;
cout << "Class Average is: " << avg;
}
The following is a sample output of Program 7.14 for 5 students
How many students? 5
Enter the score of student 1: 45
Enter the score of student 2: 50
Enter the score of student 3: 52
Enter the score of student 4: 34
Enter the score of student 5: 55
Class Average is: 47.2
184
7. Control Statements
185
In Program 7.14, the initialisation contains two expressions i=1 and sum=0 separated
by comma (,). The initialisation part may contain more than one expression, but they
should be separated by comma. Both the variables i and sum get their first values 1
and 0 respectively. Then, the test expression i<=n is evaluated to be True and body of
the loop is executed. After the execution of the body of the loop the update expression
++i is executed. Again the test expression i<=n is evaluated, and body of the loop is
executed since the condition is True. This process continues till the test expression
returns False. It has occurred in the sample output when the value of i becomes 6.
186
7. Control Statements
At first, the value 1 is assigned to the variable k. Then body of the loop is executed and
the value of k is printed as 1. After that the k is incremented by 1 (now k=2). Then it
checks the condition k<=3. Since it is found True the body of the loop is executed to
print the value of k, i.e. 2 on the screen. Again the updation process is carried out,
which makes value of k as 3 and the condition k<=3 is checked again. As it is True,
the body of the loop is executed to print the value 3. The variable k is again updated to
4 and now the condition is evaluated to be False. It causes the program control to
come out of the loop and executes the next statement after the loop body. Thus the
output of the code will be:
1 2 3
Now let us see how this loop differs from the other two. Imagine that the initial value of
k is 5. What will happen? The body of the loop is executed and the value of k will be
printed on the screen as 5. After that the variable k will be updated by incrementing it
by 1 and k becomes 6. On checking the condition k<=3, the test expression is evaluated
to False and the control comes out of the loop. This clearly shows that in do...while
loop there is no restriction to enter the loop body for the first time. So if we want the
body to be executed based on the True value of the condition, use while or for
loops.
Let us see an interactive program in the sense that some part of the code will be executed
on user's choice. The simplest form of such programs provides facility to accept user's
response for executing a code segment in the program repeatedly. Program 7.15
illustrates the use of do...while loop to write an interactive program to find the area
of rectangles by accepting the length and breadth of each rectangle from the user.
187
Program 7.15: To find the area of rectangles
#include <iostream>
using namespace std;
int main()
{
float length, breadth, area;
char ch;
do
{
cout << "Enter length and breadth: ";
cin >> length >> breadth;
area = length * breadth;
cout << "Area = " << area;
cout << "Any more rectangle (Y/N)? ";
cin >> ch;
} while (ch == 'Y' || ch == 'y');
return 0;
}
A sample output of Program 7.15 is given below:
Enter length and breadth: 3.5 7 User input
Area = 24.5
Any more rectangle (Y/N)? Y User input
Enter length and breadth: 6 4.5
Area = 27
Any more rectangle (Y/N)? N User input
We have discussed all the three looping statements of C++. Table 7.2 shows a
comparison between these statements.
188
7. Control Statements
Let us sum up
The statements providing facilities for taking decisions or for performing repetitive
actions in a program are known as control statements. The control statements are
the backbones of a computer program. In this chapter we covered the different
types of control statements such as selection statements - (if, if…else, if…else
if, switch) and iteration statements or loop statements (for, while, do…while).
All these control statements will help us in writing complex C++ programs. These
statements are essential for varuiys programming operations to be performmed.
Learning outcomes
After the completion of this chapter the learner will be able to
• use control statements in C++ for problem solving.
• identify the situation where control statements are used in a program.
• use correct control statements suitable for the situations.
• categorise different types of control statements.
• write C++ programs using control statements.
Lab activity
1. Write a program to input a digit and print it in words.
2. Write a program to print first 'n' odd numbers.
3. Write a program to print the sum of squares of first n odd numbers.
4. Write a program to print every integer between 1 and n which are exactly divisible
by m.
Sample questions
Very short answer type
1. Write the significance of break statement in switch statement. What is the effect of
absence of break in a switch statement?
2. What will be the output of the following code fragment?
for(i=1;i<=10;++i) ;
cout<<i+5;
3. Write a program using for loop that will print the numbers between 1000 and
2000 which are divisible by 132.
189
4. Rewrite the following statement using while and do...while loops.
for (i=1; i<=10; i++) cout<<i;
5. How many times the following loop will execute?
int s=0, i=0;
while(i++<5)
s+=i;
Short answer type
1. Consider two program fragments given below.
// version 1 //version 2
cin>>mark; cin>>mark;
if (mark > = 90) if (mark>=90)
cout<<" A+"; cout<<" A+";
if (mark > = 80 && mark <90) else if (mark>=80 && mark <90)
cout<<" A"; cout<<" A";
if (mark > = 70 && mark <80) else if (mark>=70 && mark <80)
cout<<" B+"; cout<<" B+";
if (mark > = 60 && mark <70) else if (mark>=60 && mark <70)
cout<<" B"; cout<<" B";
discuss the advantages of version 2 over version 1.
2. Briefly explain the working of a for loop along with its syntax. Give an example of
for loop to support your answer.
3. Compare and discuss the suitability of three loops in different situations.
4. What is wrong with the following while statement if the value of z = 3.
while(z>=0)
sum+=z;
5. Consider the following if else if statement. Rewrite it with switch
command.
if (a==1)
cout << “One”;
else if (a==0)
cout << “Zero”;
else
cout << “Not a binary digit”;
6. Write the importance of a loop control variable. Briefly explain the different parts
of a loop.
Long answer type
1. Explain different types of decision statements in C++.
2. Explain different types of iteration statements available in C++ with syntax and
examples.
190
8
192
8. Computer Networks
193
Fig. 8.1 : Data communication system
194
8. Computer Networks
Unshielded Twisted Pair (UTP) cable : As its name suggests, the individual pairs in
UTP cables are not shielded. Figure 8.2 shows the components of a UTP cable.
b. Coaxial cable
A coaxial cable consists of an inner conductor surrounded by a tubular insulating layer
which is further covered by a tubular conducting shield. It has an outer insulation to
195
protect the cable too. Figure 8.4 shows the
construction of a coaxial cable.
Characteristics of coaxial cable
• Carries data to longer distances (185 m -
500 m) at a stretch.
• High bandwidth.
• Less electromagnetic interference due to the Fig. 8.4 : Coaxial Cable
outer shield.
• Thicker than twisted pair.
• Less flexible than twisted pair.
• Difficult to install than twisted pair cable.
196
8. Computer Networks
197
Characteristics of radio wave transmission
• Waves are transmitted in all directions, therefore transmitting and receiving antennas
need not be aligned face to face.
• Relatively inexpensive than wired media.
• Can penetrate through most objects.
• Transmission can be affected by motors or other electrical equipment.
• Less secure mode of transmission.
• Permissions from authorities concerned are required for the use of radio wave
transmission.
198
8. Computer Networks
199
Characteristics of bluetooth transmission
• Line of sight between communicating devices is not required.
• Bluetooth can connect upto eight devices simultaneously.
• Slow data transfer rate (upto 1 Mbps).
b. Wi-Fi
Wi-Fi network makes use of radio waves to transmit information across a network like
cell phones, televisions and radios. The radio waves used in Wi-Fi ranges from a
frequency of 2.4 GHz to 5 GHz. Communication across a wireless network is two-
way radio communication. The wireless adapter in a computer translates data into
radio signal and transmits it using an antenna. A wireless router receives the signal and
decodes it. Once decoded, the data will be sent to the Internet or network through a
wired Ethernet /wireless connection. Similarly, the data received from the Internet/
network will also pass through the router and coded into radio signals that will be
received by the wireless adapter in a computer as indicated in Figure 8.12. Nowadays,
this technology is widely used to share Internet connection with laptops or desktops.
200
8. Computer Networks
201
to the earth is called downlink. There are multiple micro wave frequency bands which
are used for satellites links. Frequency used for uplink varies from 1.6 GHz to 30.0
GHz and that for downlink varies from 1.5 GHz to 20.0 GHz. Downlink frequency is
always lower than the uplink frequency.
The satellite system is very expensive, but its coverage area is very large. Communication
satellites are normally owned by governments or by government approved organisations
of various countries.
Characteristics of transmission using satellite link
• Satellites cover a large area of the earth.
• This system is expensive.
• Requires legal permission and authorisation.
Check yourself
202
8. Computer Networks
Fig. 8.15 (a) : NIC card Fig. 8.15 (b) : Wireless NIC card
Figure 8.15 (a, b) shows the NIC card and wireless NIC card. Some NIC cards have
wired connections (Ethernet), while others are wireless (Wi-Fi). Ethernet NICs include
jacks for network cables, while Wi-Fi NICs contain built-in transmitters / receivers
(transceivers) and an antenna. NICs can transfer data at a speed of 1 Gbps.
8.4.2 Hub
A hub is a device used in a wired network to connect computers/devices of the same
network. It is a small, simple, passive and inexpensive device (refer Figure 8.16).
Computers/devices are connected to ports of the hub using Ethernet cable. When NIC
of one computer sends data packets to hub, the hub transmits the packets to all other
computers connected to it. Each computer is responsible for determining its data packets.
The computer for which the data packets are intended accepts it. Other computers on
the network discards these data packets. The main
disadvantage of hub is that it increases the network
traffic and reduces the effective bandwidth, as it
transmits data packets to all devices connected to it.
Fig. 8.16 : Hub
8.4.3 Switch
A switch is an intelligent device that connects several computers to form a network. It
is a higher performance alternative to a hub. It looks exactly like a hub. Switches are
capable of determining the destination and redirect the data only to the intended node.
Switch performs this by storing the addresses of all the devices connected to it in a
table. When a data packet is send by one device, the switch reads the destination
address on the packet and transmits the packet to the destination device with the help
of the table. A switch performs better than a hub on busy networks, since it generates
less network traffic in delivering messages.
203
8.4.4 Repeater
A repeater is a device that regenerates incoming electrical, wireless
or optical signals through a communication medium (refer Figure
8.17). Data transmissions through wired or wireless medium can
travel only a limited distance as the quality of the signal degrades
due to noise. Repeater receives incoming data signals, amplifies
the signals to their original strength and retransmits them to the
Fig. 8.17 : Wireless
destination. repeater
8.4.5 Bridge
A bridge is a device used to segmentise a network. An existing network can be split into
different segments and can be interconnected using a bridge. This reduces the amount
of traffic on a network. When a data packet reaches the bridge, it inspects the incoming
packet’s address and finds out to which side of the bridge it is addressed (to nodes on
the same side or the other side). Only those packets addressed to the nodes on the
other side, will be allowed to pass the bridge. Others will be discarded. The packet that
passes the bridge will be broadcast to all nodes on the other side and is only accepted
by the intended destination node. Figure 8.18 shows the function of a bridge.
204
8. Computer Networks
use algorithms to find the best path for packets to reach the destination. Figure 8.19
shows the role of a router.
205
8. Computer Networks
Check yourself
207
the signal reaches the end of the bus, the terminator absorbs the signal and removes it
from the bus. Now the bus is free to carry another signal. This prevents the reflection of
a signal back on the cable and hence eliminates the chances of signal interference. The
process of transmitting data from one node to all other nodes is called broadcasting.
Characteristics of bus topology
• Easy to install.
• Requires less cable length and hence it is cost effective.
• Failure of a node does not affect the network.
• Failure of cable (bus) or terminator leads to a break down of the entire network.
• Fault diagnosis is difficult.
• Only one node can transmit data at a time.
8.6.2 Star topology
In star topology each node is directly connected
to a hub/switch as shown in Figure 8.24. If any
node has to send some information to any other
node, it sends the signal to the hub/switch. This
signal is then broadcasted (in case of a hub) to
all the nodes but is accepted only by the intended
node. In the case of a switch, the signal is sent
only to the intended node.
Characteristics of star topology Fig. 8.24 : Star topology
208
8. Computer Networks
210
8. Computer Networks
typically owned and operated by a single entity such as a government body or a large
corporation (refer Figure 8.29).
211
Parameter PAN LAN MAN WAN
Area covered Small area A few meters to A city and its Entire country,
(Up to 10 m radius) a few Kilometers vicinity (Up to continent,
(Up to 10 Km radius) (100 Km radius) or globe
Transmission High speed High speed Moderate Low speed
speed speed
Networking cost Negligible Inexpensive Moderately Expensive
expensive
Table 8.1 : Characteristics summary of PAN, LAN, MAN, WAN
8.8 Logical classification of networks
This classification is based on the role of computers in the network and division falls
into two categories: peer-to-peer and client-server.
8.8.1 Peer-to-Peer
A peer-to-peer network has no dedicated servers. Here a number of computers are
connected together for the purpose of sharing information or devices. All the computers
are considered equal. Any computer can act as a client or as a server at any instance.
This network is ideal for small networks where there is no need for dedicated servers,
like home network or small business establishments or shops.
8.8.2 Client-Server
The client-server concept is the driving force behind most of the networks. It is similar
to going to a restaurant, reading the menu, calling the waiter (server) and then ordering
one’s preference from the menu. If the ordered item is available in the restaurant at that
time, it is 'served' to whom the order was placed (client), else the request is refused.
In a network, the client-server architecture consists of high-end computer (called server)
serving lower configuration machines called clients. A server provides clients with specific
services (responses) upon client’s request. The services include sharing of data, software
and hardware resources. Figure 8.31 shows the
general client-server architecture.
Client-server architecture is an example for centralised
software management. When software is loaded on
the server and shared among the clients, changes made
to the software in the server will reflect in the clients
also. So there is no need to spend time and energy
for installing updates and tracking files independently
on the clients. Fig. 8.31 : Client - Server
212
8. Computer Networks
Check yourself
1. In bus topology, when the signal reaches the end of the bus, ______absorbs
the signal and removes it from the bus.
2. In which topology is every node connected to other nodes?
3. Categorise and classify the different types of networks given below.
ATM network, Cable television network, Network within the school,
Network at home using bluetooth,Telephone network, Railway network.
4. What is PAN?
213
manufacturer. This address is known as the MAC address. It means that a machine
with an NIC can be identified uniquely through the MAC address of its NIC. MAC
address of an NIC is permanent and never changes.
MAC addresses are 12-digit hexadecimal (or 48 bit Binary) numbers. By convention,
MAC addresses are usually written in one of the following two formats:
MM : MM : MM : SS : SS : SS or MM – MM – MM – SS – SS – SS
The first half (MM:MM:MM) of a MAC address contains the ID number of the adapter
manufacturer. The second half (SS:SS:SS) of a MAC address represents the serial
number assigned to the adapter (NIC) by its manufacturer. For example, in the following
MAC address,
00:A0:C9 : 14:C8:35
Fig: 8.32 : MAC Id
the prefix 00:A0:C9 indicates that the manufacturer is Intel Corporation. The last three
numbers 14:C8:35 are given by the manufacturer (Intel in this example) to this NIC.
8.9.2 Internet Protocol (IP) Address
An IP address is a unique 4 part numeric address assigned to each node on a network,
for their unique identification. IP address is assigned to each machine by the network
administrator or the Internet Service Provider. An IP address is a group of four bytes
(or 32 bits) each of which can be a number from 0 to 255.
To make it easier for us to remember, IP addresses are normally expressed in decimal
format as a “dotted decimal number” as indicated in Figure 8.33.
On a network, the IP address of a
machine is used to identify it. IP protocol
identifies a machine with its IP address
to route the packets.
There are two versions of IP addresses:
version 4 (IPv4) and version 6 (IPv6). Fig. 8.33 : IP address
IPv4 uses 32 bits and IPv6 uses 128
bits for an IP address. Using IPv4 only 232 (approximately 4 billion) distinct devices can
be addressed.
As the number of devices which need to be networked (mobile phones, home appliances,
personal communication devices, etc.) is increasing at a very fast pace, IPv4 addresses
are being exhausted. To address this problem IPv6 was developed and it is now being
deployed. Using IPv6, 2128 (approximately 4 billion × 4 billion × 4 billion × 4 billion)
distinct devices can be addressed.
214
8. Computer Networks
TCP/IP
TCP/IP, Transmission Control Protocol/Internet Protocol, is a suite of communications
protocols used to interconnect network devices on the local networks and the Internet.
TCP/IP defines rules for how electronic devices (like computers) should be connected
to the Internet and how data should be transmitted between them.
When data is to be sent from one computer to another over Internet, it is first broken
into smaller packets by TCP and then sent. When these packets are received by the
receiving computer, TCP checks packets for errors. If errors are found, TCP submits
requests for retransmission; else packets are assembled into the original message
according to the rules specified in TCP protocol. Figure 8.34 shows the steps involved
215
in the working of TCP/IP protocol. Delivery of each of these packets to the right
destinations is done by Internet protocol (IP). Even though different packets of the
same message may be routed differently, they will reach the same destination and get
reassembled there. HTTP, FTP and DNS are three sub protocols of TCP/IP protocol
suite.
HTTP
HTTP stands for Hypertext Transfer Protocol. It is a standard protocol for transferring
requests from client-side and to receive responses from the server-side. The HTTP
client (browser) sends a HTTP request to the HTTP server (web server) and server
responds with a HTTP response. This pair of request and response is called an HTTP
session (refer Figure 8.35).
The response from the server can be
static such as a file already stored on the
server, or dynamic, such as, the result of
executing a piece of code by the server
as per the request from the client. Fig. 8.35 : An HTTP session
216
8. Computer Networks
addresses do not change (statically assigned). If one DNS server does not know how
to translate a particular domain name, it asks another one, and so on, until the correct
IP address is returned.
Find and prepare notes on five protocols other than TCP/IP, HTTP,
FTP, DNS.
Let us do
217
developed which assigns names to computers (web servers) and maintains a database
of these names and their corresponding IP addresses. These names are called domain
names.Examples of some domain names are dhsekerala.gov.in, keralaresults.nic.in,
google.com, gmail.com, etc.
A domain name usually has more than one part: top level domain name or primary
domain name and sub-domain name(s). For example, in the domain name above, ‘in’ is
the primary domain name; ‘gov’ is the sub-domain of in and ‘dhsekerala’ is the sub-
domain of ‘gov’. There are only a limited number of top level domains and these are
divided into two categories: Generic Domain Names and Country-Specific Domain
Names. Examples of generic and country specific domain names are given in Table 8.2.
Generic Domain Names Country Specific Domain Names
·com Commercial business ·in India
·edu Educational institutions ·au Australia
·gov Government agencies ·ca Canada
·mil Military ·ch China
·net Network organizations .jp Japan
·org Organizations (nonprofit) .us United States of America
Table. 8.2 : Generic and country specific domain names
c. File name
It is the file to be opened. In the example given in Figure 8.35, 'index.html' is the file that
is to be accessed from the web server specified by the domain name.
Make a list of valid URL, containing two examples for each generic
domain name and country specific domain name. Also note down
the file name opened by default (for file look at the URL in address
Let us do bar after the site is opened).
Let us sum up
We learned about computer networks, the essential technology of the century, in this
chapter. Importance of network was discussed by highlighting the various advantages
it provides. We discussed the various communication media and their pros and cons.
The devices used at various situations while forming a network was also discussed.
Before discussing the types of network, we learned the different ways a network
could be formed by discussing various topologies. We then discussed protocol and
how TCP/IP send/receive data across the network. Methods to uniquely identify a
node in the network were introduced and finally we concluded discussing URL.
218
8. Computer Networks
Learning outcomes
After the completion of this chapter the learner will be able to
• identify and choose a communication medium.
• compare different types of network.
• explain the logical classification of networks.
• identify how data is send across networks.
• design small networks.
• explain how a node is identified in a network.
• identify the various parts of a URL.
Sample questions
219
11. An International School is planning to connect all computers, spread over distance
of 45 meters. Suggest an economical cable type having high-speed data transfer,
which can be used to connect these computers.
12. Suppose that you are the administrator of network lab in one Institution. Your
manager directed you to replace 10 Mbps switch by 10 Mbps Ethernet hub for
better service. Will you agree with this decision? Justify your answer.
13. You need to transfer a biodata file stored in your computer to your friend’s computer
that is 10 kms away using telephone network
a. Name the device used for this at both ends.
b. Explain how the file is send and received inside the device, once a connection
between two computers is established.
14. When is a repeater used in a computer network?
15. Compare infrared and Bluetooth transmission.
16. Identify and explain the device used for connecting a computer to a telephone
network.
17. Briefly explain LAN topologies.
18. Briefly describe TCP/IP protocol.
19. What is a MAC address? What is the difference between a MAC address and an
IP address?
Long answer type
1. How are computer networks classified, based on size?
2. Compare different LAN topologies.
3. Explain various types of guided communication channels.
4. Compare different unguided media.
5. Define the term protocol. Briefly describe any two communication protocols.
6. Briefly describe the various communication devices used in computer networks.
7. Which is/are communication channel(s) suitable in each of the following situations?
a. Setting up a LAN.
b. Transfer of data from a laptop to a mobile phone.
c. Transfer of data from one mobile phone to another.
d. Creating a remote control that can control multiple devices in a home.
e. Very fast communication between two offices in two different countries.
f. Communication in a hilly area.
g. Communication within a city and its vicinity where cost of cabling is too high.
220
9
222
9. Internet
etc. The Internet is an interconnected system of computer networks that serves the
users all over the world.
An intranet is considered as a private computer network similar to Internet that uses
TCP/IP protocol to share information, software or services within an organisation. An
intranet can host websites, provide e-mail service, file transfer and other services
available on Internet.
When an intranet is made accessible to some computers that are not part of a company’s
private network it is called an extranet. A network that allows vendors and business
partners to access a company resource can be considered as an example of extranet.
9.2 Connecting the computer to the Internet
As we know today, the Internet has become very popular and almost all organisations
and people around the world are joining it. Earlier, people used the Internet to search
for information and check e-mails only, but today it is used to book train tickets, recharge
mobile phones, Internet banking and a lot more. Therefore almost all of us require an
Internet connection in our computers or mobile devices.
The following are the hardware and software requirements for connecting a computer
to the Internet:
• A computer with Network Interface Card (wired/wireless) facility and an operat-
ing system that supports TCP/IP protocol
• Modem
• Telephone connection
• An Internet account given by an Internet Service Provider (ISP)
• Software like browser, client application for e-mail, chat, etc.
Nowadays desktop computers or laptops are not the only devices that we use to
connect to the Internet. People have also started using tablets, smart phones, etc. to
browse the Internet. Some of these devices come with built-in modems, whereas others
use a wireless dongle or wireless connection from a modem to access the Internet.
9.3 Types of connectivity
Today most websites use images and multimedia content to make webpages more
attractive. Several websites provide videos that can be downloaded or viewed on the
Internet. Instead of distributing software in CDs or other storage media, it is now
distributed online by various vendors. The latest trend shows that software like word
processors, spreadsheets, antivirus, etc. are used online on a rental basis instead of
223
installing it on each computer. In all these cases, a large volume of data is transferred
online. Therefore the speed or data transfer rate of the Internet is an important aspect.
Data transfer rate is the average number of bits transferred between devices in unit
time.
1 kbps = 1000 bits per second
1 Mbps = 1000 kbps
1 Gbps = 1000 Mbps
Difference between unit symbols b and B
b stands for bit
B stands for Byte
Difference between unit symbols k and K
k = 1000 = 103
K = 1024 = 210
Here ‘k’ is a decimal unit and ‘K’ is a binary unit of measurement. But for Mega,
Giga and Tera, both decimal and binary units use ‘M’, ‘G’ and ‘T’ as symbols
respectively. They are differentiated from the context in which they are
used.
Note that data transfer rate is measured in decimal units and memory is
measured in binary.
The main factor that decides Internet access speed is the type of connectivity we choose
to link to the Internet. Internet connectivity is classified based on the speed of the
connection and the technology used. They can be broadly classified as dial-up
connectivity, wired broadband connectivity and wireless broadband connectivity. The
data transfer rates of each type of connectivity may vary as techonology advances.
9.3.1 Dial-up connectivity
A dial-up connection uses the conventional telephone line and a dial-up modem to dial
and connect to the server at the Internet Service Provider (ISP). Figure 9.2 shows the
dial-up connectivity system. As the connection is made by dialing, it takes time to connect
to the server at the ISP. This connection commonly uses a 56 kbps modem that can
transmit data up to a maximum speed of 56 kbps. This slow connection is comparatively
less costly when compared to other types of connections. Another disadvantage is that
a dial-up connection requires exclusive use of the telephone line, i.e., while accessing
Internet, we cannot make or receive telephone calls (voice calls). Nowadays, broadband
connections that have a higher speed are replacing dial-up connections.
224
9. Internet
Computer
Internet Service
Provider
Telephone Modem
Modem lines
Fig. 9.2 : Dial-up connectivity
9.3.2 Wired broadband connectivity
The term broadband refers to a broad range of technologies
that helps us to connect to the Internet at a higher data rate
(speed). Wired broadband connections are ‘always on’
connections that do not need to be dialled and connected. Fig. 9.3 : Broadband modem
Broadband connections use a broadband modem (refer Figure 9.3) and allow us to
use the telephone even while using the Internet. Table 9.1 shows the comparison between
dial-up and wired broadband connections.
Dial-up connection Wired broadband connection
• Slow connection, speed upto 56 kbps • High speed connection,
speed usually higher than 256 kbps
• Requires dialing to connect to ISP • Always on connection
• Uses telephone line exclusively • Simultaneous use of voice and Internet
• Uses dial-up modem • Uses broadband modem
Table 9.1 : Comparison between dial-up and wired broadband connections
Popular broadband technologies are Integrated Services Digital Network (ISDN), Cable
Internet, Digital Subscriber Line (DSL), Leased Lines and Fiber to the Home (FTTH).
a. Integrated Services Digital Network (ISDN)
ISDN is a broadband service capable of transporting voice and digital data. Most
ISDN lines offered by telephone companies give users two lines. The users can use one
line for voice and the other for data, or they can use both lines for data. ISDN lines are
capable of offering data transfer rates upto 2 Mbps.
b. Cable Internet
Cable Internet access provides Internet access using coaxial cables laid for television
signal transmission to our homes. The service provider uses a cable modem at our
225
home to connect our computer to cable network. Cable TV systems are designed to
carry large bandwidth and therefore cable Internet can provide speeds between 1
Mbps to 10 Mbps.
c. Digital Subscriber Line (DSL)
DSL is another broadband service that provides connection to the Internet through
standard telephone lines. DSL allows the user to use copper telephone lines for both
Internet communication and for making voice calls simultaneously. It is composed of
several subcategories, the most common being Asymmetric Digital Subscriber Line
(ADSL). ADSL is a communication technology that allows faster flow of information
over a telephone line. The down stream speed of ADSL services typically ranges from
256 kbps to 24 Mbps. This connection requires an ADSL modem at our homes/offices.
ADSL is the most popular broadband service available in India.
d. Leased Line
Leased lines are dedicated lines used to provide Internet facility to ISPs, business, and
other large enterprises. An Internet leased line is a premium Internet connection that
provides speed in the range from 2 Mbps to 100 Mbps and is comparatively costly.
This is why leased lines are used only for connecting large campus of organisations like
educational institutions to Internet.
e. Fibre To The Home (FTTH)
Fibre to the Home (FTTH) uses optical fibers for data transmission. Optical fibres are
laid from the ISP to our homes. FTTH technology has been accepted worldwide to
implement high speed Internet to the home. Since optical fibres are known to have high
bandwidth and low error rates, they provide very high speed connectivity. A Network
Termination Unit (NTU) is installed in our homes, which is connected to our computer
through an FTTH modem.
9.3.3 Wireless broadband connectivity
Wireless broadband connectivity provides almost the
same speed as that of a wired broadband connection.
The popular wireless broadband accesses are Mobile
Broadband, Wi-MAX, Satellite Broadband and Wi-
Fi. Some of the wireless modems available for use to
connect to Internet are shown in Figure 9.4. Fig. 9.4 : Wireless broadband
modems
a. Mobile broadband
Mobile broadband is wireless Internet access using mobile phone, USB wireless modem,
tablet or other mobile devices. The modem is built into mobile phones, tablets, USB
226
9. Internet
dongles, etc. Mobile broadband offers the freedom to allow the user to access the
Internet from anywhere on the move. This technology uses the cellular network of
mobile phones for data transmission. The mobile technology for data transmission has
been changing from 2nd Generation (2G) through 3rd Generation (3G) to the current 4th
Generation (4G). The speed of data transmission increases with the progression of
generations of mobile technology.
b. Wi-MAX
In the previous chapter we learned that Worldwide Interoperability for Microwave
Access (Wi-MAX) is used as an alternative for wired broadband. Wi-MAX offers a
Metropolitan Area Network which can provide wireless Internet upto a distance of 50
Km. Connectivity is provided using devices like Wi-MAX handsets, USB dongles,
devices embedded in laptops, etc. that have a Wi-MAX modem integrated in it. This
technology provides a maximum connection speed of upto 70 Mbps.
c. Satellite broadband
Satellite broadband technology is a method by which Internet connectivity is provided
through a satellite. A Very Small Aperture Terminal (VSAT) dish antenna and a
transceiver (transmitter and receiver) are required at the user’s location. A modem at
the user’s end links the user’s computer with the transceiver. Download speed is upto
1 Gbps for this technology. It is among the most expensive forms of broadband Internet
access. They are used by banks, stock exchanges, governments, etc. and also for
Internet access in remote areas.
9.3.4 Internet access sharing methods
An Internet connection can be shared among several computers using a LAN,
Wi-Fi network or Li-Fi network.
a. Using LAN
The Internet connected to a computer in a Local Area Network (LAN) can be shared
among other computers in the network. This can be done either using features available
in the operating system or using any proxy server software available in the market.
Sharing can also be done by connecting computers directly to the router using a cable.
b. Using Wi-Fi network
We have heard of Wi-Fi campuses in large educational institutions, coffee shops,
shopping malls, hotels, etc. We also know that some of the broadband modems at our
homes and schools offer Wi-Fi Internet access.Wi-Fi is a popular short distance data
transmission technology that is used for network access, mostly Internet. Wi-Fi locations
227
receive Internet connection through any one of the above
mentioned wired or wireless broadband access methods,
as discussed in the previous section.They provide us
Internet connectivity through a Wi-Fi router or a wireless
network access point. Such an access point, popularly
called hotspot, has a range of about 100 meters indoors
Fig. 9.5 : Wi-Fi network and a greater range outdoors. We access Internet in our
Wi-Fi enabled devices like laptops, tablets, mobile
phones, etc. through these hotspots. A drawback of Wi-Fi is that it is less secure than
wired connections.
c. Using Li-Fi network
Li-Fi (Light Fidelity) is a fast optical version of Wi-Fi, which uses visible light for data
transmission. The main component of this communication is a bright LED (Light Emitting
Diode) lamp that can transmit data and a photo diode that serves as the receiver. LEDs
can be switched on and off to generate a binary string of 1s and 0s. The flickering of this
LED is so fast that the human eye cannot detect it. A data rate of over 100 Mbps is
possible using this technique as light offers very high bandwidth. Another advantage is
that since Li-Fi uses light, it can be used in aircrafts and hospitals where radio waves
may cause interference. It can also be used underwater where Wi-Fi does not work. It
provides greater security as light cannot penetrate walls when compared to Wi-Fi. One
of the shortcomings of Li-Fi is that it works only in direct line-of-sight. In future this
technology can be further developed to use light bulbs as a source of Internet.
Check yourself
228
9. Internet
229
b. Web browsing
All of us have visited web sites by entering the website address (URL) into web browsers
and then using the hyperlinks in it to move through the web pages. Traversing through
the web pages of World Wide Web is called web browsing. Major operations performed
while web browsing are shown in Figure 9.7.
Web server
Suppose you wish to visit the website ‘www.kerala.gov.in’. What will you do? You will
enter this URL in the address box of the web browser and press Enter key. The steps
a browser will follow to display a webpage may be summarised as follows.
1. The browser determines the URL (http://www.kerala.gov.in) entered.
2. The browser then sends a request to the DNS server of the user’s ISP to get the
IP address of the URL.
3. The ISP’s DNS server replies with the IP address.
4. The browser then makes a TCP connection to the web server at the IP address
(www.kerala.gov.in).
5. Then it sends a GET request for the required file (web page) to the web server.
6. The web server returns the web page.
7. The TCP connection is released.
8. The browser processes the contents of the webpage and displays it.
230
9. Internet
its
find possible keywords. The search vis index in the server
engine website stores these keywords
along with their URLs to form an index la u n c h
es
in the search engine’s web servers. Spider/
Crawler
When we use the search engine website
Search engine server
to search a particular topic (keyword),
it does not search the World Wide
Web. It only searches the index, which
the web crawler programs have created
in the search engine’s web server for
the topic/keyword. Search engines Fig. 9.8 : Working of a search engine
231
select a list of URLs where the particular topic is found from the index and displays it as
the result. Figure 9.8 shows the working of a search engine.
Some of the most popular web search engine sites are Google, Bing, Yahoo Search,
Ask, etc. Figure 9.9 shows the search results of different search engines.
9.4.3 E-mail
E-mail enables us to contact any person in the world in a matter of seconds. Billions of
e-mail messages are sent over the Internet every day. Electronic mail or e-mail is a
method of exchanging digital messages between computers over Internet.
E-mail has become an extremely popular communication tool. The e-mail will be
delivered almost instantly in the recipient’s mail box (Inbox). Apart from text matter, we
can send files, documents, pictures, etc. as attachment along with e-mail. The same e-
mail can be sent to any number of people simultaneously. Figure 9.10 shows a sample
e-mail message.
Most of you will have an e-mail address. The structure of an e-mail address is:
user name@domain name. An example of an e-mail address is
[email protected]
An e-mail address consists of two parts separated by @ symbol. The first part
scertkerala is the username that identifies the addressee and the second part gmail.com
is the domain name of the e-mail server, i.e., the name of the e-mail service provider.
E-mails can be accessed using websites like gmail.com, hotmail.com, etc. that provide
web applications consisting of functions to send, receive, forward, reply and organise
emails . Such a facility is popular and is commonly referred to as web mail.
232
9. Internet
E-mails can also be accessed using e-mail client software that is installed in our computers.
Such software uses our e-mail address and password to retrieve e-mails from the e-
mail service provider’s server and store it in our computer. An e-mail client allows to
send, receive and organise e-mail. The messages sent when the computer is offline are
stored in the program and send later when computer is online. For receiving messages,
e-mail client applications usually use either the Post Office Protocol (POP) or the Internet
Message Access Protocol (IMAP). The popular e-mail client applications are Microsoft
Outlook and Mozilla Thunderbird.
a. Sections of an e-mail
A client software gives provisions to enter the following sections.
To (Recepient Address) – A box to provide the e-mail addresses of the primary recipients
to whom the e-mail has to be sent.
Cc (Carbon copy) – Write the e-mail addresses of the secondary recipients to whom
the message has to be sent.
Bcc (Blind carbon copy) – Write the e-mail addresses of the tertiary recipients who
receive the message. When the message is received the primary and secondary recipients
cannot see the email addresses of the tertiary recipients in the message. Depending on
e-mail service used, the tertiary recipients may only see their own e-mail address in
Bcc, or they may see the e-mail addresses of all recipients.
Subject – Provide a meaningful subject for your conversation here. This helps you to
identify a conversation with a particular person when you search your e-mails later.
Content – Type your message here. Today most of the e-mail service providers offer
features to create an attractive message by giving colours, changing font styles, size,
etc.
Attachment facility allows us to send files
like documents, pictures, etc. along with
an e-mail. The ‘Send’ button is used to
send the message to the recipients. ‘Reply’
button allows you to send a reply back
to the sender of the message received.
‘Forward’ button helps you to send a
message received by you to other people.
Figure 9.11 shows the major sections of
an e-mail.
Fig. 9.11 : Composing an e-mail
233
b. Working of e-mail
Have you ever wondered how e-mail is sent from your computer to a friend on the
other side of the world? When an e-mail is sent from your computer using web mail or
e-mail client software, it reaches the e-mail server of our e-mail service provider. From
there the message is routed from sender’s e-mail server all the way to the recipient’s e-
mail server. The recipient’s e-mail server then delivers the e-mail to the recipient’s mail
box (inbox), which stores the e-mail and waits for the user to read it. Simple Mail
Transfer Protocol (SMTP) is used for e-mail transmission across Internet. Figure 9.12
shows the working of e-mail.
1. Sender composes
message using e-
mail client/ web mail
2. Sender uploads SMTP
message to SMTP server
server
3. Message traverses
Internet (probably
passing through
several routers)
5. Recipient’s e-mail client/ web mail checks
mailbox for new messages and downloads
4. Message arrives at message
receiving server and is
placed in recipient’s 6. Recipient reads
mailbox file/folder message using e-mail
SMTP/POP3/ client/ web mail.
IMAP Server
Fig. 9.12 : Working of e-mail
234
9. Internet
Can you imagine a fridge which checks its egg tray and reminds you
to buy eggs in your mobile phone or orders the nearby grocery store
to supply eggs to your home; an air conditioner that can be switched
on or off using your mobile phone; or a car that automatically reminds you about
filling fuel as you approach a fuel pump? This is being made possible using Internet
of Things (IoT). IoT is the concept of connecting all devices like mobile phones,
fridges, cars, air conditioners, lamps, wearable devices, etc. to the Internet. Each
device is provided with a unique IP address which identifies it and allows it to
transfer data over Internet without human intervention. The huge increase in the
number of IP addresses due to the implementation of IPv6 supports the
introduction of this technology. The IoT can be used to monitor health of patients
and inform the doctor about an urgency, applied to things which help us reduce
wastage like power, water, etc. and improve the way we work and live.
235
a. Classification of social media
The various types of social media that exist on
the Internet are: Internet forums, social blogs,
microblogs, wikis, social networks, content
communities and a lot more. Figure 9.13
displays logos of popular social media websites.
Here we discuss the most popular
classifications of social media.
1. Internet forums
An Internet forum is an online discussion web
site where people can engage in conversations
in the form of posted messages. Each Internet
Fig. 9.13 : Logo of popular social
forum will have sub forums which may have media websites
several topics. Each discussion on a topic is
called a thread. People can login and start a thread or respond to discussion in a
thread. Some forums allow anonymous login also. Discussions can be about
programming, social/political issues, fashion, etc. These discussions help us to learn
and find solutions to problems. Ubuntu Forum – a community that provides help on
Ubuntu is a popular forum.
2. Social blogs
A blog (web log) is a discussion or informational website consisting of entries or posts
displayed in the reverse chronological order i.e., the most recent post appears first.
Some blogs provide comments on a particular subject; others function as personal
online diaries and some others as online brand advertising for a particular individual or
company. Initially blogs were created by a single user only. But now there are multi-
author blogs that are professionally edited. Blogger.com and Wordpress.com are popular
sites that offer blogging facility.
3. Microblogs
Microblogs allow users to exchange short sentences, individual images or video links.
People use microblogs to share what they observe in their surroundings – information
about events and opinions about topics from a wide range of fields. Microblogging
offers a communication mode that is spontaneous and can influence public opinion.
Twitter.com is a popular microblogging site.
4. Wikis
Wikis allow people to add content or edit existing information in a web page, to form a
community document. Wiki is a type of content management system. Editing done by
236
9. Internet
users is very closely monitored by other editors and therefore incorrect information,
advertising, etc. are removed immediately. wikipedia.org – the free online encyclopedia is
the most popular wiki on web.
5. Social networks
Social networking sites allow people to build personal web pages and then connect
with friends to communicate and share content. We can share text, pictures, videos,
etc. and comment to the posts. A social networking site can be for general topics or for
a specific area like professional networking. Public opinion is greatly influenced by the
discussions and posts in these websites. Popular social networking sites are
facebook.com and linkedin.com.
6. Content communities
Content communities are websites that organise and share contents like photos, videos,
etc. Youtube.com is a popular video sharing site and flickr.com shares pictures.
Most of today’s social media websites offer more than one type of service, i.e., social
networking and microblogging; blogging and internet forum; etc. Studies have revealed
that social media is now recognised as a social influencer.
b. Advantages of social media
• Bring people together: Social networking allows people to find long-lost child-
hood friends and make new ones.
• Plan and organise events: These sites help users to organise and participate in
events.
237
• Business promotion: Social media offers opportunities for businesses to con-
nect with customers, implement marketing campaigns, manage reputation, etc.
• Social skills: These sites allow people to express their views over a particular
issue and become an agent for social change.
c. Limitations in use of social media
• Intrusion to privacy: The personal information of users can be used for illegal
activities. Information like the e-mail address, name, location and age can be used
to commit online crimes.
• Addiction: Addiction to these sites wastes our valuable time. It will negatively
affect our mental states and may lead to depression and tension. It can reduce the
productivity of workers in an organisation. Students may lose concentration and
this in turn may affect their studies.
• Spread rumours: Social media will spread the news very quickly. It can facilitate
or worsen a crisis by spreading negative information or misinformation at an in-
credible speed.
d. Social media interaction – Best practices
• Avoid unnecessary uploading of personal data like e-mail address, telephone num-
ber, address, pictures and videos.
• Setting time schedule for using these sites can save wastage of time.
• In social media websites like wikis and blogs, photo and video sharing are public.
What you contribute is available for all to see. Be aware of what you post online.
Avoid posting content you may regret later.
• Set your privacy levels in such a way that you know exactly who can see your
posts and who can share them.The three basic privacy levels in social media are
private, friends and public.
238
9. Internet
Check yourself
239
9.5.2 Worm
A computer worm is a stand alone malware (malicious software) program that replicates
itself in order to spread to other computers. Worms spread from computer to computer
on its own. Unlike a virus, it does not need to attach itself to a program to propagate. A
worm takes advantage of the data transport features of the computer system to travel
without help. Worms always slow data traffic on the network by consuming bandwidth,
whereas viruses almost always corrupt or modify files on a computer. The most
destructive effect that a worm can cause is through e-mails. A worm can send a copy of
itself to every address in an e-mail address book. Then, the worm sends itself to everyone
listed in each of the receiver’s address book and so on.
Ie0199.exe Trojan
240
9. Internet
Trojan War
9.5.4 Spams
Spams or junk mails are unsolicited e-mails sent
indiscriminately to persons to promote a product or
service. Spammers collect e-mail addresses from
chat rooms, websites, customer lists, newsgroups,
etc. Clicking on links in spams may send users to
websites that host certain viruses. Today most e-
mail service providers provide e-mail filters that can Fig. 9.14 : Collection of spams in the
successfully separate genuine email from spams as e-mail menu
241
There is another category of hackers called grey hat hackers, who fall between white
and black hackers. They sometimes act illegally, though with good intentions, to identify
the vulnerabilities. Grey hat hackers do this to achieve better security.
9.5.6 Phishing
Phishing is a type of identity theft that occurs online. Phishing is an attempt to acquire
information such as usernames, passwords and credit card details by posing as the
original website, mostly that of banks and other financial institutions. Phishing websites
have URLs and home pages similar to their original ones. The act of creating such a
misleading website is called spoofing. People are persuaded to visit these spoofed
websites through e-mails. Users are tempted to type their usernames, passwords, credit
card numbers, etc. in these web pages and lose them to these websites. These frauds
use this information to steal money. Phishing is currently the most widespread financial
threat on the Internet. The URL in Figure 9.15 indicates that it is a phishing website.
242
9. Internet
243
9.6.1 Firewall
A firewall is a system of computer hardware and software that provides security to the
computer network in an organisation. A firewall controls the incoming and outgoing
network traffic by analysing the data
Home and determining whether they should
network be allowed through or not, based on a
Internet
Firewall
rule set. Firewalls deny malicious data
from entering into the computer
networks as shown in Figure 9.17.
244
9. Internet
harmful cookies that are used by different websites to compromise our privacy. Such
websites store a special cookie in our computer that will keep track of our activities
like, websites visited, products purchased or the forms that are filled. Most browsers
provide facilities to manage/delete harmful cookies. Frequent deletion of cookies helps
to prevent illegal access and use of personal information.
I I MY PASSWORD
STOP think
MIXES
LeTters
BEFORE BEFORE I #umbers
I
DOWNLOAD click AND
$ymbol!#
245
Guidelines for Setting up a Strong Password
• A password should have atleast 8 characters.
• A password should contain
• Upper case letters
• Lower case letters
• Numbers
• Symbols like @, #, $, etc.
• A password should not be personal information like name, date of
birth, etc. or common words.
• Never disclose your password to others.
• Do not write it on a paper or store it in a file in your computer.
• Do not use the same password for all logins.
• Change password often.
• Be careful about giving personal data online. If you see e-mail message requests
for personal data such as telephone number, address, credit card number, etc.
from unknown persons, ignore it.
• Visit banks’ websites by typing the URL into the address bar. Do not click on links
within e-mails to go to bank websites. Banks or any of its representatives never
sends you e-mail/SMS or phone calls to get your personal information, usernames
or password. Never reveal your passwords or ATM card details to anyone.
• Check whether the website you are visiting is secure while performing financial
transactions. The web address in the address bar should start with ‘https://’. Also
look for a lock icon on the browser’s address bar.
• Keep a regular check on your online accounts. Regularly login to your online
accounts, and check your statements. If you see any suspicious transaction, re-
port them to your bank or credit card provider.
246
9. Internet
Check yourself
1. What is a virus?
2. What do you mean by phishing?
3. The small text files used by browsers to remember our email id’s,
user names, etc are known as _____________ .
4. The act of breaking into secure networks to destroy data is called
_____________ hacking.
5. What is quarantine?
Let us sum up
The Internet, which was started as a defence project of the US government has
become a part of our life. Today the Internet is accessed using mobile devices like
mobile phones, tablets, etc. than using a desktop computer. Therefore speed of
Internet access has become an important factor. New technologies connect to Internet
focus on data transmission speed. Internet services like e-mail, social media, searching
etc. have changed the way we communicate. Each of the above services has its own
benefits and risks. Computer networks today play an important role in providing the
above services. It has increased the risk factors for networks, like viruses, worms,
Trojan horse, phishing, etc. Antivirus software, firewalls, etc. are used to protect
computer networks from different kinds of attacks. The risks for a network attack
can be reduced by following certain guidelines while using computers on Internet.
Learning outcomes
After the completion of this chapter the learner will be able to
• recognise the people behind the evolution of Internet.
• identify the hardware and software requirements for Internet connection.
• use the services available on Internet.
• classify the different types of social media.
• judge the risks while interacting with social media.
• recognise the threats to network security.
247
Sample questions
Very short answer type
1. Why is the invention of HTTP and HTML considered as an important land mark
in the expansion of Internet?
2. Compare intranet and extranet.
3. Write short notes on
a. Mobile broadband b. Wi-MAX
4. Explain the terms web browser and web browsing.
5. Compare blogs and microblogs.
6. What are wikis?
7. What is firewall?
Short answer type
1. Your neighbour Ravi purchased a new PC for his personal use. Mention the com-
ponents required to connect this PC to Internet.
2. What are the advantages of using broadband connection over a dial-up connec-
tion?
3. XYZ engineering college has advertised that its campus is Wi-Fi enabled. What is
Wi-Fi? How is the Wi-Fi facility implemented in the campus?
4. Madhu needs to prepare a presentation. For this, he uses www.google.com to
search for information. How does google display information when he types
‘Phishing’ in the search box and clicks search button?
5. Manoj’s e-mail id is [email protected]. He sends an e-mail to Joseph whose
e-mail id is [email protected]. How is the mail sent from Manoj’s computer to
Joseph’s computer?
6. How does a Trojan horse affect a computer?
7. Explain a few threats that affect a computer network.
Long answer type
1. Suppose you wish to visit the website of kerala school kalolsavam,
www.schoolkalolsavam.in and you have entered the URL in the address bar. Write
the steps that follow until the home page is displayed.
2. Write the disadvantages of social media. What are the different ways to avoid the
disadvantages of social media?
3. Explain the various broadband technologies available for Internet access.
248
10. IT Applications
10
249
key role in conducting research for the development of new drugs.We also discuss
various ICT enabled services in this chapter.
Information and Communication Technology (ICT) is the term often used as an extended
synonym for Information Technology (IT). ICT is more specific in integrating
telecommunication and computers comprising of many technologies for capturing, storing,
processing, interpreting and printing information.
10.1 e-Governance
Information Technology (IT) has contributed much to the smooth functioning of
governments. It comprises many technologies for capturing, processing, interpreting,
storing and transmitting information. IT helps governments to take quick and judicious
decisions. It also increases transparency and accountability in all its services. Information
and Communication Technology(ICT) aided Governance is generally known as
e-Governance.
e-Governance is the application of ICT for delivering Government services to citizens
in a convenient, efficient and transparent manner. The objective of e-Governance is to
ensure that the services of the Government reach the public promptly and effectively. In
Kerala, we have many government departments like the Motor Vehicle Department,
Education, Revenue, etc. which have successfully implemented e-Governance. Let us
now discuss various types of interactions in e-Governance.
10.1.1 Types of interactions in e-Governance
e-Governance facilitates interaction among different stakeholders in governance.
Categories of these interactions are described as follows:
Government to Government (G2G) - It is the electronic sharing of data and/or
information among government agencies, departments or organisations. The goal of
G2G is to support e-Governance initiatives by improving communication, data access
and data sharing.
Government to Citizens (G2C) - It creates an interface between the government and
citizens. Here the citizens enjoy a large range of public services. It increases the availability
and accessibility of public services. It also improves the quality of services. Its primary
purpose is to make the government citizen-friendly.
Government to Business (G2B) - Here, e-Governance tools are used to aid the
business community to interact with the government. The objective is to cut red-tapism,
save time, reduce operational costs and create a more transparent business environment
while dealing with the government.
Government to Employees (G2E) - Government, being the biggest employer has to
interact with its employees on a regular basis. This interaction is a two-way process
between the government and the employees. The policies and guidelines for implementing
250
10. IT Applications
251
Panchayats. The network also connects a large number of various offices of government
departments. The infrastructure supports the integration of a large number of G2G,
G2C services with the applications received from the State Data Centre.
c. Common Service Centre (CSC)
Common Service Centres (CSC) are the front-end delivery points of the government,
private and social sector services for the rural citizens of India. A highlight of the CSCs
is that it offers web-enabled e-Governance services in rural areas. It helps in utility
payments such as electricity, telephone and water bills, submission of online applications
and generating and distributing the certificates to the needy. Other services that could
be offered through CSC are listed below:
• Agriculture services
• Education and training services
• Health services
• Rural banking and insurance services
• Entertainment services
• Commercial services
In Kerala Akshaya centres are working as Common Service Centres.
Akshaya centres
Akshaya centres were initially launched in the year 2002 in the Malappuram district in
Kerala. Its intention was to impart e-Literacy to the citizens. Akshaya was conceived
as a landmark ICT project by the Kerala State Information Technology Mission
(KSITM) to bridge the digital divide and to bring the benefits of ICT to the entire
population of the State. The services include e-grantz, e-filing, e-district, e-ticketing,
submitting online application for ration card and electoral ID, Aadhaar enrolment,
Aadhaar based services, insurance and banking services.
252
10. IT Applications
253
10.1.5 Useful e-Governance websites
Table 10.1 shows the addresses of some websites that provide various services of the
Government of Kerala. Figure 10.2 shows the home page of the Department of Higher
Secondary Education, Kerala State and Figure 10.3 shows the home page of e-District
portal.
254
10. IT Applications
www.dhsekerala.gov.in
As an official site of the Department of Higher Secondary Education,
Government of Kerala, www.dhsekerala.gov.in provides various
facilities and services to students, teachers and school administrators.
The services include registration for the examinations, issue of hall tickets,
publication of exam results, distribution of various circulars and notifications, etc.
This site also provides facilities for downloading various forms and study materials
including model question papers.
255
Check yourself
257
The term M-Business or mobile business covers all the business
activities, processes and applications performed by means of mobile
devices such as mobile phone, PDA, etc. M- Business can be regarded
as a branch of e- Business.
e-tailing (or electronic retailing) is the selling of retail goods on the Internet. It is
the most common form of business-to-consumer (B2C) transaction.
258
10. IT Applications
www.irctc.co.in
Indian Railway Catering and Tourism Corporation Limited (IRCTC) is
a government of India enterprise. It handles the catering , tourism
and online ticketing operations of the railways. IRCTC provides online
booking facilities of railway tickets and offers other services like checking
reservation status, train timing, reservation of hotels for the tourists across the
country.
259
Check yourself
260
10. IT Applications
Internet connection. Video chatting facility is also available. It however requires fairly
high speed Internet connection and supporting devices such as web camera and speakers.
On line chat is a framework that provides interaction in a social environment. It helps
communicating with people at different places. This facility can also be used to deliver
and transfer live lectures given by the faculty. Students can login from the remote locations
and attend the lecture.
d. e-Content
Nowadays lot of e-Learning materials are delivered in different multimedia formats like
videos, presentations, graphics, animations, etc. The e-Contents once prepared can be
broadcasted through television channels, webcasted or uploaded in websites. Uploaded
content can be downloaded, viewed and saved for future reference. The multimedia
contents have more scope to convey the subject matter effectively. It can show actual
or simulated activities which are not possible in the traditional classroom based teaching.
e. Educational TV channels
There are many telecasting/webcasting channels which are dedicated for the e-Learning
purpose. These channels broadcast recorded classes on various subjects, interviews
with experts, lab experiments, etc. Some of these channels can be watched in the
Internet also. Dooradarshan’s ‘VYAS’ and Kerala Government’s ‘VICTERS’ channel
are examples of educational television channels.
10.3.2 Advantages of e-Learning
e-Learning has lot of advantages. They are listed below:
• e-Learning has the ability to offer courses on variety of subjects to large number
of students from distant location.
• In e-Learning cost for learning is much less. It saves journey time and money,
instructor fees, etc.
• People with limited financial resources are very much supported by the lower cost
of e-Learning.
• It provides facility to do online courses from various nationally or internationally
reputed institutions.
• Time and place is not a constraint for e-Learning.
10.3.3 Challenges to e-Learning
Listed below are some of the challenges faced by e-Learning:
• Face to face contact between students and teachers is not possible.
• Proper interaction among teachers and students are often limited due to the lack
of infrastructural facilities.
• Equipment and technology (computer and high speed Internet) requirement
restrict adoption of e-Learning.
• Learners who require constant motivation may not be serviced adequately.
• Hands-on practicals in real laboratory scenario is also a constraint in e-Learning.
261
10.3.4 Useful e-Learning websites
The summary of useful e-Learning websites are shown in Table 10.3. Figure 10.6
shows the home page of IGNOU (Indira Gandhi National Open University)
Address of website Purpose/Service
www.ignouonline.ac.in Website of Indira Gandhi National Open University, one of
the leading open universities offering various courses in the
distance education mode.
www.nptel.iitm.ac.in National Programme on Technology Enhanced Learning
(NPTEL) provides e-Content through online Web and Video
for courses in Engineering, Science and humanities streams.
262
10. IT Applications
www.ignouonline.ac.in
IGNOU (Indira Gandhi National Open University) is an open university
under Government of India. The website provides several features
including eGyankosh, which is a digital repository available in text
and video format. The site also provides webcasting facility linking to education
channels - Gyandarshan, Gyanvani and EDUSAT. Virtual class provides links to all
the online programmes conducted by the University.
Check yourself
263
10.4 ICT applications in health care
Developments in ICT have contributed much in the field of medical practice and medical
care. There is an enormous range of opportunities for significant cost reduction and
service enhancement through IT applications in health care. Let us discuss some of the
changes that ICT has brought about in the field of medicine and healthcare.
10.4.1 Medical equipments
ICT in
Most of the modern medical equipment work with Health Care
the support of computers. Scanners like CT and
MRI depend on computers to process their data
Medical Patient record
into a readable format. Micro-processors are used equipment keeping
to control a variety of support devices. Computer
guided lasers are used in surgery, even in the
Web-based
removal of brain tumours. Some hand-held devices support/ Communication
are also available that help patients to lead normal diagnosis
life. A device for self-monitoring of sugar levels
for people with diabetes is an example.
Research
10.4.2 Electronic Medical Record (EMR)
There has been a move to store all patients' records Fig. 10.8 : ICT in health care
10.4.4 Telemedicine
Telemedicine has been used to share observations and prescriptions with the experts in
the medical field. A surgeon in one part of the world can procure medical expertise
from another who is far away, while performing surgery. It reduces cost and time. A
patient in a critical condition can get attention from a surgeon who may not be physically
available at the operation theatre. Wireless transmission helps medical personnel,
transport workers and hospitals to keep in touch in emergency.
10.4.5 Research and development
Over recent years drug discovery has been a concern for many in the pharmaceutical
industry. Escalating costs and increasing complexity suggest that traditional research
and development methods are to be changed. Now the convergence of information
and bio-technology is revolutionising drug discovery and design. Today, drugs meant
for specific purposes can be developed with the use of advanced computers. Use of IT
may radically alter the cost associated with the discovery of drug over the coming
years. Thus IT helps in diagnosis, treatment of patients and better running of hospitals.
10.5 ICT enabled services
ICT enabled services, also called web enabled services cover the entire range of
operations which make use of ICT for improving services provided by an organisation.
These services provide a wide range of career options that include opportunities in call
centres, BPOs, medical transcription, etc. Some of the common ICT enabled services
are discussed in the following sections.
10.5.1 Business Process Outsourcing (BPO)
Outsourcing is a term used in the business field. It is a practice used by different
companies to reduce costs by transferring portions of work to outside suppliers. It is
the process of hiring another company to handle business activities for you. Business
process outsourcing (BPO) is a subset of outsourcing. It involves contracting of the
operations and responsibilities of specific business functions to a third-party service
provider. Outsourcing sometimes involves transferring employees and asset from one
firm to another.
Companies implement Business Process Outsourcing (BPO) because it increases their
efficiency and saves cost. Processes such as human resource management, customer
care services, payroll, etc. are some of the processes that are usually given to BPO.
10.5.2 Knowledge Process Outsourcing (KPO)
Knowledge Process Outsourcing (KPO) is a form of outsourcing. Here knowledge
and information related work is carried out by a different company or subsidiary within
the same organisation. It helps in saving costs and resources. Some of the core processes
outsourced in KPO include: data search, data integration, market research, fraud
analytics, etc. The KPO sector has experienced explosive growth in recent years.
Industries that are increasingly using KPO include legal, financial services, management
and consulting.
265
10.5.3 Call centre
Call centres are becoming a very important part of any business/service organisation.
Call centres facilitate the public for the payment of bills, purchase of goods, etc. A call
centre is a telephone service facility set up to handle a large number of both incoming
and outgoing calls for an organisation.
Call centres are also called service centres, sales centres, contact centres, etc. Basic
responsibility of a call centre is to handle the telephone calls for supporting various
services provided by an organisation. Call centres are used by telemarketing companies,
computer product help desks and any large organisation that uses the telephone to sell
products and carryout services. Generally the calls can be classified as in-bound calls
and out-bound calls. In-bound calls are usually meant to seek assistance, help, or to
order, while out-bound calls are meant for sales promotion or other messages.
Some firms, however, specialise only in calls that are in-bound or out-bound. Most
telephonic orders are handled by call centres and not by the manufacturers or suppliers
of goods or services.
10.5.4 Teleconferencing
Teleconferencing is a meeting or conference held between two or more parties in remote
locations, made possible by the use of IT infrastructure and services.
Teleconferencing is used to connect several different people from several different
locations. It is used in educational, business and administrative fields. Saving time, reducing
travel expense and including several people in a decision-making process are some of
the advantages.
10.5.5 Video conferencing
Video conferencing is a type of teleconferencing wherein we can include the video of
the parties involved in the conference. Videoconference allows people at remote locations
join in a conference and share information. A video camera and a speakerphone are
connected to a computer and the computers are connected to the network or Internet.
Video conferencing is a facility which enables participants in distant locations to take
part in a conference by means of audio and video communication.
Let us sum up
Information Technology (IT) is a fast growing field. It is widely used in our day today
activities. Business transactions, government activities, learning processes, research
and medical field, etc. are some of the major areas where IT is substantially utilised.
The explosion in the development of communication owes much to information
technology. The use of IT helps people communicate with less effort and minimum
cost. ICT is another term often used as an extended synonym for IT. Some of the
ICT enabled services include BPO, KPO, Call centre, Teleconferencing and Video
conferencing. Hence IT and ICT enabled services have become inseparable part of
modern society.
266
10. IT Applications
Learning outcomes
Sample questions
Very short answer types
1. Name an electronic device using which we can easily read e-Text.
2. Write the full forms of BPO and KPO.
3. Name any two e-Learning tools.
Short answer types
1. List out different types of interactions in e-Governance.
2. Differentiate between BPO and KPO.
3. What are the advantages of e-Governance?
4. What are the duties of Akshaya?
5. Write down the function of Call centres.
Long answer types
1. What are the major challenges faced in the implementation of e-Learning ?
2. Compare the advantages and disadvantages of implementing e-Business?
3. Explain any three IT enabled services in detail.
4. Discuss in detail various uses of IT in health care field.
5. What is Common Service Centre (CSC)? List some of the services offered through
CSC.
267
References
Pradeep K. Sinha, Priti Sinha. Computer Fundamentals : BPB Publication
268