You are on page 1of 550

eÁw

GOVERNMENT OF KARNATAKA

COMPUTER SCIENCE

TEXT BOOK
FOR
FIRST PUC

Directorate of Pre University Education


Malleshwaram, Bengaluru - 560 012.
www.pue.kar.nic.in

i
Director’s Message

Dear Students,

We at the Department of Pre-university Education,


Karnataka strive to empower each student to dream big
and equip them with the tools that enable them to reach
new heights and successfully deal with the challenges of
life. As Swami Vivekananda said, "Real education is that
which enables one to stand on one's own legs".

The course contents in this book are designed with


the objective of equipping you well for the next level of
study.

We wish you well on your journey and look forward to


you becoming a responsible citizen of the nation and give
back to the betterment of the society.

With best wishes,

Sd/-
C. Shikha, IAS
Director
Department of Pre University Education
Bengaluru
eÁw

Preface

A new syllabus is introduced at the pre-University level after a number of fruitful deliberations.
We now go ahead to widen our knowledge and to see brighter things. Adapting to new
requirements has always been a difficult task of our lives, however we will have to look at
things with a positive attitude and take things with a challenging approach. The new syllabus
will provide the same feeling. It is however important to see that we prepare our students to
face this world with a positive attitude and equip them with the latest knowledge.
The book is organized in such a way that it is useful to the knowledgeable teacher and the
ever-willing learner. It allows the teacher to prepare the student for greater learning. The
students are further ignited to explore into the field so that they are the torchbearers of
tomorrow. The field of computer science is such that it always provides a challenge for those
who want to do better.
The vast experience of the authors has allowed them to prepare this material so that it meets
the exact requirement of the student. Greater importance is provided to the presentation, this
has always helped the students in easily understanding the subject. Importance is given to
programming methodology so that the student learns the correct technique of programming.
Good programming techniques rather than smaller programs have always generated efficient
solutions to problems. Thought provoking questions are included at the end of each chapter
this allows the student to further improve his abilities.
An effort of this nature is not possible without the blessings of number of people. The authors
would thank them and pray to provide them the strength to always travel in the right direction.
Suggestions for the improvement of the book are always awaited with open hearts.

AUTHORS

iii
AUTHORS
Sri Rajappa
Chairperson
Empress Govt. Pre-University College for Girls, Tumkur.

Smt. Sharon Mednora


Co-ordinator
Govt. Pre-University College for Boys,
18th Cross, Malleshwaram, Bengaluru.

Smt. Hemalatha N
Member
Vijaya College, R.V. Road
Basavanagudi, Bengaluru.

Sri. Srinivas K. P
Members
Govt. Pre-UniversityCollege for Women
Balmatta, Mangalore.

Sri Naveen Kumar B


Member
Govt. Pre-UniversityCollege
13th Cross, Bengaluru.

Sri Santus Xavio B.K


Member
Stracey Memorial Pre-University College
No.52, St. Marks Road, Bengaluru.

iv
eÁw

ACKNOWLEDGEMENT

The Pre-University Board acknowledges the valuable contribution of the


individuals and organization involved in the development of Computer Science Text
book for the First PUC students.

The Pre-University Board acknowledges the whole hearted service of the


reviewers Sri. H K GunduRao, Sri. N S Manjunth and Sri. M N Nachappa.

The Board specially acknowledges the service of Sri. M N Nachappa for his
co-cordination and guidance from shaping the syllabus till the submission of the text
book.

The Pre-University Board acknowledges the co-operation of Sri. Marulaiah B,


Principal, Empress Govt. Pre-University College for Girls, Ashoka Road, Tumkur.

The Pre-University Board acknowledges Govt. Pre-University College for Boys,


Malleshwaram,Bangalore for providing facilities to us.

The Pre-University Board acknowledges the contribution of Sri. Manoj kumar,


Lecturer, Govt. Pre-University College, Sira, Tumkur District.

This textbook is revised as per the order.

My whole hearted thanks to family and friends for the support renderd to the
committe.

Sri.Rajappa
Chairperson,
Computer Science Syllabus review Committee.

v
TEXT BOOK DEVELOPMENT COMMITTEE
The Committee comprises of:
Sri Rajappa
Chairperson
Empress Govt. Pre-University College for Girls,
Tumkur

Reviewers:
Sri H.K. Gundurao, HOD, Vijaya College,
R.V. Road, Basavanagudi, Bengaluru

Sri M.N. Manjunath, HOD, Sri, Bhagawan Mahaveer Jain College,


J.C. Road, Bengaluru

Sri M.N. Nachappa, HOD, St. Joseph's College,


Langford Road, Bengaluru

Co-ordinator:
Smt. Sharon Mednora
Co-ordinator
Govt. Pre-University College for Boys,
18th Cross, Malleshwaram, Bengaluru
Members :
Smt. Hemalatha N
Member
Vijaya College, R.V. Road
Basavanagudi, Bengaluru

Sri. Srinivas K. P
Members
Govt. Pre-University College for Women
Balmatta, Mangalore

Sri Naveen Kumar B


Member
Govt. Pre-University College
14th Cross, Bengaluru

Sri Santus Xavio B.K


Member
Stracey Memorial Pre-University College
No.52, St. Marks Road, Bengaluru

vi
eÁw

Contents
UNIT A Fundamentals of Computers Page 30 Hrs
No

1 Overview of a Computer
1.1 Introduction 1
1.2 Functional Components of a computer
(Working of each unit) 6
1.3 Evolution Of Computers 8
1.4 Generations Of Computers 12
1.5 Classification Of Computers 16 8 Hrs
1.6 Applications Of Computers 23
2 Input, Output and Memory devices
2.1 Introduction to input deviceS 29
2.1.1 The Keyboard 31
2.1.2 The Mouse 32
2.1.3 The Joystick 33
2.1.4 The OMR, OCR, MICR 34
2.2 Introduction to output devices 35
2.2.1 The Monitors 35
2.2.2 The Printers (Characteristics to be identified) 36
2.2.3 The Speakers 39
2.3 Introduction to Memory devices (concepts, units, etc.,) 40
2.3.1 The Primary Memory 40
2.3.2 The Secondary Memory 44 8Hrs
2.3.3 The Cache Memory 48
3 Data Representation
3.1 Introduction 51
3.2 Non-Positional and Positional Number systems 53
3.3 Positional Number Systems 53
3.3.1 Decimal Number Systems 53
3.3.2 Binary Number Systems 54
3.3.3 Octal Number Systems 54

vii
3.3.4 Hexadecimal Number systems 55 2 Hrs
3.4 Number System Conversions (All types) 55 4 Hrs
3.5 Representation Of Integers 62
3.5.1 Sign and Magnitude representation 62
3.5.2 One’s Complement representation 63
3.5.3 Two’s Complement representation 63 1 Hr
3.6 Binary Arithmetic 64
3.6.1 Addition and Subtraction 64
3.6.2 Subtraction using 1’s and 2’s Complement 65 1 Hr
3.7 Computer Codes 67 1 Hr
3.7.1 Introduction to BCD, EBCDIC, ASCII, Excess-3 68
4 Software Concepts
4.1 Introduction 77
4.2 Types Of Software (Application and System software) 78
4.3 Introduction to Operating Systems 79
4.4 Functions Of Operating Systems 81
4.5 Types Of Operating Systems 83 5 Hrs
4.6 Functional features of commonly used operating systems 85
5 UNIT B Problem Solving Methodology 15 Hrs
5.1 Introduction to Problem Solving 93
5.2 Problem Definition 95
5.3 Problem Analysis 95 1 Hr
5.4 Design Of a Solution 95
5.4.1 Algorithms 95
5.4.2 Flowcharts 102 8 Hrs
5.5 Development Of Programs (Coding, testing, debugging) 107
5.6 Documentation and Maintenance 109 1 Hr
5.7 Programming Constructs 110
(Sequence, Selection and Iteration) 2 Hrs
5.8 Characteristics Of a Good Program 122
5.8.1 Types Of Errors 124 1 Hr
5.9 Approaches to Problem Solving 124
(Top-down, Bottom-up, Modular, Structured) 2 Hrs
UNIT C Programming in C++ 50 Hrs
6 Object Oriented Concepts
6.1 Evolution Of Programming techniques 133

viii
6.1.1 Procedural programming 135
6.1.2 eÁwStructured programming 135
6.1.3 Object Oriented programming 136
6.2 Basic concepts of OOP 137
6.2.1 Classes and Objects 137
6.2.2 Data Abstraction 138
6.2.3 Data Encapsulation 138
6.2.4 Inheritance 138
6.2.5 Polymorphism 139
6.3 Advantages and dis-advantages of OOP 142 2 Hrs
7 Introduction to C++
7.1 History 147
7.2 Characteristics of C++ 147
7.3 C++ Character Set 148
7.4 Tokens 148
7.4.1 Keywords 150
7.4.2 Identifiers 149
7.4.3 Literals
7.4.4 Punctuators 154
7.5 Operators 155
7.5.1 Arithmetic operators 157
7.5.2 Relational operators 158
7.5.3 Logical operators 159
7.5.4 Unary operators 156
7.5.5 Ternary operators 162
7.5.6 Shorthand operators 160
7.5.7 Bitwise operators 159
7.5.8 Special operators 162
7.5.9 Assignment operators 161
7.6 Precedence of operators 163
7.7 Type conversion (Implicit and Explicit) 165
7.8 Structure of a C++ program (with example) 167
7.8.1 Importance of iostream.h 170
7.8.3 Comments in C++ 168 12 Hrs

ix
8 Data types
8.1 Fundamental data types 179
8.2 Modifiers 183
8.3 Derived data types 184
8.4 User defined data types 184 2 Hrs
9 Input and Output operators
9.1 Input operator “>>” 189
9.2 Output operator “<<“ 190
9.3 Simple programs 191 4 Hrs
10 Control Statements
10.1 Introduction 201
10.2 Types Of Control statements 201
10.3 Selection statements 201
10.3.1 “if” statement 202
10.3.2 “if - else” statement 206
10.3.3 “nested -if” statement 209
10.3.4 “switch” statement 213
10.4 Iteration statement 216
10.4.1 “while” statement 216
10.4.2 “do-while” statement 221
10.4.3 Comparison between “while” and “do-while” 223
10.4.4 “for” statement 224
10.5 Jump statements (goto, break,continue) 227 10 Hrs
11 Arrays
11.1 Introduction to Arrays 239
11.2 Types of arrays 240
11.2.1 One Dimensional Arrays 240
11.2.2 Two Dimensional Arrays 240
11.2.3 Multi Dimensional Arrays 240
11.3 One Dimensional Arrays 240
11.3.1 Declaration of 1-D Arrays 240
11.3.2 Initialization of 1-D arrays 240
11.4 Two Dimensional Arrays 249
11.4.1 Declaration of 2-D Arrays 249
11.4.2 Initialization of 2-D arrays 249 8 Hrs

x
12 Functions
eÁw
12.1 Introduction 265
12.2 Different Header files 266
12.3 Mathematical Library functions 268
12.4 Character and string functions 268
12.5 Other functions 268 2 Hrs
13 User Defined Functions
13.1 Definition 285
13.2 Advantages of user defined functions 285
13.3 Structure of an user defined function 285
13.4 Calling a function 287
13.5 Returning a value 290
13.6 Function prototype 292
13.7 Types of arguments 293
13.8 Scope of variables 296
13.9 Types of functions 298
13.10 Call by value 305
13.11 Call by reference (using reference variables) 306
13.12 Arrays as arguments 308 8 Hrs
14 Structures
14.1 Introduction 319
14.2 Defining a structure 319
14.3 Declaring a structure 320
14.4 Initializing structure elements 323
14.5 Referencing structure elements 321
14.6 Nested structures 325
14.7 Array of structures 328 2 Hrs

UNIT D Elementary Concepts of Word Processing,


Spreadsheets and Web designing 25 Hrs
15 Word Processing
Word Processing applications: creation of documents,
Parts of the Menu/window, copy & move, formatting 335
features, spell check, print, creation of tables and other -
basic operations 336 5 Hrs

xi
16 Spreadsheets
16.1 Spreadsheet applications (elementary level), 339
Basics concepts of spreadsheet and other features -
such as, entering text, menus, commands, column 393
width, copy, paste, to insert rows/columns, formatting,
formula, print, sort, filter and other basic operations 8Hrs
16.2 Some advanced features such as graphs,
library functions (Arithmetic, Date and Time, Financial, 394
Logical, text and statistical) With emphasis on 414
commerce related applications and data forms with
application to simple problems 7 Hrs
17 Web Designing
17.1 Introduction to the Internet 416
17.2 Services On the Internet
17.3 Some Definitions related to the web 439 2 Hrs

17.4 Introduction to HTML 426


17.5 Basic tags
17.6 Formatting tags
17.7 Lists in HTML
17.8 Some additional tags and simple programs 442 3 Hrs

xii
BLUE PRINT
eÁw
FIRST PUC – COMPUTER SCIENCE FINAL EXAMINATION

GUIDANCE FOR DISTRIBUTION OF MARKS INCLUDING CHOICE QUESTIONS

Knowledge 30% 31
Understanding 40% 43
Application 20% 21
Skill 10% 10
Total 100% 105

Question Paper Structure

10 Questions of one mark without choice out of 10 (Very Short Answers) (VSA) PART A
05 Questions of two marks each out of 08 ( Short Answers) (SA) PART B
05 Questions of three marks each out of 08 (Long Answers) (LA) PART C
07 Questions of five marks each out of 11 (Essay Type) (E) PART D

Unit Description VSA(1 SA(2 LA(3 Marks) E(5Marks) Total


Mark) Marks) Marks
A Fundamentals of 2 3 2 2 24
Computers
B Problem solving 1 1 2 2 19
Methodology
C Programming in 5 3 4 5 48
C++
D Elementary Concepts 2 1 ------- 2 14
of Word Processing,
Spreadsheets and wed
designing (Commands
should not be
included)

Total Marks 10 16 24 55 105

Total No of 10 08 08 11 37
Questions in
Question paper
Total No of 1X10=10 2X5=10 3X5=15 5X7=35 70
Questions to be
answered

xiii
BLUE PRINT SUBJECT : COMPUTER SCIENCE(41)

Unit Description VSA SA LA E Total


(1 Mark) (2 Marks) (3 Marks) (5Marks) Marks
A Fundamentals 2 3 3 2 27
of Computers
Ch1 Overview of 1 1 ---- 1 08
Comp uters
Ch2 Input Outp ut and 1 1 1 ------- 06
Memory units
Ch3 Data ------ ------ 1 1 08
representation
Ch4 Software ------ 1 1 ------- 05
Concepts
B Problem solving 1 1 1 1 11
Ch5 Methodology

C Programming in 5 3 4 5 48
C++

Ch6 Object Oriented ------ 1 ------- ------ 02


Concepts
Ch7 Introduction to 1 ------- 1 1 09
c++
Ch8 Data types ------ 1 ------- ------ 02
Ch9 Input output 1 ----- 1 ------ 04
operators
Ch10 Control 1 ------ ------ 2 11
Statements
Ch11 Arrays 1 1 1 09
Ch12 Functions ----- 1 ------ ------ 02
(Library
functions)
Ch13 User defined 1 ------ ----- 1 06
Functions
Ch14 Structures 1 03
D Elementary 2 1 ----- 3 19
Concepts of
Word
Processing,
Spreadsheets
and wed
designing
(Commands
should not be
included)
Ch15 Word Processing 1 1 ------ ------ 03
Ch16 Spreadsheets 1 ------ ------ 2 11
Ch17 Web designing ------ ------ ------ 1 05
Total Marks 10 16 24 55 105

Total No of 1X10=10 2X5/8=10 3X5/8=15 5X7/11=35 70/37


Questions to be
answered

xiv
I PUC - Computer Science
eÁw
Practical’s Syllabus

BLUE PRINT

The practical examination marks of 20 is distributed as follows :

1. Writing one program from Section A and


one problem from either Section B or Section C 8 marks
2. Execution of any one ( Examiner choice ) 6 marks
3. Formatting the output 2 marks
4. Record writing 4 marks

TOTAL 20 marks

Practical List

Section A

List of practical programs for C++

1. Write a program to interchange the values of two variables


a. Using a third variable.
b. Without using a third variable.
2. Write a program to find the area and circumference of a circle.
3. Write a program to find the area of a triangle given three sides.
4. Write a program to convert days into years, months and days (Hint:
Assume all months have 30 days)
5. Write a program to find the largest, smallest and second largest of three
numbers using simple if statement.
6. Write a program to input the total amount in a bill, if the amount is
greater than 1000 the a discount of 8% is given otherwise no discount is
given, output the total amount, the discount amount and the final
amount, use simple if statement.
7. Write a program to check whether a given year is a leap year or not
using if-else statement.

xv
8. Write a program to input a character and find out whether it is a lower case
or upper case character using if-else statement.
9. Write a program to input the number of units of electricity consumed in a
house and calculate the final amount using nested-if statement. Use the
following data for calculation
Units Consumed Cost
< 30 Rs 3.50 / unit
>=30 and <50 Rs 4.25 / unit
>=50 and < 100 Rs 5.25 / unit
>=100 Rs 5.85 /unit
10. Write a program to input the marks of four subjects, calculate the total
percentage and output the result as either “First class”, or “Second class”,
or “Pass class” or “Fails” using switch statement.
Class Range %
First Class Between 60 and 100%
Second Class Between 50 and 59%
Pass Class Between 40 and 49%
Fails Less than 40%
11. Write a program to find the sum of all the digits of a number using while
statement.
12. Write a program to input principal amount, rate of interest and time period
and calculate compound interest using while statement
(Hint: CI = P * ( 1 + R / 100) T).
13. Write a program to check whether a given number is a power of 2.
14. Write a program to check whether a given number is an Armstrong number
using do-while statement (Hint: 153 = 13 + 53+ 33).
15. Write a program to find the factorial of a number using for statement.
16. Write a program to generate the Fibonacci sequence up to a limit using for
statement.
17. Write a program to find the sum and average of “N” numbers.
18. Write a program to find the second largest of “N” numbers.
19. Write a program to arrange a list of numbers in ascending order.
20. Write a program to find the position of a given number in an array.
21. Write a program to check whether a given matrix is scalar or not.
22. Write a program to sum of all the rows and the sum of all the columns of a
matrix separately.
23. Write a program to find the sum of two compatible matrices.

xvi
24. Consider an array MARKS[20][5] which stores the marks obtained
by 20 students in 5 subjects. Now write a program to:
eÁw
a) Find the average marks obtained in each subject
b) Find the average marks obtained by every student
c) Find the number of students who have scored below 50 in their
average
25. Write a program to check whether a given string is a palindrome or not.
26. Write a program to count the number of vowels and consonants in a
string.
27. Write a program to find the GCD and LCM of two numbers using
functions.
28. Write a program to find XY using functions.
29. An industrial organization wants to computerize the Allowance
calculations. Given the monthly Sales for the salesman, the rules for the
calculations are as follows:
i. If the total sales is less than Rs. 10000/- there is no allowance.
ii. If the total sales is between Rs. 10000/- and Rs. 20,000/- then
the
Allowance is 10% of the sales amount or Rs. 1800/- whichever is
minimum.
iii. If the total sales is greater than or equal to Rs. 20000/- then the
allowance is 20% of the sales amount or Rs.6,000/- whichever is
minimum.
Write a program using a function to calculate the allowance.
30. Write a program to input the register number, name and class of all the
students in a class into a structure and output the data in a tabular
manner with proper heading
Section B
Spreadsheet Practical List
1. Eight salesmen sell three products for a week. Using a spreadsheet create
a sales report. The report should include the name of the salesman, Amount
of sales for each product and the salesman’s total sales in the format
given below.
Sales for the Month
Name Total Amt. for Total Amt. for Total Amt. Total sales

a) Type in all text and numbers in the spreadsheet.


b) Format all numbers as a currency.

xvii
c) Center the spreadsheet headings across the spreadsheet.
d) Format all text.
e) Create formulas to display a total for each sales rep.
f) Create formulas to display a total for each product.
g) Create a formula to calculate the total sales for all sales rep’s for the
month.

2. Enter the following details for 10 employees Employee Code, Employee name,
Basic salary, DA, HRA, Loans, Total salary and Tax.
Salary for the Month

Employee Employee Basic DA HRA Loan Total Tax


Code Name Salary Salary

a) Type the Employee Code, Employee Name, Basic Salary and Loan
amount data for 10 employees in the spreadsheet.
b) Format all numbers as a currency.
c) Center the spreadsheet headings across the spreadsheet.
d) Format all text.
e) Create a formula to compute DA as 50% of the Basic salary and copy
this to all the cells.
f) Create a formula to compute HRA as 12% of the Basic salary and copy
this to all the cells.
g) Create a formula to compute Total salary and copy this to all the cells.
h) If Total salary is greater than 5,00,000, compute Tax as 20% of Total
salary otherwise 10% of the Total salary using a formula.

3. Enter the following details for 10 Students Register Number, Name, Subject1
Marks, Subject2 Marks, Subject3 Marks, Subject4 Marks, Total Marks and
Percentage.
Test Marks data of a Class
Register Name Subject1 Subject2 Subject3 Subject4 Total Percentage
Number Marks Marks Marks Marks Marks

a) Type the Register Number, Name and marks of four subjects for
10students in the spreadsheet.
b) Format all text and numeric data appropriately.

xviii
e) Create a formula to compute Percentage and copy this to all the cells.
f) Create a formula to compute the highest and lowest score using a
eÁw
library function.
g) Draw a bar graph for Register Number against total marks.
h) Draw Pie chart for one student showing his marks in different subject
from total score

4. A housewife maintains the budget expenditure in a spreadsheet under the


headings Income and Expenses. Income includes husband’s and Wife’s income
separately under different headings. Expenses include Rent, Bills, Household
expenses and medical expenses.
Budget for the Month
Income Expenses Total
Husband Wife Rent Bill Household Medical Expenditure Savings

a) Type the Income and Expenses data for the entire month in the
spreadsheet.
b) Format all numbers as currency.
c) Center the spreadsheet headings across the spreadsheet.
d) Create a formula to compute the Total expenditure and copy this to
all the cells.
e) Create a formula to compute the savings and copy this to all the cells.
f) Draw a bar graph to show expenditure under each heading.
g) Draw Pie chart to show the distribution of salary.

5. A Bank offers loan for housing and vehicle at an interest of 10.25% for
housing and 14.2% for vehicle. For a loan applicants compute the monthly
premium (EMI), given total installments as 24 months. Also compute the
monthly interest and monthly principal amount and the total amount of
principal and Interest paid using Financial library functions in a spreadsheet.

6. Implement five functions each for Arithmetic, Date and Time, Financial, Logical,
text and statistical functions. Write the syntax, example and output for simple
problems.
7. Create a data form to implement a student database and perform all related
operations with the data form.

Section C

Web Designing Practical List

1. Create a Web page to display your details using different tags.


2. Create a model Web site for your college making using different tags.

xix
First PUC PRACTICAL
EXAMINATION SUB – COMPUTER
SCIENCE (41)

General instructions:
 Duration of practical examination: 2 hours.
 Maximum marks allotted: 30 marks.
 The practical examination question paper should consists of two
questions for writing (One program from C++ and One problem
from either ESS or HTML )
 Each question carries 6 marks of writing ie 2X6=12 Marks.

 Only one experiment to be executed.


 Execution process carries 6(six ) marks.
 Generating the correct output for the executed problem carries two
marks.

Scheme of valuation
A. Weightage of marks

Sl.
Particulars Marks
No.
I Performing the Experiments 20
II Viva -voce 04
III Practical Record 06
TOTAL 30

xx
B. Distribution of marks
eÁw

I. Performing the Experiment

a) PROGRAMS ON C++

Sl. No. Particulars Marks


1 Including the necessary headers: 1
2 Declaration of correct identifiers 1
3 Input/Inputs commands 1
4 Logic 2
5 Output/Outputs commands 1
Total 6

b) PROBLEM on ESS

Sl. No. Particulars Marks


1 Including the necessary headers in ESS sheet : 1
2 Data entry 1
3 Using the correct Formula 2
4 Generating the correct output may include Graphs 2
Total 6

c) PROBLEM on HTML

Sl. No. Particulars Marks


1 Including the necessary basic tags of the HTML 1
2 Including the necessary basic tags of the Head & Title 1
3 Including the necessary basic tags of the Body 1
4 Including any other relevant tags 3
Total 6

xxi
II. Viva- voce
1. Four questions must be asked and each question carries 1 mark.

2. The questions in the viva- voce should be simple, direct and related to the
experiment to be performed by the student.

III. Practical Record

Sl. No. Particulars Marks


If the student has performed and recorded
27 programs or more
1 6
91% to 100% of the experiments prescribed for the
practical examination or more. )
If the student has performed and recorded
24 programs and below 27 programs
2 5
(81% to 90% of the experiments prescribed for the
practical examination.)
If the student has performed and recorded
21 programs and below 24 programs
3 4
(71% to 80% of the experiments prescribed for the
practical examination.)
If the student has performed and recorded
below 21 and above 11 experiments
4 3
(41% to 70% of the experiments prescribed for the
practical examination)
If the student has performed and recorded
below 10 or below 10 experiments
5 0
(40% and below40% of the experiments prescribed for
the practical examination)

NOTE : At least 30 experiments (21from C plus plus +7 from ESS +2


from HTML ) experiments have to be conducted in the Practical classes.

*************

xxii
eÁw

CHAPTER 1
FUNDAMENTALS OF COMPUTERS

OBJECTIVES
To Understand components
History
Generations of Computers

1
2
Fundamentals of Computers

eÁw

1.1 Introduction
Computers were invented to be an aid to the mankind in the field of calculations, the versatility
of present day computers are giving rise to the modern society in the field of information and
technology.
Computers are changing, the very being/area of communication, transport, trafficking, industry,
government, education, medicine, scientific research, law, social service and even arts like music, movies,
paintings, gaming or any filed which involves data and information.
Computers are becoming the bondage of reality in meeting the desires of communication and
exploration of information. The distance of the world is sinking with the utilization of the computers with
the help of email, chatting, online banking, booking tickets, audio, video etc.
Computer literates are well placed in the modern society in the field of career opportunities, workforce.
The professionals can attain greater opportunity with the help of computers.
The application of computers is wide and expandable, without limitation of time and place.
This chapter will explain the evolution of computers, personalities who have involved in the field of
computer, along with the functional units of the computer systems.

1.1.1 Definition
Computer is an automatic electronic machine that can store, recall and process data. Computers
are electronic machines that perform tasks or complex calculations according to a set of instructions or
programs.

Figure 1.1 COMPUTER SYSTEM

What can you do with computers? In the workplace, many people use computers to keep records,
analyze data, do research, and manage projects. At home, you can use computers to find information,
store pictures and music, track finances, play games, and communicate with others and these are just a
few of the possibilities. A computer is used essentially as a data processor.

3
Fundamentals of Computers

How does the computer work? Let’s consider, your mother is asking you to prepare tea. The ingredients
required may be ¾ cup of water, ½ teaspoon tealeaves, ½ teaspoon sugar and ½ cup of milk. You have
to follow certain definite steps to prepare tea like boiling water/milk, adding tea-leaves, sugar and milk.
Finally, you have prepared tea.
This Human being task/activity can be transformed into a computer environment in the following:

INPUT PROCESS OUTPUT


Ingredients required The actual process The result
Preparation of tea ¾ cup of water, Boiling water/milk, Obtain the prepared
½ teaspoon tealeaves, adding tea-leaves, tea.
½ teaspoon sugar and sugar and milk
½ cup of milk.

1.1.2 Characteristics of Computers

i. Speed
The ability to get answers fast enough so that one has time to take action.
Electrical pulses travel at incredible speeds, because the computer is an electronic machine, its
internal speed is virtually instantaneous. We do not talk in terms of seconds or even milliseconds. Our units
of speed are the microsecond (millionths), the nanosecond (thousand- millionths) and latterly even the
Picosecond (million-millionths). A powerful computer is capable of adding together two 18-digit number
in 300 to 400 nanoseconds, even the non-numerical environments. The indexing of the complete students
name in the college will consume less time with the help of computer.

ii. Memory
As a human acquires new knowledge, the brain subconsciously selects what it feels to be important
and worth retaining in its memory, and relegates unimportant details to the back of the mind or just forgets
them. Similarly in computers, the primary memory RAM is used to store the data temporarily.

iii.Storage
After processing, the data and information must be stored in the secondary storage device, so that
the data or information can be used later. The data and information can be stored permanently in secondary
storage devices (or auxiliary storage).
The computer memory is measured using BITS and Bytes.

iv. Accuracy
The computer generated results are exact and without any mistakes with high rate of consistency.

4
Fundamentals of Computers

v. Versatility
Computers seem capable of performing almost any task, provided that the task can be reduced
eÁw
to series of logical steps.

vi.Automation
A computer is much more than an adding machine, calculator or check-in/out system, all of which
require human operators to press the necessary keys for the operations to be performed. Once a program
is in the computer’s memory, the individual instructions are then transferred, one after the other, to the
control unit for execution. The processor/CPU follows these instructions until it meets a last instruction
which says stop program execution.

vii. Diligence
Being a machine, a computer does not suffer from the human traits of tiredness and lack of
concentration. For example, if 3 million calculations have to be performed, it will perform the 3 millionth
with exactly the same accuracy and speed as the first.

viii. Cost effectiveness


Computers reduce the amount of paper work and human effort, thereby reducing costs.

1.1.3 Data and Information


The term data and information are common terminology in the field of computers. Computers process
data into information.
Data is collection of unprocessed items, which can include text, numbers, images, audio and video.
We can also define data as collection of raw facts, figures, statistics which requires to be processed.
For example, “PARAM” 16.
The computer processed data is called the information, which conveys meaning and is useful to
people to take future decisions on the information.
For example, Name = “PARAM” AGE=16.

 Computers work through an interaction between hardware and software.


 The machine parts (physical parts) of the computer is called as hardware.
 The programs that tell computer what to do, how to do etc. is called as software.
Hardware refers to the parts of a computer that you can see and touch (physical components)
including the case and everything inside it. This part translates instructions and performs calculations.
Hardware items such as monitor, keyboard, mouse, printer, and other items are often calledhardware
devices, or devices.

5
Fundamentals of Computers

Figure 1.2 HARDWARE COMPONENTS

Common computer hardware components include a keyboard, mouse, microphone, scanner, Web
cam, printer, monitor, speakers, system unit, hard disk drive, external hard disk, optical disc drive(s),
USB flash drive, card reader/writer, memory cards, and modem.

Software
Software refers to the instructions, or programs, that tell the hardware what to do.
The two categories of software are system software and application software.
1. System software consists of the programs that control or maintain the operations of the computer
and its devices. System software serves as the interface between the user, the application software, and
the computer’s hardware.
2. Application software consists of programs designed to make users more productive and/or
assist them with personal tasks.

1.2 Functional components of a computer (working of each unit)


Basically any computer is supposed to carry out the following functions.
 Accept the data and program as input
 Store the data, program and retrieve as and when required.
 Process the data as per instructions given by the program and convert it into useful information
 Communicate the information as output

6
Fundamentals of Computers

Based on the functionalities of the computer, the hardware components can be classified into four
main units,
eÁw
namely input unit, processing unit, output unit, memory unit.
These units are interconnected by minute electrical wires to permit communication between them.
This allows the computer to function as a system.
Input Devices
An input device is any hardware component that allows you to enter data and instructions into a
computer. Some of the widely used input devices are the keyboard, mouse, microphone, scanner, and
Webcam.

Figure 1.3 Block diagram of computer

Central Processing Unit


CPU is the part of the computer that carries out the instructions of a computer program. It is the unit
that reads and executes program instructions. Hence it is known as the brain of the computer. It takes all
major decisions, makes all sorts of calculations and directs different parts of the computer function by
activating and controlling the operation. It consists of arithmetic and logic units, control unit and internal
memory (registers). The CPU controls and coordinates all the actions of the entire system. Programs
(software) provide the CPU, a set of instructions to follow and perform a specific task and communicate
between two or more components of the computer system. There is a pathway called as bus which
allows the data transfer between them. The CPU consists of storage or memory unit, Arithmetic Logic
Unit (ALU) and control unit.
a. Memory Unit: Memory unit is also known as the primary storage or main memory(RAM). It
stores data, program instructions, internal results and final output temporarily before it is sent to
an appropriate output device. It consists of thousands of cells called storage locations. These
cells activate with off-on or binary digits(0,1) mechanism. These bits are used to store instructions
and data by their combinations. The main memory holds data and program only

7
Fundamentals of Computers

temporarily(volatile-data/information will be lost when power off). Hence there is a need for
storage devices to provide backup storage.
b. Arithmetic and Logical Unit(ALU): ALU is the unit where all Arithmetic operations (addition,
subtraction, multiplication, division etc.) and logical functions such as AND, OR NOT are
performed. Non-numeric data results in true or false along with logical functions. Once data are
fed into the main memory from input devices, they are held and transferred as needed to ALU
where processing takes place. No process occurs in primary storage. Intermediately generated
results in ALU are temporarily placed in memory until needed at later time. Data may move
from primary memory to ALU and back again to storage many times before the process is
finalized.
c. Control Unit: It acts as a central nervous system and ensures that the information is stored
correctly and the program instructions are followed in proper sequence as well as the data are
selected from the memory as necessary. It also coordinates all the input and output devices of a
system. Control unit controls all the hardware operations i.e., those of input units, output units,
memory unit and the processor.

Storage Unit
Results obtained after processing will be in the primary memory, these data or information can be
stored in the storage device/secondary memory units. Secondary storage devices are called as auxiliary
memory devices. Secondary storage devices can hold more storage data than main memory and is less
expensive. This result or information can be copies to any storage medium and used in future.

Output Unit
An output device is any hardware component that conveys information to one or more people.in
user understandable form. Commonly used output devices are printer, monitor and speakers.

1.3 Evolution of Computers


Evolution of man and mankind has helped to invent a calculating tool. Early man used stones,
sticks, fingers, pebbles and cowries to count. Even today we calculate using our fingers. The limitations of
the ten fingers and ten toes apparently caused early man to construct a tool for calculations .Every civilization
have contributed calculating tool in their own methods/design. Mechanical counting devices were made.

8
Fundamentals of Computers

2500 BC – The Abacus


eÁw

Figure 1.4 Abacus

Abacus is the first known calculating machine used for counting. It is made of beads strung on cords
and is used for simple arithmetic calculations. The cords correspond to positions of decimal digits. The
beads represent digits. Numbers are represented by beads close to the crossbar (heaven and earth),
Abacus was mainly used for addition, subtraction and later for division and multiplication. The reason
for studying about abacus is, even today the complex calculations which are performed by advanced
computers are calculated using abacus.

1614 AD – Napier’s bones

Figure1.5 Napier’s bones

9
Fundamentals of Computers

The Napier’s bones was invented by John Napier, a Scottish mathematician as an aid to
multiplication. A set of bones consisted of nine rods, one for each digit 1 through 9 and a constant rod for
the digit ‘0’. A rod is similar to one column of a multiplication table.
1633 AD – The Slide Rule

Figure 1.6 Slide Rule


The Slide Rule was invented by William Oughtred. It is based on the principle that actual distance
from the starting point of the rule is directly proportional to the logarithm of the numbers printed on the
rule. The slide rule is embodied by the two sets of scales that are joined together, with a marginal space
between them. The suitable alliance of two scales enabled the slide rule to perform multiplication and
division by a method of addition and subtraction.
1642 AD – Adding Machine-Pascaline

Figure1.7 Adding machine

The Rotating Wheel Calculator was developed by a French philosopher, Blaise Pascal invented
the first mechanical calculator in 1641. It was named Pascaline. It had a box with eight movable wheels
called dials. The numbers for calculations were entered with dials. It could add, subtract, divide and
multiply the numbers as big as thousands. It was using simple components such as gears and levers. This
is a predecessor to today’s electronic calculator. He was inspired by the computation work of his father’s
job and devised the model. He was only 19 years old, when he devised this model.

Leibniz Calculator

Mathematician Gottfried Leibniz built a calculator in 1650 that could add, subtract, multiply and divide
the numbers.

Figure1.8 Rotating wheel calculator

10
Fundamentals of Computers

1801- Jacquard’s Loom


In 1801, Joseph Mary Jacquard invented a powered loom that used punched wooden cards to
eÁw
automatically weave incredibly detailed patterns including pictures and text. This can be taken as the first
“read only memory” device.

Figure 1.9 Power loom calculator

1822 –Charles Babbage: The Difference Engine

Figure 1.10 Difference Engine Figure 1.11 The Analytical Engine

Charles Babbage, British mathematician and engineer, designed an automatic calculating machine in
1822. He called it a Difference Engine. Later he thought of a mechanical construction which was known
as a mechanical-digital computer. Babbage called this Analytical engine. This analytical engine consisted
five units, which became the basic principles for the development of modern computer. Hence Charles
Babbage is rightly called the “Father of Computers”.

11
Fundamentals of Computers

1833-First Programmer

Figure 1.12 Lady Ada Lovelace

Lady Ada Lovelace, her mathematical genius came to light most strikingly in her work with Charles
Babbage. Babbage was pathway into the process of designing the first mechanical computer ( “Analytical
Engine”). She started writing the first computer algorithm, and she predicted that later computers’ will
have the abilities to do more than mathematical calculations. Lovelace realized that the Analytical Engine
was in essence, a machine for manipulating symbols and music notations .Ada called herself ( “an Analyst
& Metaphysician),”

Lady Ada Lovelace is the first programmer.

1890 AD - Hollerith Tabulating Machine

Fig. 1.13 Hollerith Tabulating Machine

In 1889, an American named Herman Hollerith invented a counting machine to count the population
of USA. This electronic machine is able to read the information on the punched cards and process it
electronically. It was one of the main electronic counting devices. It was based on punch cards. Herman
Hollerith was the founder of the company that became famous as IBM.

1.4 Generations of Computers


The evolution of electronic computers, over a period of time can be traced effectively by dividing
this period into various generations. Each generation is characterized by a major technological development

12
Fundamentals of Computers

that fundamentally, changed the way computers operated. These helped to develop smaller, economical ,
powerful, efficient and reliable devices.
eÁw

First Generation - 1940-1956: Vacuum Tubes

Figure 1.14 Vacuum Tube

The first generation of computers used vacuum tubes for switching circuits and magnetic drums for
memory. They were large in size, occupied a lot of space and produced enormous amount of heat. They
were very expensive to operate and consumed large amount of electricity. Most of the times the heat
generated caused the computer to malfunction. First generation computers operated only on machine
language. Input was based on punched cards, paper tapes and output was obtained as print out. First
generation computers could solve only one problem at a time.
In America, with the success of Aiken’s, Harvard Mark-I as the first major American development
in the computing race, work was proceeding on the next great break through by the Americans. Their
second contribution was the development of the giant ENIAC machine by John W Mauchly and J Presper
Eckert at the University of Pennsylvania.

Figure1.15 ENIAC

13
Fundamentals of Computers

ENIAC (Electrical Numerical Integrator and Computer) used a word of 10 decimal digits instead
of binary ones like previous automated calculators/computers. ENIAC also was the first machine to
use more than 2,000 vacuum tubes, using nearly 18,000 kms of wires. Space for all those vacuum tubes
and the machinery required to be keep cool and occupied up more than 167 square meters of floor
space. Nonetheless, it had punched-card input and output and arithmetically had 1 multiplier, 1 divider-
square rooter, and 20 adders employing decimal “ring counters”, which served as adders and also as
quick-access (0.0002 seconds) read-write register storage.

Figure1.16 EDVAC

EDVAC (Electronic Discrete Variable Automatic Computer) was to be a vast improvement upon
ENIAC. Mauchly and Eckert started working on it two years before ENIAC even went into operation.
Their idea was to have the program for the computer stored inside the computer. This would be possible
because EDVAC was going to have more internal memory than any other computing device to date.
Memory was to be provided through the use of mercury delay lines. The idea being that given a tube of
mercury, an electronic pulse could be bounced back and forth to be retrieved at will another two state
device for storing 0’s and 1’s. This on/off switch ability for the memory was required because EDVAC
was to use binary rather than decimal numbers, thus simplifying the construction of the arithmetic units.
UNIVAC (UNIVersal Automatic Computer) was the first commercial computer produced in the
United States.

Second Generation - 1956-1963: Transistors

Figure1.17 Transistor

14
Fundamentals of Computers

The second generation of computers witnessed the vacuum tubes being replaced by transistors.
The transistor
eÁw was far superior to the vacuum tube, allowing computers to become smaller, faster, economical
energy-efficient and more reliable than their first-generation computers. The transistors also generated
considerable heat that sometimes caused the computer to malfunction. But it was a vast improvement
over the vacuum tube. Second-generation computers used punched cards for input and printouts for
output.
Second-generation computers moved from the use of machine language to assembly languages,
which allowed programmers to specify instructions in words. High-level programming languages were
also being developed at this time, such as early versions of COBOL and FORTRAN. The computers
stored their instructions in their memory, which moved from a magnetic drum to magnetic core technology.
Third Generation - 1964-1971: Integrated Circuits

Figure1.18 Integrated Circuit

The development of the integrated circuit(IC's) left its mark in the third generation of computers.
Transistors were made smaller in size and placed into silicon chips, which dramatically increased
the speed and efficiency of computers. In this generation, keyboards and monitors were used instead of
punched cards and printouts. The computers were interfaced with an operating system which allowed to
solve many problems at a time. Some of the LSIC's and VLSIC's were used.
Fourth Generation - 1971-Present: Microprocessors

Figure 1.19 Microprocessor

The microprocessor brought forth the fourth generation of computers, as thousands of integrated
circuits were built onto a single silicon chip. As these small computers became more powerful, they could
be linked together to form networks, which eventually led to the development of the Internet.

15
Fundamentals of Computers

Fifth Generation - Present and Beyond: Artificial Intelligence (ROBOTICS)

Figure1.20 Robotics

Fifth generation computing devices, based on artificial intelligence, are still in their developmental
stage. Fifth generation computers will come close to bridge the gap between computing and thinking.

1.5 Classifications of Computers


Classification of the electronic computers may be based on either their principles of operation or
their configuration, by configuration; we mean the size, speed of doing computation and storage capacity
of a computer.

1.5.1 Classification based on Principles of Operation


Based on the principles of data handling, computers are classified analog, digital or hybrid.
Analog Computer is a computing device that works on continuous range of values, with a minimum
value and maximum value. At a given point of time any value can be attained which is dependent on the
pervious value .The analog computers give approximate results since they deal with quantities that
vary continuously. To represent an analog graph there must be two quantities.

16
Fundamentals of Computers

Digital computers are those that operate with information, numerical or otherwise, represented in a
digital form.
eÁw
Such computers process data into a digital value (in 0s and 1s). They give the results with
more accuracy and at a faster rate.
Hybrid computers incorporate the measuring feature of an analog computer and counting feature of
a digital computer. For computational purposes, these computers use analog components and for storage,
digital memories are used.

Analog Computers

Figure1.21 Analog Graph with two parameters time and temperature

Analog computers work on the principle of measuring, in which the measurements obtained are
translated into data rather than counting. The analog computers are that all calculations take place in
parallel, hence faster. Modern analog computers usually employ electrical parameters, such as voltages,
resistances or currents, to represent the quantities being manipulated. Such computers do not deal directly
with the numbers. They measure continuous physical magnitudes. It generally deals with physical variables
such as voltage, pressure, temperature, speed etc.,

Digital Computers

Figure1.22 Digital Graph with 0’s and 1’s

Digital computers are those that operate with information, numerical or otherwise, represented in a
digital form. Such computers process data into a digital value (in 0s and 1s). They give the results with
accuracy and at a faster rate, On the other hand a digital computer operates on digital data such as
numbers. It uses binary number system in which there are only two digits 0 and 1. Each one is called a bit.
All the data representation will be in the series of 0’s and 1’s. Not dependent of time of other values.
Digital computers are unique. The digital computer is made for both general purpose and special purpose.
Special purpose computer is one that is built for a specific application.

17
Fundamentals of Computers

General purpose computers are used for any type of applications. It can store different programs
and do the jobs as per the instructions specified on those programs. Most of the computers used are
digital computers.

Hybrid Computer (Analog + Digital)


A combination of computers those are capable of accepting inputs and outputs in both digital and
analog signals. A hybrid computer system setup offers a cost effective method of performing complex
simulations.
A hybrid computing system is a combination of desirable features of analog and digital computers. It
is mostly used for automatic operations of complicated physical processes and machines. Now-a-days
analog-to-digital and digital-to-analog converters are used for transforming the data into suitable form for
either type of computation.
For example, in hospital’s automated intensive care unit, analog devices might measure the patient’s
temperature, blood pressure and other vital signs. These measurements which are in analog might then be
converted into numbers and supplied to digital components in the system. These components are used to
monitor the patient’s vital sign and send signals if any abnormal readings are detected. Hybrid computers
are mainly used for specialized tasks.

Figure1.23 Hybrid with Analog and Digital signal ECG of a person

1.5.2 Classification of Computers based on Configuration


Based on performance, size, cost and capacity, the digital computers are classified into four different
types: Microprocessor, Minicomputer, Mainframe computer and Super computers.

1.5.2.1 Micro Computers

Fig. 1.24 Desktop Model computer

18
Fundamentals of Computers

Micro computer is also called personal computer. It was introduced in 1970. The number of processors
in microcomputers
eÁw
will be one or two processors. It contains input devices, output device, storage
device, memory and processor. It is used by one person at a time. Examples of personal computers are
PC and Apple Macintosh. The major types of personal computers are desktop computer and portable
computer.

Desktop computers
These computers can easily fit on a table or desktop, hence the name. These computers come in two
models or casings. In Desktop model, the system unit is placed on the desktop or table. Monitor is placed
on the system unit. In Tower model, both monitor and system unit are placed on the table.

Figure 1.25Tower Model computer

Portable Computers
Portable is a personal computer that can be carried from one place to other easily. Notebook
computer and handheld computer (smart phone) are examples of portable computers. Notebook
computer is also called laptop computer. Laptop computers are very small in size and can be placed
easily on lap.

Figure 1.26 Lap top computer or notebook computer

19
Fundamentals of Computers

Hand held computer

Figure. 1.27Hand held computer

Handheld Computers (like smart phone) are also portable. Handheld computer is also known as
palmtop computer. It easily fits in the hand of the user.
Uses of Micro Computer The PC is the most common type of computer used in the office. It is
now widely used in many homes. These are also used for business and engineering application.

1.5.2.2. Mini Computers


Mini computers were introduced in the 1960s. Minicomputer is larger and more powerful computer
than personal computer. It can execute five million instructions per second. It generally consists of two or
more processors.

Figure1.28Mini Computers

Mini computer can serve up to 4000 connected users simultaneously. It is normally accessed by
users via personal computer or terminal. A device with a monitor and keyboard is called terminal. It is also
known as dumb terminal. It has no processing power and cannot work as stand-alone computer. Examples
of mini computers are: VAX-8800, AS 400.

20
Fundamentals of Computers

Uses ofeÁw
Mini Computers:
Mini computers are often used by small and medium-sized companies to provide centralized store of
information.
1.5.2.3. Mainframe Computers
Mainframe computers were introduced in 1975. A mainframe computer is a very large computer in
size. It is more powerful than minicomputer. It consists of multiple processors. It is designed to perform
multiple tasks for multiple users at the same time. Mainframe computers can serve up to 50,000 users at
the same time.

Fig. 1.29 Mainframe Computers

The users access a mainframe computer through terminal or personal computer. A typical main
frame computer can execute 16 million instructions per second. Examples of mainframe computers
are NEC610, DEC 10.

Uses of Mainframe Computers


Mainframe computers are used in large organizations. For example, airlines use these computers
for ticket reservation system. IBM's offering z -series mainframe. The server-dominated have presented
its own challenges of cost, complexity and security. Indian companies are looking for a more responsive
and dynamic environment and mainframe are increasingly being considered. This company machines are
used by RBI, HDFC, TCS, HCL, Wipro, NSDL are come of clients. Clients face rising energy and
cooling cost, limited floor space and manpower concerns required to man servers. NADRA - The
Computerized National Identity Card Issuer in Pakistan - uses mainframe computers to maintain the
information of population.

21
Fundamentals of Computers

1.5.3.4. Super Computers

Figure 1.30 Super computer

Super computers were introduced in 1980s. Super computer is the fastest computer. Super computer
is the biggest in size and the most expensive in price than any other computers.
Tata’s Eka supercomputer in Pune’s Computational Research Laboratories (CRL) remains the
fastest Indian supercomputer, its top performance of 132.8 teraflops remaining unchanged. However,
shifting goal posts in high performance computing technology sees the Eka slip from no. 18 to no. 26 in
the list.
The government-run Centre For Development of Advanced Computing (C-DAC) also
headquartered in Pune, sees its Param Figure 1.30. Super computers Yuva machine at no. 137 in the
latest ratings announced November 17. Its speed is in fact a bit faster than before — 38.1 teraflops —
but its rank is now 137, down from 109 in June.
Super computer is the most sophisticated, complex and advanced computer. It has a very large
storage capacity. It can process trillions of instructions in one second. Super Computer is the fastest and
most powerful computer of a time. Super computers are very expensive. Super computers are used for
highly calculation intensive tasks. Super computers are used for specialized applications that require immense
amounts of mathematical calculations. Super computers were designed primarily by computer scientist -
Seymour Cray at Control Data Corporation (CDC).
Uses of Super Computers include:
1. Weather forecasting
2. Animated graphics like in Hollywood movies
3. Fluid dynamic calculations
4. Nuclear energy research
5. Space science
6. Weapon and missile design
7. Petroleum exploration etc.

22
Fundamentals of Computers

Today, supercomputers are produced by traditional companies such as Cray, IBM and Hewlett-
Packard,
eÁw
who had purchased many of the 1980s companies to gain their experience. Since October
2010, the Tianhe-1A super computer has been the fastest in the world; it is located in China.
The main difference between a Supercomputer and a mainframe is that a Supercomputer channels all
its power into executing a single program as fast as possible, whereas a mainframe uses its power to
execute many programs concurrently. The modern super computer consists of thousands of
microprocessors. Super computer uses high-speed facilities such as satellite for online processing. Examples
of Super computers are CRAY-XP, ETA-10, and Deep Blue and above all today’s number one super
computer is Tianhe-1A supercomputer of China. Aircraft companies use super computer to simulate
aircraft and check its performance. Computers differ based on their data processing abilities. They are
classified according to purpose, data handling and functionality.

1.6 Applications of computers


The uses of computers can be classified into the area of usage.
Schools and colleges: Computers are implemented in the schools for the creation of school ID
card, (some schools have smart card with the IC’s embedded) which contains the details of the student.
The creation of marks card, attendance, learning the subject with audio and video and fees collection so
on are the few examples.
Banks : The computers are used in the creation of account in the bank, transactions, transfer of
funds, alert messages, transaction messages, used of banking with ATM (Automatic Teller Machine) card
which can be accessed any part of the globe, Online banking etc.
Office: Used in documentation of the transactions, events that are carried out every day along with
the money, funds transactions, payroll for all the events either in the form of letters or specific application
software are used, payroll for employee, audit etc.,
Stock control in business firms: Computers are used in the shops and business for the stock
account of the movements of the items in business and the money transactions along with the shipping of
the items with the quantity price and quality expiry date ,the tracing of the product at any given point of
time etc.,
Stock Exchange: To check the stock exchange globally, transaction of sell and buying of the stock
can be done with the help of computers, stock exchange members carry out the transactions only with the
help of computers, and online trading is carried throughout the world, sitting at one place.
Research and developments : The new invention are designed and implemented with the animated
virtual viewed with scientific and mathematical equations in the labs , with the help of computers and
models are implemented in the real world which saves time, resource, money etc.,
Entertainment and NEWS : The audio and video are created in the studio after the pictures is
taken the editing process(cloning, merging of sound and images, super impose etc.,) is carried out
simultaneously. NEWS are telecasted live and immediately.
Governments office: All the transactions of the government, law and information are been obtained
in the websites of the government.
23
Fundamentals of Computers

Satellite Communications: With the venture of satellite the communication are made
available to the entire world. This have led to the
growth of the information and technological globally
and every country is implementing the standardized,
so that the communication is at its ease.
Usage: Browsing, Surfing, Chatting, email,
Messaging, online gaming are some of the area of
communications.
Figure 1.31. Internet Communications

Publishing: Publishing is the process of making works available to the public. These works
include books, magazines, newspapers, music, film, and video. Special software assists graphic designers
in developing pages that include text, graphics, and photos; artists in composing and enhancing songs;
filmmakers in creating and editing film; and journalists and mobile users in capturing and modifying video
clips. Many publishers make their works available online. Some Web sites allow you to copy the work,
such as a book or music, to your desktop computer, mobile computer, smart phone, or other mobile
device.
Travel: Whether traveling by car or airplane, your goal is to
arrive safely at your destination. As you make the journey, you may
interact with some of the latest technology. Vehicles manufactured
today often include some type of onboard navigation system, such
as INDIAMAP. Many mobile devices such as smart phones have
built-in navigation systems. Some mobile users prefer to carry
specialized hand held navigation devices. In preparing for a trip, you
may need to reserve a car, hotel, or flight. Many Web sites offer
these services to the public. For example, you can order airline tickets Figure 1.32. Travel Karnataka Map
on the Web. If you plan to drive somewhere and are unsure of the road to take to your destination, you
can print directions and a map from the Web.

Computer-aided manufacturing (CAM) refers to the use of computers to assist with manufacturing
processes such as fabrication and assembly. Industries use CAM
to reduce product development costs, shorten a product’s time
to market, and stay ahead of the competition. Often, robots carry
out processes in a CAM environment. CAM is used by a variety
of industries, including oil drilling, power generation, food
production, and automobile manufacturing. Automobile plants,
for example, have an entire line of industrial robots that assemble
a car and special computers on the shop floor record actual
Figure 1.33 CAM labor, material, machine, and computer time used to manufacture
a product. The computers process this data and automatically
update inventory, production, payroll, and accounting records on the company’s network.

24
Fundamentals of Computers

Hospitals: The patients id card, details, help in diagnosing


(MICR,eÁw
CEG, Scanning etc.), medication and history of patients
are maintained. These are few areas were data and information
are obtained with the help of computers, have made the right
impression for the betterment of man and mankind.

Figure 1.34. Hospital with Life saving computer controls

Area of usage and specifications of hardware and software

Area of usage Hardware Software

Home Desktop or notebook computer Business (e.g., word processing) Personal


Smart phone or other mobile device information manager Personal finance, online
Game consoles banking, tax preparation Web browser E-mail,
blogging, instant messaging, chat rooms, and
online social networking Internet telephone calls
Photo and video editing Reference (e.g.,
encyclopedias, medical dictionaries, road atlas)
Entertainment (e.g., games, music composition,
greeting cards) Education (e.g., tutorials,
children’s math and reading software)

Small Office/ Desktop or notebook computer Business (e.g., word processing, spreadsheet,
Home Office Smart phone or other mobile device database) Personal information manager
Shared network printer Company specific (e.g., accounting, legal
reference) Network management Web browser
E-mail Internet telephone calls

Enterprise Server or mainframe Desktop or Business (e.g., word processing, spreadsheet,


notebook computer Industry- database)Personal information manager
specific handheld computer Smart Accounting Network management, Web
phone or other mobile device browser E-mail, Blogging, Specific database

SCHOOLS & Desktop or notebook computer Business (e.g., word processing, spreadsheet,
COLLEGES Smart phone or other mobile device database)Personal information manager
Shared network printer Accounting Network management Web
browser, E-mail, Blogging

Hospitals Desktop or notebook computer Business (e.g., word processing, spreadsheet,


Smart phone or other mobile device database) Personal information manager
Shared network printer Company specific (e.g., accounting, legal
reference) Network management Web browser
E-mail Internet telephone calls
25
Fundamentals of Computers

Area of usage Hardware Software

Traffic Desktop or notebook computer Business (e.g., word processing, spreadsheet,


Network Smart phone or other mobile device database)Personal information manager
Shared network printer Accounting Network management Web
browser E-mail Blogging Specific database –
fine details

26
Fundamentals of Computers

Review Questions
eÁw questions :
One mark
1. What is a computer ?
2. What are advantages of learning computers?
3. Which is the earliest computing machine?
4. Who invented the Pascaline?
5. What are the advantages of the machine by Leibnitz over the Pascaline?
6. What is Charles baggage known as?
7. What is the machine proposed by Babbage, to perform differential equations called as?
8. Who is the father of computers?
9. What concept of computing did Herman Hollerith to find a faster way to compute U.S. census.
10. Who developed the first all-electronic computer?
11. What us the electronic relay computer Mark-I also called as?
12. Expand the term ENIAC?
13. Expand the term EDVAC.
14. What is the Von Neumann concept also called as?
15. Expand the term UNIVAC.
16. Which is the basic electronic component of the first generation systems?
17. Which is the basic electronic component of the second generation systems?
18. What does IC stand for?
19. How internet is used ?
20. How computer help in publishing?

Two Marks Questions:


1. What are the fields where computers are used today?
2. Write a note on Abacus?
3. Write a note on Pascaline?
4. Explain the important features of difference engine.
5. Explain Charles Babbage’s role in the history of modern computers?
6. Mention any two features of ENIAC?
7. Mention any two features of EDVAC?
8. What are the importance features of the III generation computers?
9. Explain the role of computers in education?
10. Why are computer used in the industry?
11. How are computers important in communication?

27
Fundamentals of Computers

Three marks questions:


1. Briefly explain the history of computers
2. Give the features of the Generations
3. Explain the importance and usage of computers in education and industry
4. Discuss the characteristics of a computer in detail.
5. Explain the functional units of a computer with a neat block diagram?
6. Explain the role of computers in science and engineering?
7. Explain the latest implementation of computers?
8. How does the computer help mankind?
9. What is the concept of e-governance?
10. Explain the use of computer in the email?

Five marks questions:


12. Explain generations of computers in details.
13. Which are the areas computer have proved its effective?
14. In the field of communication computer are the best? Why?
15. What are the latest development in the file of computers list the areas and explain.
16. Explain the robotics in detail.
17. Compare the features of micro and mini computers?
18. Compare mainframe and supercomputers

Activities: a. Collect the images of personalities in the fields of computers.


b. Area where computer are not used.
c. Making charts for the known area.

28
eÁw

CHAPTER 2
INPUT OUTPUT MEMORY DEVICES

OBJECTIVES
 To identify the types and purposes of specialized input devices
 Output devices
 Memory devices
 Storage devices
 Cache Memory

29
30
Input output Memory Devices

eÁw

2.1 Input Devices


An input device is used to feed data into a computer. The human understandable form (usually
English/Kannada or any other language) is converted into machine understandable form 0’s and 1’s (digital
or analog signals). Input devices are capable of converting data into a form which can be recognized by
computer. A computer can have several input devices. Namely Keyboard, Mouse, Joystick, OCR, MICR
etc.
Ø Input and output devices connect the external world to the computer system.

2.1.1 Keyboard

Figure 2.1 Keyboard

The most common input device is the keyboard. Keyboard consists of a set of typewriter like
keys that enable you to enter data into a computer. They have alphabetic keys to enter letters, numeric
keys to enter numbers, punctuation keys to enter comma, period, and semicolon etc., functional keys
to perform some specific functions. The keyboard detects the key pressed and generates the corresponding
ASCII codes which can be recognized by the computer.

Standard Ergonomic Wireless Virtual Compact

Figure 2.2 Types of keyboard

31
Input output Memory Devices

Standard keyboards have their basic layout. The average number of keys on a regular keyboard
is 105/108, though range of 95-108 slight variations, especially in the manner the keys are placed. QWERTY
keyboards are the most common and have the six alphabets Q, W, E, R, T, and Y in the first row.
Ergonomics refers to the study of methods that can reduce stress on muscles to avoid repetitive
strain injury. It mostly deals with optimizing posture and technique while working, so the work can be
carried out in the easiest manner with the least possible strain on any muscle joint or organ. Ergonomic
keyboards are designed in such a way that typing can be done putting the least amount of stress on the
fingers and wrist. This is a radical type of keyboard designed to prevent Carpal Tunnel Syndrome.
Wireless Keyboard is a keyboard that does not need to be connected to the computer via a wire.
This makes it very convenient for the user to use the keyboard comfortably. Wireless keyboard use
Bluetooth, Infrared (IR), and Radio Frequency to connect to the computer with the help of batteries and
transmitted and receiver with the range 1 to 40 feet distance contact between the computer and the
keyboard type very ineffective.
Virtual keyboards are software devices that let you input data just like a hardware keyboard. They
open up as an application and can be controlled by a mouse or via a touch screen. They are mainly used
in devices which do not necessarily require a keyboard, like a tablet or a smart-phone. They are useful as
they aid in making the size of the device smaller. Virtual keyboards are also used in situations concerning
security, as anything entered on an ordinary keyboard is recorded in a key log, leading to security risks
associated with passwords or PIN numbers. This is the reason many banks provide the facility of a virtual
keyboard in their online banking operations.
Compact keyboards are slim and usually do not have the numeric keypad that is present on the
right side of other keyboards. These are typically used in laptops, where sizing issues make it difficult to
accommodate a standard keyboard. To make up for the small size, these keyboards rely on the use of
multiple keys to carry out functions that would only use a single key on a standard-sized keyboard. Some
models also include a touch-pad that can be used instead of the mouse. These are not extremely small in
size, but offer portability during travel and storage. Another benefit of compact keyboards is that they can
be used by people with certain disabilities that hinder them from effectively using hand and finger movements.

2.1.2 Mouse
Mouse is an input device that controls the movement of the cursor on the display screen. The display
screen is map in the form of graphical points dot is called pixels. The number of pixels differs depending
upon the resolution of the screen. Mouse is a small device; you can roll/navigate along a flat surface. In a
mouse, a small ball/ IR rays is kept inside and touches the pad through a hole at the bottom of the mouse.
When the mouse is moved, the ball rolls/position on the screen. This movement of the ball/position is
converted into signals and sent to the computer. You will need to click the button at the top of the mouse
to select the option. Mouse pad is a pad over which you can move a mouse. Mouse is very popular in
modern computers.

32
Input output Memory Devices

eÁw

Manual mouse RJ Scroll Mouse USB mouse Wireless mouse

Figure 2.3 Types of Mouse

2.1.3 Joystick
A joystick is an input device consisting of a stick that pivots on a base and reports its angle or
direction to the device it is controlling.

Video game joystick elements: The movements of the joystick is been identified
1. Stick 2. Base 3.Trigger 4. Extra buttons 5. Auto with the axis form x, y and z with three
fires switch 6. Throttle 7. Tat switch (POV hat)

Figure 2.4 Joystick

Joysticks are often used to control video games, simulated programs, usually have one or
more push-buttons whose state can also be read by the computer. A popular variation of the
joystick used on modern video game consoles is the analog stick. Joysticks are also used for
controlling machines such as cranes, trucks, underwater unmanned vehicles, surveillance cameras
and zero turning radius lawn mowers. Miniature finger-operated joysticks have been adopted as
input devices for smaller electronic equipment.

2.1.4 OMR, OCR and MICR


Optical reading of the pictures, symbols and shapes are scanned with the help of laser beam,
usually the position is pre-programmed, accessed and documented instantly.

33
Input output Memory Devices

i. Optical Mark Reading and Recognition (OMR)


Special pre-printed forms are designed with boxes which can be marked with a dark pencil or ink. Such documents
are read by a reader, which transcribes the marks into electrical pulses which are transmitted to the computer. They
are widely used in applications like objective type answer papers evaluation in which large number of candidates
appear, time sheets of factory employees etc.

ii. Optical Character Recognition (OCR)

Figure 2.6 OCR Sheet

The OCR technique permits the direct reading of any printed character without any special ink. With
OCR, a user can scan a page from a book. The computer will recognize the characters in the page as
letters and punctuation marks, and stores. This can be edited using a word processor the size (width,
height and depth) of the scanned.

34
Input output Memory Devices

iii. Magnetic Ink Character Recognition (MICR)


eÁw

Figure2.7 MICR Cheque

MICR is widely used by banks to process cheques. Human readable numbers are printed on
documents such as cheque using a special magnetic ink. The cheque can be read using a special input unit,
which can recognize magnetic ink characters. This method eliminates the manual errors. It also saves time,
ensures security and accuracy of data.

2.2 Introduction to output devices


Output is the result/information that is obtained after processing. The information must be presented
in the human understandable form (usually from 0’s and 1’s to English/Kannada or any other language) is
capable of presenting information on to the output devices. There are many output devices attached with
the computers. The monitors and printers are commonly used output devices.

2.2.1 Monitors
Monitor is a commonly used output device, sometimes called as display screen/Visual display unit
(VDU). It provides a visual display of data. Monitors are connected with the computer and are similar in
appearance to a television set.

Figure 2.8 Monitor

35
Initially there were only monochrome monitors. But gradually, we have monitors that display colour.
Monitors display images and text. The smallest dot that can be displayed is called a pixel (picture element).
The resolution of the screen improves as the number of pixels is increased. Most of the monitors have a
4:3 width to height ratio. This is called ‘aspect ratio’. The number of pixels that can be displayed vertically
and horizontally gives the resolution of the monitor. The resolution of the monitor determines the quality
of the display. Some popular resolutions are 640x480 pixels, 800x600 pixels and 1024x768 pixels. A
resolution of 1024x768 pixels will produce sharper image than 640x480 pixels. The size of the monitor
is measured diagonally may be 12",14",17",19", 21" and based on technology.

CRT LCD TFT LED


Cathode ray tube Liquid Crystal Display Thin Film Transistors Light Emitting
diode

Figure 2.9 Types of Monitors


2.2.2 Printers
Printer is an output device that prints text or images on paper or other media (like transparencies). By
printing you create what is known as a ‘hard copy’. There are different kinds of printers, which vary in
their speed and print quality.
The two main types of printers are impact printers and non-impact printers.

PRINTERS
IMPACT NON-IMAPACT

LINE PRINTER DOT MATRIX INKJET LASER THERMAL

Figure2.10 Types of Printers


Impact printers include printers that print by striking device against inked ribbon. Impact printers
use a print head containing a number of metal pins, which strike an inked ribbon placed between the print
head and the paper. Line printers, dot-matrix printers are some of the impact printers.

Ø The programs and data present in the memory is called as soft copy.
Ø The programs and data present on the paper is called as hard copy.

36
Input output Memory Devices

2.2.2.1 Characteristics of impact printers


Ø eÁw
In impact printers, there is physical contact with the paper to produce an image. Due to being
robust and low cost, they are useful for bulk printing.
Ø Impact printers are ideal for printing multiple copies (that is, carbon copies) because they can
easily print through many layers of paper.
Ø Due to its striking activity, impact printers are very noisy.
Ø Since they are mechanical in nature, they tend to be slow.
Ø Impact printers do not support transparencies.
Ø Measured with characters per seconds (cps).

2.2.2.2 Characteristics of Non-impact printers


Non-impact printers do not use striking device, the ink or semi-solid ink is stored in the printer
cartridges and the flow of ink is controlled by the processors which is much faster and can print colour,
different font and size also.
Ø They are quiet than impact printers because there is no striking mechanism involved.
Ø They possess the ability to change type faces automatically.
Ø These printers produce high-quality graphics
Ø These printers usually support the transparencies
Ø These printers cannot print multi part forms because no impact is being made on the paper.
Ø Measured in dots per inches (dpi)
Ø The speed is calculated by the number of pages per minute (ppm)
Ø The size of the printing various A4, A3, A2, A0 and Jumbo size.

2.2.2.3 Line Printer


Line printers are high-speed printers capable of printing an entire line at a time. A line printer can
print 150 lines to 3000 lines per minute. The limitations of line printer are they can print only one font, they
cannot print graphics, the print quality is low and they are noisy to operate. But it can print large volume
of text data very fast compared to the other printers. It is also used to print on multi part stationeries to
prepare copies of a document.

Figure 2.11 Line Printer

37
Input output Memory Devices

2.2.2.4 Dot Matrix Printer


The most popular serial printer is the dot matrix printer. It prints one line of 8 or 14 points at a
time, with print head moving across a line. They are similar to typewriters. They are normally slow. The
printing speed is around 300 characters per second. It uses multi part stationeries to prepare copies of a
document.

Figure 2.12 Dot Matrix Printers

2.2.2.5 Thermal Printer


Thermal printers are printers that produce images by pushing electrically heated pins against special
heat-sensitive paper. They are inexpensive and used widely in fax machines and calculators.

Figure 2.13 Thermal Printer

Thermal printer paper tends to darken over time due to exposure to sunlight and heat. So the printed
matters on the paper fade after a week or two. It also produces a poor quality print.

2.2.2.6 Laser Printers


Laser printers use a laser beam and dry powdered ink to produce a fine dot matrix pattern. It can
produce very good quality of graphic images. One of the chief characteristics of laser printers is their
resolution – how many dots per inch (dpi) they lay down. The available resolutions range from 300 dpi at
the low end to around 1200 dpi at the high end.

38
Input output Memory Devices

eÁw

Figure 2.14 Laser Printer

2.2.2.7 Inkjet Printers


Inkjet printers use colour cartridges which combine magenta, yellow and cyan inks to create colour
tones. A black cartridge is also used for crisp monochrome output. Inkjet printers work by spraying
ionizing ink at a sheet of paper. Magnetized plates in the ink’s path direct the ink onto the paper in the
described shape.

Figure2.15 Inkjet Printer

2.2.2.8 Plotter Printers


Plotter is an output device that draws pictures on paper based on commands from a computer.
Plotters differ from printers in that they draw lines using a pen. As a result, they can produce continuous
lines, whereas printers can only simulate lines by printing a closely spaced series of dots. Multicolor
plotters use different-colored pens to draw different colors.

In general, plotters are considerably more expensive than printers. They are used in engineering
applications where precision is mandatory.

39
Input output Memory Devices

2.2.3 Speakers
The speakers are the output units. The sound signals from analog/digital are converted into audible
frequency in the speakers and produce voice output (audio data). Using speakers along with speech
synthesizer software, the computer can provide voice output. Voice output has become very common in
many places like airlines, banks, automatic telephone enquiry system etc. Users can also hear music/
songs using the voice output system. The advance in the development of the speakers are given rise to the
track system of output sound based on the position of the speakers and the numbers of tracks output.
Namely 2.1 or 5.1 which indicates the position of the speakers and tracking systems. The latest speakers
are crystal clear audio. Walkman speakers are smaller in size with less watts and disables. Today the
speakers are with the subwoofer and 2/3/4 speakers.

Figure 2.16 Speakers

2.3 Introduction to Memory devices


Memory is the most essential part of the computer. Memory is storage part of the computer. We
need memory to store the data. This storage enables us to use the stored data to in future. Computer
memory is mainly divided as primary memory and secondary memory.
The memory and storage devices are measured in terms of bits and bytes, the measurements in
used are 0 ,1 binary digit (bit).
8 bits make a byte.2*2*2*2*2*2*2*2*2*2=1024. 210
210 bytes 1024 bytes 1 Kilo byte
20
2 bytes 1024 Kilo bytes 1 Mega byte
230bytes 1024 Mega bytes 1 Giga byte
240bytes 1024 Giga bytes 1 Terra byte
250bytes 1024 Terra bytes 1 Peta byte
60
2 bytes 1024 Peta bytes 1 Exa byte
270bytes 1024 Exa bytes 1 Zeta byte
280bytes 1024 Zeta bytes 1 Yotta byte
90
2 bytes 1024 Yotta bytes 1 Bronto byte
2100bytes 1024 Bronto bytes 1 Geop byte

Table 1.0
Units of Measurements in computer for Primary Memory and secondary memory

40
Input output Memory Devices

2.3.1 Primary Memory


Memory
eÁw units are the storage areas in the computer. The term "memory" usually refers to the main
memory of the computer, whereas the word “storage” is used for the memory that exists on disks, CD's,
floppies or tapes. The main memory is usually called a physical memory which refers to the ‘chip’
(Integrated Circuit) capable of holding data and instruction.

Figure 2.17 Memory Unit

There are different types of memories: ROM and RAM

Figure 2.18 Different types of ROM

They are Read Only Memory (ROM), Programmable Read-Only Memory (PROM), Erasable
Programmable Read-Only Memory (EPROM), Electrically Erasable Programmable Read-Only Memory
(EEPROM).
Read Only Memory - ROM
In ROM, the information is burnt (pre-recorded) into the ROM chip at manufacturing time. Once data
has been written into a ROM chip, it cannot be erased but you can read it. When we switch OFF the
computer, the contents of the ROM are not erased, but remain stored permanently. ROM is a non-
volatile memory. ROM stores critical programs such as the program that boots the computer.
Programmable Read Only Memory - PROM
PROM is a memory on which data can be written only once. A variation of the PROM chip is that it is
not burnt at the manufacturing time, but can be programmed using PROM programmer or a PROM
burner. PROM is also a non-volatile memory.
Erasable Programmable Read Only Memory – EPROM
In EPROM, the information can be erased and re-programmed using a special PROM – programmer.
EPROM is non-volatile memory. A n EPROM differs from a PROM in that a PROM can be written to
only once and cannot be erased. But an ultraviolet light is used to erase the contents of the EPROM.

41
Input output Memory Devices

Electrically Erasable Programmable Read Only Memory – EEPROM


EEPROM is a recently developed type of memory. This is equivalent to EPROM, but does not
require ultraviolet light to erase its content. It can be erased by exposing it to an electrical charge. It is also
non-volatile in nature. EEPROM is not as fast as RAM or other types of ROM. A flash memory is a
special type of EEPROM that can be erased and re-programmed.
Random Access Memory - RAM
RAM is the most common type of memory found in the modern computers. This is really the main store
and is the place where the program gets stored temporary. When the CPU runs a program, it fetches the
program instructions from the RAM and carries them out. If the CPU needs to store the results of the
calculations it can store them in RAM. When we switch OFF a computer, whatever is stored in the RAM
gets erased. It is a volatile form of memory.

Figure 2.19 RAM

The main memory must store many data items and have some way of retrieving them when they are
needed. The memory can be compared to the boxes at a post office. Each box-holder has a box with a
unique number which is called its address. This address serves to identify the box. The memory has a
number of locations in its store. Each location in a memory has a unique number called its memory
address. This serves to identify it for storage and retrieval.
Operations on memories are called reads and writes, defined from the perspective of a processor
or other device that uses a memory: A write instruction transfers information from other device to memory
and a read instruction transfers information from the memory to other devices. A memory that performs
both reads and writes is often called a RAM.
In a computer system, the clock signal is an oscillating frequency used to coordinate interaction
between digital circuits. Simply put, it synchronizes communication. Digital circuits designed to operate
on the clock signal may respond at the rising or falling edge of the signal. SDRAM memory chips used
only the rising edge of the signal to transfer data, while DDRRAM transfers data on both the rising and
falling edges of the clock signal, making it essentially twice as fast as SDRAM. RAM speed works in
conjunction with the front side bus (FSB) of a computer system. The FSB is the two-way data channel
that sends information from the central processing unit (CPU) throughout the motherboard to the various
components, including the RAM, BIOS chips, hard drives and PCI slots.

42
Input output Memory Devices

Types ofeÁw
RAM

Figure 2.20 Types of RAM

EDO RAM (extended data output RAM)


EDO (extended data output) RAM is a type of random access memory (RAM) chip that improves
the time to read from memory on faster microprocessors such as the Intel Pentium. EDO RAM was
initially optimized for the 66 MHz Pentium.
Static random-access memory (SRAM) is a type of semiconductor memory that uses bi-stable
latching circuitry to store each bit. The term static differentiates it from dynamic RAM
(DRAM) which must be periodically refreshed. SRAM exhibits data remainence, but it is still volatile in
the conventional sense that data is eventually lost when the memory is not powered. FSB will be 166
MHz.
Double-Data-Rate Synchronous Dynamic Random Access Memory, better known as DDR
SDRAM or DDR RAM for short, is a type of very fast computer memory. It’s based on the same
architecture as SDRAM, but uses the clock signal differently to transfer twice the data in the same amount
of time.
DDR SDRAM at 400 MHz (DDR-400 or PC-3200)
DDR2 SDRAM at 800 MHz (DDR2-800 or PC2-6400)
DDR3 SDRAM at 1600 MHz (DDR3-1600 or PC3-12800)
Suppose a computer system has DDR memory, a Memory Divider of 1:1, a FSB operating at
200 MHz and a CPU multiplier of 10x. Then, the base memory clock will operate at (Memory Divider)
× (FSB) = 1 × 200 = 200 MHz and the effective memory clock would be 400 MHz since it’s a DDR
system (“DDR” stands for Double Data Rate; the effective memory clock speed is double the actual
clock speed). The CPU will operate at 10 × 200 MHz = 2.0 GHz. Using I/O bus frequency of 200 MHz
various types of DRAM will operate.

43
Input output Memory Devices

2.3.2 Secondary Memory


The computer may need to store data, programs etc., (because the primary memory is volatile).
Secondary storage is also called backup storage. Secondary storage can be used to transmit data to
another computer either immediately or a later time. This provides a mechanism for storing a large amount
of data for a long period of time. Some of the commonly used secondary storage devices are hard disks,
magnetic tapes, floppy disks and CD-ROM. To understand the physical mechanism of secondary storage
devices one must have basic knowledge of magnetism, electronics and electro mechanical systems. The
average time required to reach a storage location and obtain its contents is called its access time. In
electro mechanical devices with moving parts such as disks and tapes, the access time consists of a seek
time required to position the read write head to a location and transfer time required to transfer the data
to or from the device.

Figure2.21 Hard Disk Drive

Hard Disk
Hard disk is a magnetic disk on which you can store computer data. The hard disk is direct-access
storage medium. This means you can store and retrieve data randomly. Disk storage systems are essentially
based on magnetic properties. The magnetic disk consists of high speed rotating surfaces coated with a
magnetic recording medium. The rotating surface of the disk is a round flat plate. When writing data, a
write head magnetizes the particles on the disk surface as either north or south poles. When reading data,
a read head converts the magnetic polarizations on the disk surface to a sequence of pulses. The read and
write heads are generally combined into a single head unit. There may be more than one read/write head.
Data is arranged as a series of concentric rings. Each ring(called a track) is sub-divided into a number of
sectors, each sector holding a specific number of data elements (bytes or characters).

44
Input output Memory Devices

eÁw

Figure 2.22 A track subdivided into sectors

The smallest unit that can be written to or read from the disk is a sector. Once a read or write
request has been received by the disk unit, there is a delay involved until the required sector reaches the
read/write head. This is known as rotational latency, and on average is one half of the period of revolution.
The storage capacity of the disk is determined as (number of tracks * number of sectors * bytes
per sector * number of read/write heads). Thus, the data is stored as magnetized spots arranged in
concentric circles (tracks) on the disk. Each track is divided into sectors. The arrangement of tracks and
sectors on a disk is known as its ‘format’.
High data rates demand that the disk rotates at a high speed(about 80,000 rpm). As the disk rotates
read/write heads move to the correct track and fetch the desired data. The storage capacity of a hard disk
can be Gigabytes (GB). i.e. thousands of Mega bytes of information.

Magnetic Tape
This recording medium contains a thin tape with a coating of a fine magnetic strip, used for recording
digital data. The tape itself is a strip of plastic, coated with a magnetic recording medium. Bits are
recorded as magnetic spots on the tape along several tracks. Usually, seven or nine bits are recorded
simultaneously to form a character together with a parity bit. Read/write heads are mounted one in each
track so that data can be recorded and read as a sequence of characters.

Figure2.23 Magnetic Tape Reader

45
Input output Memory Devices

Data is stored in frames across the width of the tape. The frames are grouped into blocks or records
which are separated from other blocks by gaps. Magnetic tape is a serial access medium, similar to an
audio cassette, and so data cannot be randomly located. This characteristic has prompted its use in the
regular backing up of hard disks.

Floppy Disk

Figure2.24 Floppy Disk

The floppy drive uses a thin circular disk for data storage. It is a soft magnetic disk. It is a thin
magnetic-coated disk contained in a flexible or semi-rigid protective jacket. The disk rotates at 360rpm
(Rotations per minute). A read/write head makes physical contact with the disk surface. Data is recorded
as a series of tracks sub-divided into sectors. The floppy disks are usually 3.5" in size. However, older
floppy disks may be in use; these would be 5.25" in size or even 8" in size. A 3.5" floppy disk can hold
1.44 MB of data. Once data is stored on a floppy disk it can be ‘write protected’ by clicking a tab on the
disk. This prevents any new data being stored or any old data being erased. Disk drives for floppy disks
are called floppy drives. Floppy disks are slower to access than hard disks and have less storage capacity.
It is less expensive and is portable. It can be accessed randomly.

Optical Disk
Optical disks are the storage medium from which data is read and to which it is written by lasers.
The optical disk is random access storage medium; information can be easily read from any point on the
disk. CD-ROM stands for Compact Disk - Read Only Memory.

Figure 2.24 Compact Disk

46
Input output Memory Devices

It is now possible to have CD-ROMs where tracks of information can be written on to them by the
user. These
eÁw
are called read/write CD-ROMs and these are becoming a popular and economical method
of storage.

Optical track
Optical track is a recording unit of data on the disc. The information stored on CD-ROM is arranged
according to certain rules, and is shaped like an “Optical track”, called “light rail” in spiral shapes. The
data from the directory inside the CD-ROM (TOC, Table of Contents) is recorded in the starting address
of the number of consecutive logical sectors of an Optical track. The audio CD in a song is corresponding
to a light rail, therefore, there are many light rails. CD-ROM light rails are at most 99 in number. The
minimum length of each light rail is indicated by Time: 4 seconds, or 300 sectors. This value is sometimes
referred to as “threshold.” Less than 4 seconds, light rail, if it cannot be used as light rail, it might be a “bad
Optical track”. The depression part on the Optical track is called information pit and the flat part is called
land. Pit and land are used to record information.CD-R disc has been pressed with spiral groove, known
as the “pre-groove”, instead the pit of optical track. When burning, CD-R disc in a trench in an organic
dye laser irradiation, the formation of bubbles, this is the “pit”. Bubbles, once formed, will not be able to
restore the status quo, therefore, CD-R can only be written once. These “pit” and “land” is the signal after
“8-14 coded modulation” (EFM, Eight to Fourteen Modulation), plus three interval code could access
code to form inside the burning to disc. This treatment can guarantee the accuracy of reading.

Figure2.25 Optical track

DVD Digital Video Disc, that is, “digital video disc.” With the advances in optical disc technology,
it can not only store video program, but also store music, data, along with increased use, it will be this type
of CD-ROM referred to as “Digital Versatile Disc”, and the English name is the Digital Versatile Disc.

BLUE ray disk


Blue-ray Disc, referred as BD. BD disc features are: It consists of a thickness of 1.1mm of the
recording layer and a thickness of only 0.1mm composite made of a transparent protective layer. The
work of the shorter wavelength light source, in the recording layer surface can be comparable with the
operating wavelength of fingerprints, with storage capacity
Recording capacity 23.3GB/25GB/27GB

47
Input output Memory Devices

Portable storage device


A portable storage device (PSD) is a small hard drive designed to hold any kind of digital data. This is
slightly different from a portable media player, which stores and plays music and movies. Some are fixed
size hard drives of 256GB, 320GB,500Gb,1Tb,2Tb etc. Newer units are expandable using 2.5" laptop hard
drives, allowing for an unlimited storage capacity, which is useful for video and images. When travelling, a
portable storage device may be a useful alternative to backing up or purging memory cards if a computer
is unavailable for downloading.

Figure 2.25 Portable storage device

HDD F la s h D r iv e S e c u r e D is k U S B F lo p p y
2.3.3 Cache Memory

Figure 2.26 Cache memory


The cache is a small amount of high-speed memory, present between the primary memory and CPU
(processor). There are two levels of cache memory L1 and L2, L1 cache memory will present inside the
CPU, whereas the L2 cache will be present on the mother board, cache memory holds the most recent
data/instructions. Usually with a memory cycle time comparable to the time required by the CPU to fetch
one instruction. The cache is usually filled from main memory when instructions or data are fetched into
the CPU. Often the main memory will supply a wider data word to the cache than the CPU requires, to fill
the cache more rapidly. The amount of information which replaces at one time in the cache is called the
line size for the cache. This is normally the width of the data bus between the cache memory and the main
memory. A wide line size for the cache means that several instruction or data words are loaded into the
cache at one time, providing a kind of perfecting for instructions or data.

48
Input output Memory Devices

eÁw
Review Question
One mark questions:
1. What is PC?
2. What is the use of input unit?
3. What happens to the data in the input unit?
4. What is the use of memory?
5. What is ROM and RAM?
6. Classify various units of memory.
7. What is cache memory?
8. What does MOUSE stand for ?
9. What is MICR?
10. Define the resolution of a monitor
11. What is use of speakers?
Two marks questions:
1. Compare input and output units.
2. What is difference between volatile and non-volatile memory.
3. Compare static and dynamic Ram
4. Give different types of ROM.
5. Explain the different types of keyboard.
6. Give the difference between hard copy and soft copy.
7. Explain different types of printers.
8. Explain the structure of CD-ROM.
Three marks questions:
1. Write the difference between ROM and RAM.
3. Give the applications of OCR, OMR, and MICR.
4. Explain impact and non-impact printers in detail.
5. Explain the storage medium in detail.
Five marks questions:
1. Explain input unit in detail.
2. Explain output in detail.
3. Explain storage medium in detail.
4. Illustrate the latest configuration of computers for today.

49
50
eÁw

CHAPTER 3
DATA REPRESENTATION

OBJECTIVES
 To understand representation of data and information
 Number systems
 Conversions
 Basic operations

51
52
Data Representation

eÁw

3.1 Introduction
In digital computers, data and instructions are stored in the computer’s memory using binary code
(or machine code) represented by Binary digIT 's 1 and 0 called BITs. The data may contain digits,
alphabets or special character, which are then converted to bits, understandable by the computer. All
arithmetic operations are performed using binary bits. The study of different number systems is necessary
to understand data representation.
The number system uses well defined symbols called digits. The values of digits depend on the
position in which they appear in the number.
Number systems are basically classified into two types. They are,
1. Non-positional number system.
2. Positional number system.

3.2 Non-positional number system


In olden days people made use of this type of number system for simple calculations like additions
and subtractions. The non-positional number system consists of different symbols that are used to represent
numbers.
Roman number system is an example of the non-positional number system i.e. I=1, V=5, X=10,
L=50. Each of these symbols represents a value, irrespective of the positions. This number system
cannot be used effectively to perform arithmetic operations.

3.3 Positional number system


Decimal, Binary, Octal and Hexadecimal number systems are some of the examples of this type of
number systems.
The base or radix of a number system is the total number of digits present in that system.
Every number is represented by a base (or radix) x, which represents x digits. To determine the
quantity that the number represents, the number is multiplied by an integer power of x depending on the
position it is located and then finds the sum of the weighted digits.
The base or radix of a number system is the total number of digits present in any number system.
3.3.1 Decimal number system
This is the most commonly used number system in our daily life. It has 10 numbers from 0 to 9; hence
its radix is 10. The positional values are expressed in powers of 10.
Example 3.1 Consider a decimal number 542.76(10) which can be represented in equivalent value as:
5x102 + 4x101 + 2x100 + 7x10-1 + 6x10-2

53
Data Representation

Table 3.1 shows the weightage of the positional values of the decimal number:

Hundreds Tens Units One-tenth One-hundredth


Weights 102 101 100 10-1 10-2
Digits 5 4 2 7 6
Values 500 40 2 0.7 0.06

Table 3.1

3.3.2 Binary number system


The digital computers cannot process decimal numbers, hence it has to be converted to binary
digits 0 (low voltage) and 1 (high voltage), which is suitable to represent the bi-stable of electronic
components.
The representation of data in a computer is usually in binary digits 0 and 1. Hence the base is 2.
The positional values are expressed in powers of 2. It is very essential to know how to count a binary
number and also the conversion from binary to all other number systems.
E x a m p l e 3 . 2 C o n s i d e r a b i n a r y n u m b e r 1 1 0 1 1 . 1 0 1

(2)
which can be represented in equivalent
values:
1x24 + 1x23 + 0x22 + 1x21 + 1x20+1x2-1 + 0x2-2 + 1x2-3

Table 3.2 shows the weightage of the positional values of the binary number:

Weights 24 23 22 21 20 2-1 2-2 2-3


Bits 1 1 0 1 1 1 0 1
Values 16 8 4 2 1 0.5 0.25 0.125

Table 3.2

In the binary number 11010(2) the left most bit 1 is the highest order bit. It is called as the most
significant bit (MSB). Rightmost bit 0 is the lower order bit. It is called least significant bit (LSB).

3.3.3 Octal number system


Binary number representation generates long sequence of 1’s and 0’s, while representing
large decimal numbers. To overcome this problem, other number systems like octal and hexadecimal
number system is used which can effectively compress long strings of binary numbers.
The octal number system has 8 digits 0, 1, 2, 3, 4, 5, 6 and 7. Its radix is 8. The positional values
are expressed in powers of 8.

54
Data Representation

Example 3.3 Consider an octal number 234.56(8) which can be represented in equivalent value as:
eÁw 2x82 + 3x81 + 4x80 + 5x8-1 + 6x8-2

The table 3.3 shows the weightage of the positional values of the octal number:

Weights 82 81 80 8-1 8-2


Digits 2 3 4 5 6
Values 64 8 1 0.125 0.03125

Table 3.3

3.3.4 Hexadecimal number system


This number system has 16 digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F. The radix is 16.
The positional values are expressed in powers of 16. The digits A, B, C, D, E and F have the decimal
equivalents 10, 11, 12, 13, 14 and 15 respectively.
Example 3.4 Consider a hexadecimal number 5AF.D(16) which can be represented in equivalent
value as:
5x162 + Ax161 + Fx160 + Dx16-1

The table 3.6 shows the weightage of the positional values of the hexadecimal number:

Weights 162 161 160 16-1


Digits 5 A F D
Values 256 16 1 0.0625

Table 3.6

3.4 Number system conversions (All types)


In representing the data on computers we need to convert the data from one number system to
other number system. In this section we study the inter conversions of number systems.

3.4.1 Decimal to binary conversion:


Step1: Divide the given decimal number by 2
Step2: Note the quotient and remainder.
Step2: Repeat the step1 and step2 until the quotient becomes zero.
Step3: The first remainder will be the LSB and the last remainder is the MSB. The
equivalent binary number is then written from left to right i.e., from MSB to LSB.

55
Data Representation

Example 3.5 Consider the decimal number 53(10) which can be represented in binary as:

Therefore, 53(10) = 110101(2)

3.4.1.1 Decimal fraction to binary conversion:


Step 1: Multiply the decimal fraction by 2, note the carry and the product.
Step 2: Repeat Step1until the fractional product becomes zero.
Step 3: The first carry will be the MSB and the last carry is the LSB. The equivalent binary fraction
is then written from MSB to LSB ( right to left).

Example 3.6 Consider the decimal fraction 0.3125(10)

Multiply by 2 Carry Product


0.3125 x 2 0 (MSB) 0.625
0.625 x2 1 0.25
0.25 x 2 0 0.50
0.50 x2 1 (LSB) 0.00
0.00
Therefore, 0.3125(10) = 0.0101(2)

3.4.2 Binary to decimal conversion


Step1: Multiply each bit of the binary number by its positional weight.
Step2: Add all the products.
Example 3.7 Consider the binary number 11011.101(2) which can be represented in decimal value
as:
1x24 +1x23+ 0x22 + 1x21 + 1x20 + 1x2-1 + 0 x 2-2 + 1x2-3

56
Data Representation

The table 3.2 shows the weightage of the positional values of the binary number.
eÁw
Weights 24 23 22 21 20 2-1 2-2 2-3
Bits 1 1 0 1 1 1 0 1
Values 16 8 4 2 1 0.5 0.25 0.125
Table 3.2

Therefore, 11011.101(2) = 27.625(10)

3.4.3 Decimal to octal conversion


Step 1: Divide the given decimal number by 8
Step 2: Note the quotient and remainder.
Step 3: Repeat the step1 and step 2 until the quotient becomes zero.
Step 4: The first remainder will be the LSB and the last remainder is the MSB. The
Equivalent octal number is then written from left to right i.e. from MSB to LSB.

Example 3.8 Consider the decimal number 459(10)

Therefore, 459(10) = 713(8)

3.3.4 Octal to decimal conversion


Step 1: Multiply each digit of an octal number by its weight.
Step 2: Add all the products.

Example 3.9 Consider an octal number 234.56(8) which can be represented in decimal value as:
2x82 + 3x81 + 4x80 + 5x8-1 + 6x8-2

Table 3.3 below shows the weightage of the positional values of the octal number:

Weights 82 81 80 8-1 8-2


Digits 2 3 4 5 6
Values 64 8 1 0.125 0.03125
Table 3.3
Therefore, 234.56(8) = 156.71875(10)

57
Data Representation

3.3.5 Decimal to hexadecimal conversion


Step 1: Divide the given decimal number by 16.
Step 2: Note the quotient and remainder.
Step 3: Repeat step1and step2 until the quotient is becomes zero.
Step 4: The first remainder is the LSB and the last remainder is the MSB. The hexadecimal
number is written from left to right with MSB occurring first.

Example 3.10 Consider a decimal number 559(10)

Therefore, 559(10)= 22F (16)

3.3.6 Hexadecimal to decimal conversion


Step1: Multiply each digit of the hexadecimal number by its positional weight.
Step2: Add all the products.

Example 3.11 Consider a hexadecimal number 5AF.D (16) which can be represented in decimal
value as:
5x162 + A x 161 + F x 160 + D x 16-1

Table 3.6 shows the weightage of the positional values of the hexadecimal number:

Weights 162 161 160 16-1


Digits 5 A F D
Values 256 16 1 0.0625

Table 3.6
Therefore, 5AF.D (16) = 1455.8125(10)

3.3.7 Binary to octal conversion


In the given binary number, the binary digits are grouped into groups of three bits starting from the
binary point and convert each group into its equivalent octal number. For whole numbers, it may be
necessary to add a zero as the MSB. Similarly, when representing fractions, it may be necessary to add a
trailing zero in the LSB to complete grouping of three bits.

58
Data Representation

Adding a leading 0 as the MSB into the whole number and adding a 0 trailing 0 as the LSB into the
fractional
eÁw binary number does not change the value of the number.

Therefore, 0.110111(2) = 0.67(8)

3.3.8 Octal to binary conversion


The application of octal numbers is to represent binary numbers, as it is easier to read large numbers
in octal form than in binary form. Each octal digit is represented by a three-bit binary number as in table
3.4. Hence it is very easy to convert from octal to binary.

Octal digit Binary digit


0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111
Table 3.4

Example 3.14 Consider the octal number 456(8)


4 100
5 101
6 110
Therefore, 456(8) =100101110(2)

59
Data Representation

Example 3.15 Consider the octal number 73.16(8)


7 111
3 011
1 001
6 110
Therefore, 73.16(8) = 111011.001110(2)

3.3.9 Binary to Hexadecimal conversion


The binary bits are grouped into four bits starting from the binary point and replace each group
by a hexadecimal digit. For whole numbers, it may be required to add a zero as the MSB to complete a
group of four bits. Similarly, when representing fractions, it may be required to add a trailing zero as
the LSB to complete a group of four bits. This addition of zeros will not change the value of the
binary number.

Table 3.5 shows each hexadecimal number may be represented as a 4-digit number.

Decimal Binary Hexadecimal


0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F

Table 3.5

60
Data Representation

eÁw

3.3.10 Hexadecimal to binary conversion


Each digit of a hexadecimal number is replaced by a 4-bit binary number (Refer table 3.5).
Example 3.18 Consider a hexadecimal number CEBA (16)
C 12 1100
E 14 1110
B 11 1011
A 10 1010
Therefore, CEBA (16)=1100 1110 1011 1010(2)

3.3.11 Octal to Hexadecimal conversion


Using binary system, we can easily convert octal numbers to hexadecimal numbers and vice-versa.
Step 1: Write the binary equivalent of each octal digit.
Step 2: Regroup them into 4 bits from the right side with zeroes added, if necessary.
Step 3: Convert each group into its equivalent hexadecimal digit.

Example 3.19 Consider an octal number 274(8)


2 010
7 111
4 100
Therefore, 274(8) =010 111 100(2)

61
Data Representation

Group the bits into groups of 4-bits as 0 1011 1100

3.3.12 Hexadecimal to octal conversion


Step 1: Write the binary equivalent of each hexadecimal digit.
Step 2: Regroup them into 3-bits from the right side with zeros added, if necessary.
Step 3: Convert each group into octal equivalent.

Example 3.20 Consider a hexadecimal number FADE (16)


F 15 1111
A 10 1010
D 13 1101
E 14 1110

Therefore, FADE (16) = 1111 1010 1101 1110(2)

001 111 101 011 011 110

1 7 5 3 3 6

Therefore, FADE (16)= 175336(8)

3.5 Representation of signed integers


The digital computers handle both positive and negative integers. So some means is required for
representing the sign of the number (+ or -). This is done by adding the leftmost bit to the number called
the sign bit. A positive number has a sign bit 0, while the negative has a sign bit 1. Hence it is also called as
fixed point representation.
A negative signed integer can be represented in one of the following ways
 Sign and magnitude representation
 One’s complement representation
 Two’s complement representation

3.5.1 Sign and magnitude representation


An integer containing a sign bit followed by magnitude bits are called sign-magnitude integer. The
MSB is always the sign bit and the remaining bits always stand for magnitude.

62
Data Representation

Example 3.21 If in a Computer of word size of 1 byte (8 bits), then an integer +83 and -83 is
eÁw
represented in 8-bit sign-magnitude representation as

27 = 128 numbers can be represented using 7 bits, numbers from 0 to +127 and 0 to -128.

3.5.2 1’s complement representation


This is the simple method of representing negative binary numbers. The negative binary number is
formed by subtracting the value of each bit in the word from 1. This changes the value of each bit from 0
to 1 and 1 to 0.
Example 3.22 Consider the binary number 101000.
1’s complement of this number is obtained as follows:
111111
- 101000
010111
Thus, one’s complement of 101000 is 010111.
We observe that one’s complement of a binary number is easily obtained by changing all 1’s into 0’s
and all 0’s into 1’s of the binary number.

3.5.3 2’s complement representation


The 2’s complement of a binary number is obtained by adding 1 to the 1’s complement of the binary
number.
Two’s complement of a binary number = One’s complement + 1
Example 3.23 Consider the binary number 101000. 2’s complement of this number is obtained as
follows:
One’s complement of 101000 = One’s complement of 101000 + 1
= 010111 + 1
= 011000
Thus, 011000 is the 2’s complement of 101000.

63
Data Representation

Example 3.24

All modern computers operate based on 2’s complement representation because of its hardware
being simpler which makes the computer work faster.

3.6 Binary arithmetic


It involves addition, subtraction, multiplication and division operations which are fundamental to all
digital computers. Binary addition is the most important operation because it can be used to perform other
arithmetic operations.

3.6.1 Binary addition


The basic rules of binary addition are given in table 3.7:
Addend1 Addend2 Sum Carry
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1
Table 3.7

The above table adds only two bits and gives sum and carry. If a carry is generated, it should be
carried over to the addition of next two bits. Thus the addition is a 3-bit addition.

64
Data Representation

Table 3.8 gives the rules to add two addend bits and a carry generated from the addition of previous
bits. eÁw
Addend1 Addend2 Previous carry Sum Carry
0 0 0 0 0
0 0 1 1 0
0 1 0 1 0
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1
1 1 0 0 1
1 1 1 1 1
Table 3.8

Carry 1
Example 3.25 Add 75 and 18 in binary
Carry
75 =Addend1 1
1001011
64 + 8 + 2 + 1 = 1001011
Addend2
Addend1
18 =Carry
16 + 2 = 10010 10010
1001011
1
Addend2
Addend1
Carry 10010
1001011
11
Sum
Carry 1011101
Addend2
Addend1 10010
1001011
Sum 1
Addend 1011101
1001011
Addend2
Sum 2
Addend 10010
1011101
10010
Sum
Sum 1011101
1011101

3.6.2 Binary Subtraction

It is performed as the addition of negative binary numbers.


For example, 8-5 may be performed as 8+ (-5).
The basic rules for binary subtraction are given in table 3.8.

Minuend Subtrahend Difference Borrow


0 0 0 0
0 1 1 1
1 0 1 0
1 1 0 0

Table 3.8

When we subtract a 1 from a 0, it is necessary to borrow 1 from the next left column i.e. from the
next higher order position.

65
Data Representation

Simple subtraction

Example 3.27 Add 75 and -25.

75 = 64 + 8 + 2 +1 = 1001011
25 = 16 + 8 + 1 = 11001

Borrow
Minuend 1001011
Subtrahend 11001
ddd
Difference 110010

3.6.2.1 Subtraction using 1’s complement


Though subtraction using borrow is straight, the computer does not use this method due to
circuit complications. It does subtraction using complement methods.

Case1: Subtracting a smaller number from a larger number (minuend is greater than subtrahend)
Step 1: Find the 1’s complement of the subtrahend.
Step 2: Add this to the minuend.
Step 3: Carry is generated. This carry is called as the end around carry.
Step 4: Add the end around carry back to the LSB to get the final difference.
Example 3.28 Subtract 15 from 23 using 1’s compliment
Minuend 23 10111
Subtrahend -15 - 01111
? ?

Minuend 10111
1’s compliment of Subtrahend +10000
End around carry 100111
Add end carry to LSB + 1
Difference 1000

66
Data Representation

Case 2: Subtracting a larger number from a smaller number (minuend is less than subtrahend).
Step
eÁw1: Find the 1’s complement of the subtrahend.
Step 2: Add this to the minuend.
Step 3: There will be no carry. Re-complement the answer to get the difference.
Step 4: Add the end around carry back to the LSB to get the final difference.

Example 3.29 Subtract 52 from 25 using 1’s compliment.


Minuend 25 011001
Subtrahend -52 - 110100
? ?

Minuend 011001
1’s compliment of Subtrahend + 001011
100100
There is no carry. Therefore re-complement and insert a negative sign, we get - 011011

3.6.2.2 Subtraction using 2’s complements


Case 1: Subtracting a smaller number from a larger number (minuend is greater than subtrahend).
Step 1: Find the 2’s complement of the subtrahend.
Step 2: Add it to the minuend.
Step 3: Carry is generated. Discard the carry and the remaining bits give the difference.

Example 3.30 Subtract 9 from 17 using 2’s complement.


Minuend 17 10001
Subtrahend - 9 -01001
? ?
2’s complement of 01001 = 1’s complement of 01001 + 1
= 10110 + 1
= 10111
Minuend 10001
2’s complement of Subtrahend +10111
101000
Carry is generated. Discarding the carry, we get 1000 = 8.

67
Data Representation

Case 2: Subtracting a larger number from a smaller number (minuend is less than subtrahend).
Step 1: Find the 2’s complement subtrahend.
Step 2: Add it to the minuend.
Step 3: There is no carry. Hence take the 2’s complement of the answer and place a negative sign in
front.

Example 3.31 Subtract 47 from 26 using 2’s complement


Minuend 26 011010
Subtrahend - 47 - 101111
? ?
2’s complement of 101111 = 1’s complement of 101111 + 1
= 010000 + 1
= 010001
Minuend 011010
2’s complement of Subtrahend + 010001
101011
2’s complement of the answer = -10101 = -21

3.7 Computer codes


Computer codes are used for internal representation of data in computers. As computers use binary
numbers for internal data representation, computer codes use binary coding schemes. In binary coding,
every symbol that appears in the data is represented by a group of bits. Thus computer codes represent
various characters, numbers and control keys that the computer user selects on the keyboard. Some of
the commonly used computer codes are:
 Binary coded decimal (BCD)
 Extended binary coded decimal interchange code (EBCDIC)
 American standard code for information interchange (ASCII)
 Excess-3 code

3.7.1 Introduction to BCD, EBCDIC, ASCII, Excess-3 Codes


One way of encoding decimal numbers digit by digit using group of 4 bits is called BCD code. Two
popular 4-bit BCD codes are

i. BCD code (or Weighted BCD code or 8421 code)


BCD stands for Binary Coded Decimal. It is one of the early computer codes. In this coding system,
the bits are given from left to right, the weights 8, 4, 2, 1 respectively. Since these weights are just the
place values in the binary system, a decimal digit is encoded as its binary representation.
Example 3.32 The decimal number 537 is represented in 4-bit 8421 BCD code as
55 33 77

0101
0101 0011
0011 0111
0111

68
Data Representation

4-bit BCD code only 24 =16 configurations are possible which is insufficient to represent the
In eÁw
various characters used by computers. Hence 6-bit BCD code was developed by adding two zone
positions with which it is possible to represent 26 = 64 characters.
BCD code BCD code
Character Character
Zone Digit Zone Digit
A 01 0 0 0 1 J 10 0 0 0 1
B 01 0 0 1 0 K 10 0 0 1 0
C 01 0 0 1 1 L 10 0 0 1 1
D 01 0 1 0 0 M 10 0 1 0 0
E 01 0 1 0 1 N 10 0 1 0 1
F 01 0 1 1 0 O 10 0 1 1 0
G 01 0 1 1 1 P 10 0 1 1 1
H 01 1 0 0 0 Q 10 1 0 0 0
I 01 1 0 0 1 R 10 1 0 0 1

BCD code BCD code


Character Character
Zone Digit Zone Digit
S 11 0 0 0 1 1 00 0 0 0 1
T 11 0 0 1 0 2 00 0 0 1 0
U 11 0 0 1 1 3 00 0 0 1 1
V 11 0 1 0 0 4 00 0 1 0 0
W 11 0 1 0 1 5 00 0 1 0 1
X 11 0 1 1 0 6 00 0 1 1 0
Y 11 0 1 1 1 7 00 0 1 1 1
Z 11 1 0 0 0 8 00 1 0 0 0
9 00 1 0 0 1
0 00 1 0 1 0

i. Excess-3 BCD Code or XS-3 Code


The excess–3 BCD code is a non-weighted code and is obtained from 8421 BCD code by
adding 3 (0011).

Example 3.33: The decimal number 537 would be represented in the XS-3 code as

5 3 7  Decimal digit
0101 0011 0111  8421 BCD Code
0011 0011 0011  Add 3 (0011)
1000 1010 0110  XS-3 Code

69
There are 8 bit BCD systems. They are EBCDIC and ASCII.

iii. EBCDIC code - EBCDIC stands for Extended Binary Coded Decimal Interchange Code
This coding was developed by IBM. It is an 8 bit code and so it has 28 = 256 possible code groups
This coding scheme is used with large computers as mainframes.

EBCDIC code EBCDIC code


Character Character
Zone Digit Zone Digit
A 1100 0 0 0 1 J 1101 0 0 0 1
B 1100 0 0 1 0 K 1101 0 0 1 0
C 1100 0 0 1 1 L 1101 0 0 1 1
D 1100 0 1 0 0 M 1101 0 1 0 0
E 1100 0 1 0 1 N 1101 0 1 0 1
F 1100 0 1 1 0 O 1101 0 1 1 0
G 1100 0 1 1 1 P 1101 0 1 1 1
H 1100 1 0 0 0 Q 1101 1 0 0 0
I 1100 1 0 0 1 R 1101 1 0 0 1

EBCDIC code EBCDIC code


Character Character
Zone Digit Zone Digit
S 1110 0 0 0 1 01 1111 0 0 0 1
T 1110 0 0 1 0 02 1111 0 0 1 0
U 1110 0 0 1 1 03 1111 0 0 1 1
V 1110 0 1 0 0 04 1111 0 1 0 0
W 1110 0 1 0 1 05 1111 0 1 0 1
X 1110 0 1 1 0 06 1111 0 1 1 0
Y 1110 0 1 1 1 07 1111 0 1 1 1
Z 1110 1 0 0 0 08 1111 1 0 0 0
09 1111 1 0 0 1
i. ASCII code -ASCII stands for American Standard Code for Information Interchange
It is a 7 bit code, which is possible to represent 27 = 128 characters. The first 3 bits are used
as zone bits and the last 4 bits indicate the digit. This coding is used to represent alphanumeric and
some special characters. It is used in micro computers for data communications. Since microcomputers
use 8-bits the ASCII was extended to an 8 bit code.

ASCII Table and Description


Computers can only understand numbers, so an ASCII code is the numerical representation of a
character such as ‘a’ or ‘@’ or an action of some sort. ASCII was developed a long time ago and now the
non-printing characters are rarely used for their original purpose. Below is the ASCII character table and
this includes descriptions of the first 32 non-printing characters. ASCII was actually designed for use with
70
Data Representation

teletypes and so the descriptions are somewhat obscure. If someone says they want your CV however in
ASCII format,
eÁw all this means is they want ‘plain’ text with no formatting such as tabs, bold or underscoring
the raw format that any computer can understand. This is usually so they can easily import the file into their
own applications without issues. Notepad.exe creates ASCII text, or in MS Word you can save a file as
‘text only’.

71
Data Representation

Review Questions

One mark questions:


1. Define the base of the number system.
2. What is the expansion of BIT?
3. Define MSB
4. Define LSB.
5. What is the weight of the LSB of an 8-bit number?
6. What is the weight of the MSB of a 16-bit number?
7. What does BCD stand for?
8. What is the expansion of ASCII?
9. What is the expansion of EBCDIC?
10. What is binary system?
11. What is octal system?
12. What is hexadecimal system?
13. How are negative numbers represented?
14. Write 1’s complement of 11010111(2)
15. Write 2’s complement of 11011011(2)

Two marks questions:


1. Specify the general rule for representing number using positional notation in any number system.
2. Mention different types of positional number system.
3. Explain the need of binary number system in computers.
4. What is the importance of hexadecimal system?
5. What is 1’s complement? Give an example.
6. What is 2’s complement? Give an example.
7. What are computer codes? Give example.
8. Mention the different types of number systems.
9. What is the use of binary number system over decimal number system?
10. Convert 97.188 (10) to binary.
11. Convert 728.45(10) to binary.
12. Convert 1101111.101(2) to decimal
13. Convert 2835(16) to decimal
14. Convert 789.625(10) to octal
15. Convert 4563 in octal to binary.
16. Convert BED(16) to binary
17. Convert 1101.01101in binary to octal.
18. Convert A492.B in hexadecimal to decimal.

72
Data Representation

19. Convert 512.45(10) to hexadecimal.


20. Convert
eÁw 11011110(2) to hexadecimal.
21. Convert 6A9.ABC (16) to binary.
22. Add 1010101 and 1010111
23. Explain ASCII code.

Three marks questions:


1. Give the Radix of:
(a) Decimal system (b) Binary system
(c) Octal system (d) Hexadecimal system
2. Explain 1’s and 2’s complement with examples.
3. Subtract 36 from 83 using 2’s complement.
4. Using 1’s complement method, solve 54(10) – 87(10)
5. Using 2’s complement method, solve 73(10) – 25(10)
6. Add: 64(10) + 35(10) using binary addition.

Five marks questions:


1. Find (11001001.1011)2 = (?)8 = (?)16
2. Find (FADE) 16 = (?)8 = (?)10
3. Explain different types of computer codes.
4. Evaluate: BEAD (16) = () 10 = ( ) 2 = () 8
5. Subtract: 25 (10) – 14 (10) using 1’s and 2’s complement.
6. Write a brief note on computer codes.
7. Write a note on ASCII code.

73
74
eÁw

CHAPTER 4
SOFTWARE CONCEPTS

OBJECTIVES
 To identify types of software
 Basic of different operating systems

75
76
4.1 Introduction
eÁw
A computer system has three components viz. Hardware, Software and Users. Hardware
consists of the physical devices and their interconnections for the purpose of storing and executing a
program. Pictorially, we have the following overall view about a computer system as in figure 4.1.

Figure 4.1 Components of computer system

Computer software or just Software is a collection of computer programs and related data that
provides the instructions for instructing a computer what to do and how to do it. Software refers to one or
more computer programs and data held in the storage of the computer.

We have an interesting example i.e. the processing of information in human brain. Human brain
consists of Neurons, and Neurons are interconnected with each other. We can say our brain is a
“massively parallel processor”. The process of recalling a face, which a person may not be seen since
last thirty years, is a very complex task requiring lots of comparison among similar faces/images stored in
his mind. Interestingly, our brain can store approximately 244 bits of data.

Software is the set of programs, procedures, algorithms, and documents concerned with
the operation of a data processing system”.

4.2 Types of software


Software is broadly grouped into two categories namely,
 System software
 Application software
4.2.1 System software
The objective of system software is to efficiently perform the functions commonly required by
most of the users. In order to achieve this objective, these programs are generally written at the machine
level using instructions for addressing various registers of the central processing unit. Thus system software

77
Figure 4.2

is hardware dependent and not portable. Input/output operations are generally performed by systems
software. System software provides a convenient environment for program development and execution.
Programming languages like assembly language/C/ C++ /Visual C++ /Pascal are used to develop system
software.

System software is a collection of systems programs to perform common tasks.

4.2.2 Application software

Application software consists of user application packages such as Payroll, Inventory, Financial
Accounting packages. Application software is generally written in high level languages. These are custom-
made although many application packages for word processing, Data base management and spreadsheet
are used by millions of users all over the world. Being hardware independent these are portable.

Examples of application software are Microsoft Office, Open Office, Oracle, Sybase, Informix,
Ingress, DB2, Tally etc.

System software is of three types:

 Operating system
 Language translators (Assemblers, compilers, interpreters, Linkers and loaders)
 Utilities
4.3 Introduction to Operating system
An operating system is a set of program modules which provides a friendly interface between the user
and the computer resources such as processors, memory, input/ output devices and information (files).

78
Operating systems manages these resources, resolves conflicts and tries to optimize the
performance
eÁw of the system. Generally part of the operating system resides in memory and supervises
execution of all other programs executed on the computer. The user communicates with the computer
through operating system commands and program instructions. It plays an important role in loading programs
from disk into memory, displaying messages, translating programs and in outputting results. Basically, it
executes the user programs without letting the user bother about the detailed steps involved in executing
them.

Some examples of operating systems are: Unix operating system, OS/2, Linux Operating system, Sun
Solaris, MS-DOS(Microsoft disk operating system), Microsoft Windows operating systems such as
Windows 95, Windows 98, Windows 2000, Windows NT, Windows XP, Windows Vista, Windows 7,
Windows 8, Windows 2000 server, 2003 server, 2008 server, .NET server, Android, Mac OS.

An operating system is a set of programs which acts as an interface between the


user and the computer
Let us now discuss in short all the terminologies which is dealt with Operating system.
Computer languages
Language is a medium of communication. If we have to communicate with the computer, we
require a suitable language understandable by the computer. Such a language is called programming
language or computer language. Using a programming language a user instructs the computer what it
should do.
Programming language is a set of rules called syntax which the user has to follow, to instruct
the computer what operations are to be performed.
Computer languages are classified into two categories:
Low level languages
a) Machine level language
b) Assembly language
High level languages
1. General purpose high level language. Ex: BASIC, Pascal, C languages

79
2. Specific purpose high level language
Ex: COBOL (specific for business applications)
Ex. FORTRAN (specific for scientific applications)
Ex. C++ (specific for object oriented programming)
 Machine level language
Machine language is the only language of the system, and these are sequence of machine
instructions. These instructions are externally represented by a sequence of 0’s and 1’s, and stored internally
as a sequence of voltage levels (high/low) in primary memory (RAM). As general programmers come
across many difficulties such as remembering of such a large sequence of 0’s and 1’s which is very difficult
to program, debug, it requires lot of experience and knowledge about the internal architecture of the
system. In spite of all these odds it is the fastest because no translation is required, and we can program
each bits and bytes.

Example 4.1 Sample machine language program to add two numbers


0001 00110010: Load the data
0100 10100101: Add the contents
1000 00101001: Store the results
0000 00000000: Stop
In our example 4.1 the first (most significant) 4-bits represent opcodes denoting the operation, or action
such as load, move etc. and the last 8-bits (least significant) represents the operand denoting the address.
Advantages of machine language are machine language instructions can be directly typed and executed
and no compilation or translation is required. Disadvantages of machine language are machine language
instructions are machine dependent and it is difficult to program, modify and debug errors.
 Assembly Language
The disadvantages of a machine language lead to the development of a new programming
language which uses symbolic instructions called as assembly language. The burden of remembering a
lengthy machine code was reduced, and instead replaced them with symbolic codes. These symbolic
instruction codes of machine language are referred to as the mnemonics. Some of
the mnemonics are given in example 4.2 below.
Example 4.2
ADD for addition
SUB for subtraction
MUL for Multiplication
STA for storing value in accumulator
HALT for Halt
Since, the above instructions are English-like; the computer does not
understand instructions. Therefore, the instructions have to be translated to

80
the equivalent machine codes. This process is carried out by a program called
assembler.
eÁw

Advantages :Assembly language are assembly language which has mnemonic code is easy to remember,
easy to understand and write the assembly program and easy to modify and debug the assembly program.
Disadvantages : Assembly language are the mnemonics are machine dependent and assembly language
programming takes longer to code.
Assembly language is a symbolic language in which mnemonics are used to code operations
and characters are used for address.

High level languages

The high level languages were developed to overcome the difficulties of low level languages.
The high level languages are English-like languages and are machine independent. The programming
language that is more concerned with the problem specification and not oriented towards the details of
a computer is called High level languages (HLLs). Some of the High Level Languages are BASIC,
COBOL, FORTRAN, PASCAL, C, C++ and JAVA.

Advantages : High level language are HLLs are machine independent, easy to learn and understand,
easy to write the program using HLL as it does not require the knowledge of the internal structure of the
computer and easy to debug and modify the program.
Disadvantages : High level language are HLL lacks flexibility because the features of HLL always occur
and are not under the control of the programmer. HLL is slower in execution due to the generality of the
statements and that they are portable between different machines but with suitable compiler. HLL requires
a translator or a compiler to convert source code to object code. HLL programs take more time to
execute and require more memory. Hence becomes less efficient.

Language Translators

Language translators perform the translation of high level language program or assembly language
program into machine language. These language translators even check for some types of errors that may
be present in the program being translated.

S o u r c e p r o g ra m L a n g u a g e t r a n sla t o r O b je c t p r o g r a m

There are three types of translator programs:


 Assembler
 Compiler and
 Interpreter

Assembler is the translator for assembly language. Assembly language


requires translation of English like statements to machine language. The system

81
software Assembler will check for the syntax and semantics of code and translate
it into its equivalent machine code also known as object code.
The following are some of the generally used assemblers TASM (Turbo assembler), MASM
(Microsoft Macro assembler), as (Unix. assembler), FASM (Flat Assembler), NASM (Net wide
assembler) and many others.

Assembler is system software which translates programs written in assembly language into
machine language.

A s se m b ly pr o gr a m A ss e m bl e r M a c h ine pr o gr a m

Compiler is the language translator for translating high level language source code into machine code
known as object code. A compiler will check the entire source code for syntax and semantic errors line
by line and produces an executable file only if it is free from all errors.

Compiler is system software that translates source code written in high level language
into object code which is in machine language.

Interpreter
As discussed above the process of compilation consumes lot of memory and so systems with less amount
of RAM always prefer interpreters where the source code is analyzed line by line and executed immediately,
and it reduces the need of larger RAM capacity. Source level debugging also becomes easier when
compared to compiled one, but overall execution time is more compared to a compiled program, because
during execution we require both source code and Interpreter, and translation is required afresh. This
invites security problems also.
All system specific software will use compiled program, because it does not require a recompilation
of source code. The earlier versions of COBOL, FORTRAN used interpreters for translation now they
have compilers for translation. Web application languages are mainly dependent on Interpreters, for example
java is an interpreted language. It requires JVM (java virtual machine) for running web applications. C/
C++/Visual C++ are compiler dependent languages due to their inherent application nature.

Interpreter is a language processor that translates an instruction of a high-level


language program and immediately executes it before translating the next instruction
of the source program.

82
Ø Utilities
eÁw
Utilities are those helpful programs that assist the computer by performing useful functions
(housekeeping functions) like backing up disk or scanning/cleaning viruses or arranging information etc.
Utility software is generally called as Application oriented ready-made system programs. Some of
the important utilities are: Text Editor, Backup Utility, Compression Utility, Disk defragmenter, Antivirus
Software.

Linkers and loaders

A source program written in high-level language may contain a number of modules or segments.
For the program to be executed properly the modules are to be linked properly and the various library
segments included so that execution of the program is sequential. This operation is performed by software
called as the linker.

A linker is system software which links the modules or program segments together so that they
can be executed properly with proper reference.

The output of the linker is a single program, which includes all the modules and the entire library
required for execution. The linker is thus responsible for generating the executable code of a program.

Once an executable program is generated someone will have to load the program into the
main memory of the computer so that it can be executed. This operation is performed by system software
called as the loader. It actually places the object code from secondary memory storage into main memory
and starts execution

A loader is system software which accepts the object program produced by the compiler or
assembler and prepares these programs for execution.

4.4 Functions of operating systems


Operating system is a large and complex software consisting of several components. Each component
of the operating system has its own set of defined inputs and outputs. Different components of
OS perform specific tasks to provide the overall functionality of the operating system. Main functions of
the operating system are as follows:

4.4.1 Memory Management— The activities of memory management handled by OS are—


i Allocate memory,
i i Free memory,
iii Re-allocate memory to a program when a used block is freed, and
iv Keep track of memory usage.
4.4.2 Process Management— The process management activities handled
by the OS are—

83
(1) Control access to shared resources like file, memory, I/O and CPU.
(2) Control execution of applications.
(3) Create, execute and delete a process (system process or user
process).
(4) Cancel or resume a process.
(5) Schedule a process.
(6) Synchronization, communication and deadlock handling for
processes.

Process is defined as a program in execution.

4.4.3 Device management— The device management tasks handled by OS


are—
(1) Open, close and write device drivers, and
(2) Communicate, control and monitor the device driver.

4.4.4 File Management— The file management tasks include—


(1) Create and delete both files and directories,
(2) Provide access to files,
(3) Allocate space for files,
(4) Keep back-up of files, and
(5) Secure files.

4.4.5 Protection and Security— OS protects the resources of system. User


authentication, file attributes like read, write, encryption, and back-up
of data are used by OS to provide basic protection.

4.4.6 User Interface or Command Interpreter— Operating system provides


an interface between the computer user and the computer
hardware. The user interface is a set of commands or a graphical user
interface via which the user interacts with the applications and the
hardware.

4.5 Types of operating systems

Based upon the time constraints and service requirements or criticality every operating system will
come under one of the following groups namely, batch operating system, online operating system, and
Real time operating system.

84
The different types of operating systems are
1. Single user operating system
eÁw
2. Batch operating system
3. Multiprogramming operating system
a. Multitasking Operating system
b. Multiuser operating system
c. Time sharing systems (online / multiuser)
d. Real time system
4. Distributed operating system
5. Network operating system
6. Multithreading operating system
4.5.1 Single user operating system
This OS allows only one user to share the system resources including the CPU. These are mainly the
operating systems configured for the use of desktop personal computers and Laptops. DOS and windows-
95, windows-98, Apple Macintosh etc. are examples for such systems. However, all others except DOS
has ability called context switching allowing it to operate on multiple program windows/applications.
4.5.2 Batch operating systems
Batch operating systems usually allow little or no interaction between users and executing programs. It
requires programs, data and necessary commands (Job Control Language-JCL) to be submitted in the
form of a job. It has a better potential for resource utilization compared to simple serial systems serving
multiple users. This is well suited for applications with large computation time and no user interaction.
Payroll, forecasting, statistical analysis and large scientific number crunching programs are examples for
its usage.
Users need not wait during its execution. Batch operating systems will function in FIFO (first in
first out) order. The main disadvantages of batch operating systems are Non-interactive mode of execution
and Offline debugging.
IBM System/360 operating system (OS/360) for IBM system/360, is an example for batch
processing operating systems. In DOS we can emulate the batch processing using .BAT files.
4.5.3 Multiprogramming operating systems
Multiprogramming is the capability of CPU to execute two or more programs concurrently.
This capability is accomplished through the operating system. Essentially, two or more programs are
stored concurrently in primary storage, and the CPU moves from one program to another, partially executing
each in turn. Early computer system and many personal computers execute program in the order in which
it is read into the system, and only one program is executed at a time.
4.5.4 Multitasking operating systems
A multitasking operating system is distinguished by its ability to support concurrent execution
of two or more processes. A process or task is an instance of a program in execution. Multitasking is
usually implemented by code and data of several programs in memory simultaneously and multiplexing

85
processor and I/O devices among them. Multitasking is also called context switching. Multitasking usually
refers to a single user. Example: Windows 98 and some real time systems.
4.5.5 Multi-user operating system
Multitasking with sophisticated memory protection and enforcement of concurrency control
among processes which try to access shared resources such as I/O devices and files are called
multiprogramming operating systems. Since it supports multiple users, it is also known as Multi-user
operating system. It creates and maintains individual user environments, individual authentication and
security levels/privileges, provides per user resource usage accounting. Due to these reasons we can say
Multiprogramming /Multitasking implies multitasking but the converse need not be true. We have systems
with more than one processors, each processor can be multitasked. So in purely multiuser/multiprogramming
system processor is also a resource.

4.5.6 Time-Sharing systems


Time-sharing is a popular representative of multiprogramming and multi-user systems. Large
CAD and text processing systems belongs to this category. Good terminal response is one of the main
objectives of such systems providing an illusion of total dedication. Time-sharing systems provide equitable
sharing of common resources. Most of the time-sharing operating systems adopted time-slicing/round
robin scheduling algorithm. Each user/process will receive a portion of the time slot.
UNIX and its flavors, Windows Server are the best examples for multiprogramming, multi-user and time
sharing systems.
4.5.7 Real-time systems
Real time systems are used in environments where a large number of events, mostly external to
the computer system, must be accepted and processed in a very short time or within certain deadlines.
Such applications include industrial control, telephone and switching equipment, flight control, real-time
simulations and military applications. The primary objective of real-time systems is to provide quick event-
response times and thus meeting the scheduling deadlines. User convenience and resource utilization are
of secondary concern to real time systems design.
Lynx OS, Windows CE are examples for real-time operating systems.
4.5.8 Distributed operating systems
A distributed operating system is a collection of autonomous computer systems capable of
communication and cooperation via their software and hardware interconnections.
For example, if we have ‘n’ systems in a distributed environment then the distributed operating
system helps us in balancing the load by sharing processors, I/O devices, and memory etc. without the
knowledge of the user. The end user will get his output on his terminal. This has a very reliable mode of
operation.
The ATM (Automatic Teller Machine) centers of a bank are a classic example of application
of distributed operating systems.

86
4.5.9 Network operating systems
A network operating system is a collection of software and associated protocols that allow a set
eÁw
of autonomous computers which are interconnected by a computer network. It can be used in a convenient
and cost-effective manner.
In a network operating system the users are aware of the existence of multiple computers and
can log in to remote machines and copy files from one machine to another machine. Each computer has its
own private operating system. Processing will be done locally. All file movements are done with the
explicit knowledge of user.
Operating systems based on Microsoft Windows NT technology, UNIX and its flavors, Novel
Netware, Cisco IOS are some of its representatives.
4.5.10 Multithreaded operating systems
A thread is a sequence of instructions within a program. A program or process may have many
threads which share the same code section, data section, and other OS resources. In other words, it
provides many logical paths through the program to be executed simultaneously.
All modern operating systems have incorporated this concept rather than evolving as a separate
product.
Sun Solaris, Windows 2000, Multithreaded UNIX and Linux are examples for such systems.

4.6 Functional Features of commonly used operating systems


The operating system in general, provides a user interface to interact with the computer. The objects
available on the monitor provide the user interface to the required program. There are two types of user
interfaces:
 Command-line user interface (CUI)
 Graphical user Interface (GUI)
4.6.1 CUI interface
CUI interface allows the user to interact with a computer through text terminal. MS-DOS is an
operating system which provides a CUI. The commands must be given at the command prompt(C :\>).
Since both input and output are character based, the interface is also known as Character User Interface.
Hence it is a non-graphical and text based user interface. To overcome some of the limitations of MS-
DOS such as-user must remember commands and parameters can not be used for multi-tasking, a new
interface called the graphical user interface (GUI) was developed.
4.6.2 Graphical User Interface (GUI)
The GUI was first introduced in 1984 by Apple with Macintosh. GUI is an interface where the
commands are selected from menus and icons rather than typing them from the keyboard. It allows the
user to click on the required icon, with the help of a hand held device called Mouse. Windows operating
system is the most popular operating system based on GUI.

87
4.6.3 Comparison of CUI and GUI

CUI GUI

1. The user must type the 1. The user must click on


commands at command icons, menus, dialog boxes
prompt to interact with the etc. to interact with the
computer. computer.
2. The user must remember 2. The user need not
the commands and their remember any commands as it
parameters. is available in the form of
menus and icon on monitor.
3. Mouse operation not
available for DOS. 3. Mouse operation required to
select the commands.

Operating System Features

Disk Operating System (DOS) 1. File management features (to create,


edit, write and delete files).
DOS is a single user operating 2. Directory management (creation,
system. It was developed by Bill Gates and change, search, and deletion of
Paul Allen in 1980 for IBM PCs. directories).
3. Memory management (allocation and
de-allocation of memory).
4. Command interpreter interprets
commands and executes DOS
functions, utility programs or
application programs.
5. Executive programs to load and
execute user programs, retrieve error
code, correct and re-run programs.
6. Utility programs such as COPY,
ERASE, and DIR etc.

UNIX OS
1. Hierarchical file organization
UNIX was developed by Dennis Ritchie and 2. Portability
Ken Thompson on a DEC in 1985 by Sun 3. Multi-user, multitasking support
Micro systems. 4. Facilitates Kernel and Shell
programming
5. Machine independent
6. Excellent tools and tool-building
utilities

88
inux Linux
eÁwOS
Linux was initially developed 1. Facilitates Kernel
by FinnishUniversity student Linus programming, which provides
Torvalds. It is a free download from access to software and
www.linux.org. hardware
2. Open source development
operating system
3. Machine independent
4. Multi-user, multitasking
support
5. Compatibility and Portability

Solaris OS 1. Advanced networking capability


supporting wireless and high
TheSolaris Operating System is a throughput networks.
free Unix-based operating system
introduced by Sun Microsystems in 2. Facilitates Zoning security
1992 as the successor to Sun OS.
3. User-interface for internet
browsers, media players, office
suite

4. Managing hardware usage of a


particular application

Windows 7
1. A redesigned taskbar and
Windows 7 is the most recent client multitouch support
version of Windows, developed by 2. Better search facility for files
Microsoft. and documents
3. Sharing of file folders among
users
4. Automatic defragmentation of
disk to release continuous
areas of disk
5. It is designed for 64 bit
machines and supports 32 bit
operations with smaller RAM
6. Bundled Internet Explorer
Version 8
7. Energy management by
putting inactive devices in
sleep mode
8. Better support for multimedia
9. Support for wireless to
facilitate mobility
10. Better security support
11. Support for multicore
processors

89
Windows 8 1. Better interfaces aimed at
tablet computers and touch
Windows 8 is a 2012 touch user screen devices(without
interface version of Microsoft taskbar)
windows. 2. Safety and security
3. Online services and
functionality
4. Windows store applications
5. Secure boot which prevents
usage of boot kits for loading
multiple operating systems
Mobile Operating Systems

1. Android OS It is a Linux-based platform


for mobile phones. Android was
developed by Google and the Open
Handset Alliance (OHA), a coalition
of hardware, software and
telecommunications companies.
Android was released under the
Apache v2 open source license.

2. Symbian OS It is an operating system for


mobile phones used on Nokia
advanced or data enabled smart
phones. The Symbian OS is
designed for the specific
requirements of 2G and 3G mobile
phones.

3. Windows Phone 8 Windows Phone 8 is a


mobile operating system developed
by Microsoft and is the successor
to its Windows Mobile platform,
although incompatible with it.
Windows Phone 8 was Microsoft’s
answer to the flourishing smart
phone world.

90
Review Questions
One mark
eÁwquestions:
1. What is a program?
2. What is hardware?
3. What is software?
4. What is machine language?
5. What is assembly language?
6. Give an example for high-level language.
7. What is meant by machine dependent language?
8. What is meant by machine independent language?
9. Define opcode.
10. What is an assembler?
11. What is a compiler?
12. What is an interpreter?
13. What is system software?
14. What is application software?
15. What is linker?
16. What is loader?
17. Define operating system.
18. Write any one function of operating system.
19. Name any single-user operating system.
20. Name any multi-user operating system.
21. What is multitasking?
22. What is multithreading?
23. Name any mobile operating system.

Two marks questions :

1. Explain object code and source code.


2. Compare hardware and software.
3. Mention the types of software.
4. What is system software? Give an example.
5. What is application software? Give an example.
6. What is language translator?
7. What is an operating system? Give an example.
8. Differentiate between interpreter and compiler.
9. What is the function of linker and loader.
10. Write any two functions of operating system.
11. Explain operating system as an user interface.
12. Explain the need of operating system.

91
13. Explain real time operating system.
14. What is software? How do you classify software?
15. What is the need for programming languages?
16. Mention any two mobile operating systems.

Three marks questions:


1. Write a note on programming language.
2. Explain different types of operating system.
3. Explain batch processing operating system.
5. Explain multi-user operating system.
8. Explain the purpose of utilities.
9. What is meant by the terms multiprogramming and multitasking.

Five marks questions:


1. Differentiate between
a) Interpreter and Compiler
b) Object code and Source code.
c) Application software and System software.
d) Linker and loader.
2. What is an operating system? Explain any four operating systems.
3. What are language translators? Explain briefly.
4. What are the different functions of an operating system?
5. What are the features of Disk Operating System (DOS)?
6. What are the features of UNIX operating system?
5. What are the features of Windows operating system?

***************

92
eÁw

CHAPTER 5
Problem Solving Methodology

OBJECTIVES
Ø To understand process of problem solving
Ø Concepts
Ø Features
Ø Methodologies of problem solving

93
94
Problem Solving Methodology

5.1 Introduction to problem solving


The term problem solving is used in used in many disciplines, sometimes with different perspectives,
eÁw
and often with different terminologies. For instance, it is a mental process in psychology and a
computerized process in a Computer Science.

5.1.1 Computerized process


In Computer science and in the part of artificial intelligence that deals with algorithms Problem
solving encompasses a number of techniques known as algorithms, heuristics, root cause analysis, etc. In
these disciplines, problem solving is part of a larger process that encompasses problem determination, de
duplication, analysis, diagnosis, etc.
Today almost all fields of human life sphere are computerized. Some of the major areas are Scientific
and engineering, education, commerce etc. Scientific and Engineering problems are mathematical
oriented. Commercial field problem deals with record keeping, accounting and so on. Whatever the kind
of Problem, Problem solving using computer needs to follow the step-by-step methodology to arrive at an
efficient solution.

5.1.2 Man-machine interface


Computer works on set of instructions called computer program, which clearly specify the way to
carry out a specific task. In early history of computers, it was felt that every computer user needs to know
a great deal about computer. If you wanted to use a computer you had to study machine and/or Assembly
language. The goal was to help you gain an intimate understanding of the machine. Hence developing
program in machine language is tedious and needs thorough understanding of computer working. To
make the program development problem oriented rather than machine oriented Assembly language and
high level languages such as FORTRAN, COBOL, Basic etc. are developed. Computer understands
machine language only. Hence programs developed in a language other than machine level language
needs to be translated into its machine language version.
Assembler is developed along with Assembly language and respective compiler/interpreter is devel-
oped along with high level languages.
Each new programming language is designed to improve the man-machine interface. This progress
in improving the man-machine interface leads to the questions of who needs to learn computer program
and what can one learn about problem solving through studying computer programming. Thus,
Computer courses are placing increased emphasis on problem solving in a Computer environment.
The problem solving process starts with the problem specification and ends with a concrete (and
correct) program.
The steps to follow in the problem solving process are:
 Problem definition
 Problem analysis
 Algorithm development
 Coding

95
Problem Solving Methodology

 Program testing and debugging


 Documentation.

The stages of analysis, design, programming, implementation and maintenance forms the life cycle of
the system.
We briefly describe the steps in problem solving process by using a programming environment and
by considering only a specific process from the whole system. In this context the stages can be:

5.2 Problem definition


Here we define the problem. In practice to solve any complex real life problem, first we
have to define the problem by answering to the following questions.
 What the computer program does?
 What tasks will it perform?
 What kind of data will it use and where will it get data from?
 What will be the output of the program?
 How does the program interact with the computer user?

Specifying the problem requirements makes you to state the problem clearly and unambiguously and
to gain a clear understanding of what is required for its solution. Your objective is to eliminate unimportant
aspects and to focus on the root problem, and this may not be as easy as it sound.

5.3 Problem analysis


Analyzing the problem or analysis involves identifying the following:
i. Inputs, that is, the data you have to work with.
ii. Outputs, the desired results.
iii.Any additional requirements or constraints on the solution

5.4 Design of solution


We represent the solution to the problem using the tools such as algorithm and flowchart.

5.4.1. Algorithm development


An algorithm is a step-by-step finite sequence of instructions, to solve a well-defined problem.Write
step-by-step procedure and then verify that the algorithm solves the problem as intended.
The word algorithm originates from the word ‘algorism’ which means the process of doing arithmetic
with Arabic numerals. Mathematical historians believe that this word comes from the name of a ninth-
century Arab mathematician Mohammed al-Khwarizmi. It is combined with the word ‘arithmetic’ to
become algorithm.

96
Problem Solving Methodology

Characteristics of algorithms
A well-defined
eÁw algorithm has the five basic characteristics; as follows:
i. Input: Algorithm starts with procedural steps to accept input data. The algorithm must accept
one or more data to be processed.
ii. Definite: Each operational step or operation must be definite. i.e., each and every instruction
must clearly specify that what should be done.
iii. Effective: Each operational step can at least in principle is carried out by a person using a
paper and a pencil in a minimum number of times.
iv. Terminate: After some minimum number operations algorithm must come to an end.
v. Output: An algorithm is written to solve the problem, therefore it must produce one or more
computed result or answer called output.

ALGORITHM

Compound interest
Given the principal amount p, rate of interest r and time period p, this algorithm finds the com-
pound interest ci.
Step 1: START
Step 2: [Read the values of p, r, n]
INPUT p, r, n
Step 3: [Calculate compound interest]
ci = p * pow(1+ r/100, t)-p
Step 4: [print the computed results]
OUTPUT ci
Step 6: [End of Algorithm]
Exit
In the above example, we used = that represents assignment. Assignment statement will
be used to store a value into the variable or copy the value of the variable into another variable.

97
Problem Solving Methodology

ALGORITHM

Greatest of three numbers


Given three numbers a, b, c this algorithm finds the greatest and store the result in the variable
large.
Step 1: START
Step 2: [read the three numbers]
INPUT a, b, c
Step 3: [Assign a to large]
large= a
Step 4: [Compare large and y]
if( b > large )
large= b
endif
Step 5: [Compare large and z]
if( c > large )
large=c
endif
Step 6: [Print the largest number]
OUTPUT large
Step 7: [End of Algorithm]
STOP
The following algorithm finds the factorial of a number. We know that factorial is defined only for the
positive integers and 0.

98
Problem Solving Methodology

ALGORITHM
eÁw
Factorial of a number
Given a number n, this algorithm finds the factorial of n and store the result in the variable fact. The
variable i is the for loop counter that varies from 0 to n.
Step1: START
Step 2: [Read the number]
INPUT n
Step 3 [Initialize factorial to 1]
Fact = 1
Step 4: [Compute the factorial by successive multiplication]
Repeat for i= 1 to n
Fact = Fact * i
[End of Step 4 for loop]
Step 5: [Print factorial of given number]
OUTPUT Fact
Step 6: [End of Algorithm]
Exit

99
Problem Solving Methodology

The following algorithm generates the Fibonacci sequence up to some limit.0 and 1 are
initial terms. To get the next term, we should add the previous two terms. This process is repeated
until last term is less than or equal to the limit n. Thus the Fibonacci sequence up to the limit n is 0, 1, 1, 2,
3, 5, 8, 13, …

ALGORITHM

Fibonacci series
Here first, second and third are the variables that represent first, second and third terms of the
sequence. Every time first and second terms are added to get the third term.
Step 1: START
Step 2: [Read the number]
INPUT n
Step3: [Initialize the variables]
first = 0
second = 1
term = 2
Step 4: [Print the values of first and second]
PRINT first, second
Step 5: third = first + second
Step 6: Repeat while (term <= n)
PRINT third
first = second
second = third
third = first + second
term = term + 1
[End of while]
Step7: [End of Algorithm]
Exit

The following algorithm finds the GCD of two numbers. The algorithm follows the Euclidian method.
Let A and B are the two positive integers. To obtain the GCD of A and B, the algorithm constructs the
descending sequence of numbers.
The first number is the larger of two numbers, the second number is the smaller and the third
number is the remainder obtained when dividing the first by the second, the fourth is the remainder
from dividing the second by the third; and so forth. The process ends when there remainder is 0.
The greatest common divisor is the last divisor in the sequence. For example, the descending
sequence of numbers for greatest common divisor of 44 and 28 is 44 28 16 12 4 0.
The last divisor is 4, which is the result. The algorithm can be summarized in the following list of
instructions:
100
Problem Solving Methodology

ALGORITHM
eÁw
Greatest common divisor
Here, a and b are the two numbers. r is the remainder obtained when a is divided by b.
Step1: START
Step2: [Read the numbers]
INPUT a, b
Step3: Repeat while (b 0)
r=a%b
a=b
b=r
[End of while loop]
Step 4: [Print the last divisor]
PRINT a
Step 5: [End of Algorithm]
Exit

Analysis of algorithm
There may be more than one approach (or algorithm) to solve a problem. The choice of a particular
algorithm depends on the following performance analysis and measurements:
1. Space complexity: The amount of memory needed by the algorithm to complete its run.
2. Time complexity: The amount of time, the algorithm needed to complete its run.

When we analyze an algorithm it depends on input data, there are three cases:
1. Best case: The amount of time a program might be expected to take on best possible input
data.
2. Average case: the amount of time a program might be expected to take on typical (or average)
input data.
3. Worst case: the amount of time a program would take on the worst possible input
configuration.

Time-Space Trade Off


The best algorithm(or a program) to solve a given problem is one that requires less space in
memory and take less time to complete its execution.. But in practice, it is not always possible to achieve
both of these objectives. One algorithm may require more space but less time to complete its
execution while the other algorithm require less space but more time to complete its execution. Thus, we
may have to sacrifice one at the cost of other. If the space is our constraint, then we have to choose a
program that requires less space at the cost of more execution time. On the other hand, if time is our

101
Problem Solving Methodology

constraint such as in real time system, we have to choose a program that takes less time to complete its
execution at the cost of more space.

Stepwise refinement techniques


There are several steps to reach a program from a mathematical model. In every step there is a
refinement (or conversion). That is, to convert an informal algorithm into a program, we must go through
several stages of formalization until we arrive at a program, whose meaning is formally defined by a
programming language manual is called stepwise refinement.
There are three major steps in refinement process, which is illustrated in the following figure.

Mathematical Formal Data


Model Language Structures
Informal Pseudo- C/C++
Algorithm language Program
Program
Figure5.1
Figure 5.1 Major
Major steps
stepsof of
stepwise refinement
stepwise refinement

The development can be expressed as:


 Pseudo code- a narrative description of the flow and logic of the intended program, written in
plain language that expresses each step of the algorithm.
 Flowchart- a graphical representation that uses graphic symbols and arrows to express the
algorithms.

5.4.2 Flowchart
The diagrammatic representation of an algorithm is called flowchart. Flowchart play a vital role in the
programming of a problem and helpful in understanding the logic of complicated and lengthy problem.
Once the flowchart is drawn, it becomes easy to write program in any high level language. Hence it
necessarily provides a better documentation of a complex problem.
There are two types of flowcharts - program flowchart and system flowchart.
A Program Flowchart specifies only the flow of operations of an algorithm, pictorially. But pro-
gram Flowchart never specify the computer environment in which program will be executed.
A system flowchart is a flowchart which gives an overall view of computer system environment in
addition to the flow of operations for an algorithm or program to be solved. It provides information such
as whether program is stored on magnetic disk, whether data is coming from keyboard or also the result
are printed out on a printer.

102
Problem Solving Methodology

Importance of Flowchart
1. eÁw
Communication: Flowcharts are better way of communication of the logic of a program to all
concerned.
2. Effective Analysis: With the help of flowchart, problem can be analyzed in more effective way.
3. Proper Documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
4. Efficient coding: The flowchart acts as a guide or blueprint during the system analysis and pro-
gram development phase.
5. Proper Debugging: The Flowchart helps in debugging process.
6. Efficient Program maintenance: The maintenance of a program becomes easy with the help of
flowchart. It helps the programmer to put efforts more efficiently on a specific part.

Flowchart Symbols
Name Symbol Meaning

Oval Beginning or End

Parallelogram Input or Output

Rectangle Process or Calculation or assignment

Rhombus Decision or Branching

Preparation For loop

Pre-defined
Subprogram
process

Connector Connection

Arrows Control flow

103
Problem Solving Methodology

Example 5.1: Flowchart to interchange the values of two variables

START

INPUT a, b

temp = a
a=b
b = temp

OUTPUT a, b

STOP

Example 5.2: Flowchart to find the area and circumference of a circle

START

INPUT rad

area = 3.142 * rad * rad


circum = 2 * 3.142 * rad

OUTPUT area, circum

STOP

104
Problem Solving Methodology

Example 5.3: Flowchart to find the area and circumference of a circle


eÁw
START

INPUT s1, s2, s3

s = (s1 + s2 + s3)/2
area = sqrt(s * (s – s1) * (s – s2) * (s –s3))

OUTPUT area

STOP

Example 5.4: Flowchart to find the greater of two numbers

START

INPUT a, b

F Is T
a > b?

OUTPUT b OUTPUT a

STOP

105
Problem Solving Methodology

Example 5.5: Write a Flowchart to find the sum and average of numbers.

START

sum = 0
count = 0

INPUT number

sum = sum + number


count = count +1

Y More
Numbers?

N
O
average = sum/count
O

PRINT sum, average

STOP

106
Problem Solving Methodology
Example 5.6: Write a Flowchart to find the sum of digits in a given number.
eÁw

START

INPUT n

sum = 0

F
Is
n ≠ 0?

T
rem = n % 10
sum = sum + rem
n = n / 10

PRINT sum

STOP

107
Problem Solving Methodology

Example 5.7: Write a Flowchart to check whether a number is prime or not

START

INPUT n

>=2
limit = sqrt(n)

for i = 2 to limit

Is T
n % i = 0?

F
i

PRINT “It is prime” PRINT “It is not prime”

STOP

Pseudo Code:
Pseudo code a short hand notation for the control structure and other elements of a programming
language. It is neither an algorithm nor a program and is near to program. Thus it is easy to convert pseudo
code into a program.

5.5 Development of programs or computer solution


In this step, we develop the complete solution in the form of a computer program.

5.5.1 Coding or programming


It is the process of translating the algorithm or flowchart into the syntax of a given programming
language. You must convert each step of the algorithm into one or more statements in a programming
language such as C, C++ etc.

108
Problem Solving Methodology

5.5.2 Testing and debugging


Testing
eÁw means running the program, executing all its instructions/functions and checking the logic by
entering sample data to check the output.
Debugging is the process of finding and correcting program code mistakes that are called errors.
There are three types of errors. They are
• Syntax errors
• Run-time errors
• Logic errors (or so called bugs).
Field testing is realized by users that operate the software with the purpose of locating
problems.
In order to achieve the required output, the program that is written in coding phase must be tested,
compiled and then executed.

Role of a Compiler
The first task of the compiler is to analyze the program for correctness and detects errors
if any. During compilation, certain errors are detected by the compiler and then indicated. These
errors constitute the grammatical errors in the programming language. They are known as syntax
errors.
Syntax errors: These are the errors occur when grammatical rules of the programming language is
violated.

Example 5.8:
int main()
{
int x, y
cout << “Type two integer values:”;
cin >> x >> y:
cout << x*y;
return 0
}
The first statement of main() produces a syntax error as the missing semicolon. The third
statement also has an error as the statement is terminated by colon (:) rather than semicolon (;).
These errors have to be rectified and then recompiled. The corrected program is then
executed.
During execution of the program, some errors may occur. Such errors are called run-time Errors.
For example, attempting to divide by zero gives a “Division by Zero” error message. These errors are
corrected by modifying and recompiling the source program and then execute the object program again.
Run time errors are frequently known as Bugs.

109
Problem Solving Methodology

Semantic Error
Consider an arithmetic expression Y = A + B indicating that values of the variables A and B are
added and assigned to variable Y.
If written as A + B = Y, though values of A and B are added, it cannot be assigned to variable Y
written to the right of = sign. This is semantic error.

Debugging
It is the process of identifying and correcting or removing the Bugs.
Sometimes programs may have errors known as logical errors. Suppose the given problem is
to find the area of the circle, given its radius. The formula to be used is area = 3 .1415*rad*rad.
But if it is written as area = 2*3*14*r, then the required output is not obtained even though
the program is successfully executed. In this case, the algorithm has to be modified in the design
phase and the source code has to be changed, recompiled and the object code has to be executed
once again. Complete testing involves execution of the program many times with various possible
inputs.
Testing a program for correctness is an essential step in obtaining the successful computer solution
for a given problem. Testing of a program is a process of executing the program with a set of sample data
and check the output for correctness.

5.6 Documentation and maintenance


Documentation is a reference material which explains the use and maintenance of the program or
application for which it has been written. It could be in the form of a separate printed document or as a
help file in the program itself.
There are two types of documentation -internal documentation and external
documentation.
Internal documentation
This is also known as technical documentation. It is meant for the programmer who may update the
program code at later stages. It is done by:
 Defining meaningful variable names.
 Including remarks or comments in the program code.
 Adding remarks on every module indicating its purpose.
 Presenting the program code clearly by inserting spaces, blank lines and using
indentation.

External documentation
The program or application is supported with additional textual information about the application. It
is useful for the user, administrator or developer (for subsequent modifications).

110
Problem Solving Methodology

Accordingly there are 3 types of documents:


a. eÁw
User’s manual
b. Administrator’s manual
c. Developer’s manual
User’s manual contains the operating instructions of the application for the user.
Administrator’s manual contains instructions for the user who is going to manage the application in
future.
Developer’s manual contains low level flowcharts, data dictionaries, decision tables, files and complete
system chart so that the application can be easily updated.

Maintenance
Programs that are developed become outdated with time. Sometimes errors may creep in.
Depending on the changing rules and user’s requirements, programs need to be modified.
Program maintenance means periodic review of the programs and modifications based on user’s
requirements.
To improve the clarity, fresh documentation may be needed. Maintenance is a continuous task.
Documentation plays an important role in program maintenance. It helps speedy and efficient maintenance.

5.7 Programming constructs


Every language has syntax of its own. Syntax of a language is a set of rules by which various elements
occurring in that language are defined. In English language words, sentences and paragraphs are
constructed using its character set and punctuation marks etc. A computer language has its own character
set which is the building block of the program. Program statements can be constructed using the characters
from the character set of the language.
Pseudo code is another notation for expressing an algorithm. It is a mixture of English and
computer instructions. It uses English words or sentences and computer programming language words
such as IF, THEN, ELSE, DO WHILE, FOR, READ, WRITE and END etc.
A programming construct is a statement in a program. There are 3 basic programming constructs:
i. Sequential.
ii. Selection.
iii. Iteration.

111
Problem Solving Methodology

i. Sequential Construct
In a sequential construct, the program statements are executed one after another, in a sequence.
There will be no backward or forward references.
Single Entry

s1

S2

s3

s4

Single Exit

s1, s2, s3 and s4 are simple statements which could be any one of the following:
a. Input statement
b. Assignment statement
c. Output statement

a. Input statement
This statement is used to input value(s) into the variable(s) from the input device.
Example 5.9 INPUT a, b, c
This input statement indicates that 3 values should be read from the input device will be put into the
variables a, b and c respectively. Variable refers to a specific memory locations.

b. Assignment statement
This statement is used to store a value in a variable. In many languages the character = is used as the
assignment operator.
Example 5.10 a=b
The value of the variable b is assigned to variable a.
Example 5.11: c = 10
This means that value 10 is assigned to the variable c.
Example 5.12: i = i +1
The value of the variable is incremented by one unit. Suppose I has the value 15 before executing the
statement, after execution i becomes 16. The old value 15 is lost.

112
Problem Solving Methodology

Example 5.13: z=x+y


The values of the variables x and y are added and the sum is stored in variable into the variable z.
eÁw

c. Output statement
This statement is used to display the values of variables on the standard output device. The word
OUTPUT, DISPLAY, WRITE and PRINT are used for this purpose.
Example 5.13: PRINT a, b, c
This statement takes the values of variables a, b, c from memory and prints them on an output
device.

ii. Selection construct


It is also known as conditional construct. This structure (or construct or statement) helps the
programmer to take appropriate decision. The decision or selection is normally expressed as a
condition.
There are five kinds of selection constructs. They are
a. Simple - if
b. if - else
c. if – else – if
d. Nested if
e. Multiple selection

a. Simple – if
This structure helps to decide the execution of a particular statement (or set of statements) based on
a condition. This statement is also called as one-way branch.
The general form of simple – if statement is
if (test-condition)
statement-1;
statement-2;
Here, statement-1 can be simple or compound statement.

113
Problem Solving Methodology

F
Is
test-condition?

T
Statement-1

Statement-2

First, the test-condition is tested. If the test-condition is TRUE then statement-1 is executed.
Otherwise ( if the test-condition is FALSE), statement-2 is executed. In the syntax, test-condition is
any expression that gives TRUE or FALSE.

Example 5.15 if (amount t>= 5000)


discount = amount * (10/100)
net-amount = amount - discount

if-else statement
This statement is used to decide whether a set of statements should be executed or another set of
statements should be executed. This statement is also called as two-way branch.
The general form of if-else statement is
if (test-condition)
statement-1;
else
statement-2;

T F
Is
test-condition?

Statement-1 Statement-2

114
Problem Solving Methodology

The test-condition is tested. If the test-condition is TRUE, statement-1 is executed. Otherwise,


statement-2
eÁw
is executed.
Example 5.15 if (amount >= 5000)
discount = discount * (10/100)
else
discount = discount * (5/100)
Example 5.16 if (n % 2 = 0)
PRINT n, “is even”
else
PRINT n, “is odd”

if-else-if statement
This structure help the programmer to decide the execution of a statement from multiple statements
based on a condition. There will be more than one condition to test. Therefore, this statement is also called
as multiple-way branch.
The general form is
if test-condition-1
statement-1
else
if test-condition-2
statement-2
else
…….
else
if (test-condition-n)
statement-n;
else
default-statement;

115
Problem Solving Methodology

Is F
Condition-1
?

T
Is F
Statement-1 Condition-2
?

Statement-2
Is F
Condition-n
?

Statement-n default-statement

Condition-1 is tested. If it is TRUE, statement-1 is executed control is transferred out of the structure.
Otherwise, condition-2 is tested. If it is TRUE, statement-2 is executed control is transferred out of the
structure, and so on. If none of the conditions is satisfied, a statement called default-statement is executed.
Example 5.17:
if (marks >= 85)
PRINT “DISTINCTION”
else
if (marks >= 60)
PRINT “FIRST CLASS”
else
if (marks >= 50)
PRINT “SECOND CLASS”
else
if (marks >= 35)
PRINT “PROMOTED”
else
PRINT “DETAINED”
116
Problem Solving Methodology

Nested-if statement
It iseÁw
possible to write an if statement within another if statement. Such if statement is called as nested-
if statement. i.e., the statement within the if statement is another if statement.
The general form of nested if statement is
if(test-condition-1)
if (test-condition-2)
statement-1
else
statement-2
else
if (test-condition-3)
statement-3
else
statement-4

F Is
T
condition-1?

F Is
T F Is
T
condition-3? condition-2

statement-4 statement-3 statement-2 statement-1

Example 5.12 To find the greatest of three numbers a, b and c


if (a>b)
if(a>c)
OUTPUT a
else
OUTPUT c
else
if(b>c)
OUTPUT b
else
OUTPUT c

117
Problem Solving Methodology

Multiple Selection Construct or switch Statement


If there are more than two alternatives to be selected, multiple selection construct is used.
The general form is
Switch (Expression)
{
Case label-1: statement-1;
break;
case label-2: statement-2;
break;
………
case label-n: statement-n;
break;
default : default-statement;
}

Is
expression

=label-1? =label-2? =label-n? default

statement-1 statement-2 statement-n default-statement

Case labels can be integers, characters, Boolean on enumerated data items. Each case label indicates
the value of the expression for which the associated statement is to be executed.
When the switch statement is executed, first the expression is evaluated. The value of the expression
is then compared with each of the case labels. The statement whose label matches with the expression is
executed and then control comes out of the construct. When no match occurs, the default-statement
mentioned in the default label is executed. The switch statement is similar to if-else-if construct.

118
Problem Solving Methodology

Example 5.13 To find the name of the day given the day number
eÁw switch (dayno)
{
case 1: PRINT “Sunday”;
break;
case 2: PRINT “Monday”;
break;
case 3: PRINT “Tuesday”;
break;
case 4: PRINT “Wednesday”;
break;
case 5: PRINT “Thursday”;
break;
case 6: PRINT “Friday”;
break;
case 7: PRINT “Saturday”;
break;
default: PRINT “Invalid day number”;
}

Iterative Constructs or Looping


In some problems, we need to execute a statement or set of statements until some condition is
satisfied. For this purpose iterative statements are used.
Iterative statements are the statements that are used to repeatedly execute a sequence of statements
until some condition is satisfied or a given number of times. Iterative statements are also called as repetitive
statements or looping statements.
The process of repeated execution of a sequence of statements until some condition is satisfied is
called as iteration or repetition or loop.
There are two iterative constructs:
i. Conditional looping
ii. Unconditional looping.

i. Conditional Looping:
This statement executes a group of instructions repeatedly until some logical condition is satisfied.
The number of repetitions will not be known in advance. The two conditional looping constructs arewhile
and do-while.

ii. Unconditional Looping:


This statement executes of a group of instructions is repeated for specified number of times. The
unconditional looping construct is for statement.

119
Problem Solving Methodology

while construct
This is a pre-tested loop structure. This structure checks the condition at the beginning of the structure.
The set of statements are executed again and again until the condition is true. When the condition becomes
false, control is transferred out of the structure.
The general form is while structure is
while(test-condition)
statement-1
statement-2
…….
statement-n
End of while

Is F
test-c Ondition
?

T
statement- 1
statement- 2
……
statement- n

Example 5.14 i = 1;
while (i <= 5)
PRINT i
i=i+1
end of while
Output: 1 2 3 4 5
The variable i is first initialized to 1. The statements inside the while structure displays the value of the
variable i and then increment by 1. This process continues until the condition is TRUE. When the condition
becomes FALSE, control is transferred out of the structure.

120
Problem Solving Methodology

do-while construct
This
eÁwis a post-tested loop structure. This structure checks the condition at the end of the structure.
The set of statements are executed again and again until the condition is true. When the condition becomes
false, control is transferred out of the structure.
The general form is while structure is
do
statement-1
statement-2
…….
statement-n
while(test-condition);

statement-1
statement-2
……
statement-n

T Is
test-condition?

Example 5.15 sum = 0;


i = 1;
do
sum = sum + i;
i = i + 1;
while (i <= 100);

The variables sum and i are first initialized to 0 and 1 respectively. The statements inside the structure
repeatedly find the sum of all numbers from 1 to 100. The calculated sum is stored in the variable sum.

for construct
This structure is the fixed execution structure. This structure is usually used when we know in
advance exactly how many times a set of statements is to be repeatedly executed again and again. This
structure can be used as increment looping structure or decrementing looping structure.

121
Problem Solving Methodology

The general form of this structure in a programming language is as follows:


for ( expression1; expression2; expression3)
{
statement-1;
statement-2;
———
statement-n;
}
Where, expression 1 represents initialization
expression 2 represents condition
expression 3 represents incrementation

for CV = IV to FV

statement-1
statement-2 CV=Control variable
------ IV=Initial value
statement-n FV=Final value

CV

The initialization is an expression which initializes the loop counter or a control variable.
The condition is logical expression that determines the repetition of the loop and updating is an
expression that increments or decrements the loop counter depending on the requirement.
Example 5.16 A program segment to find the sum of first 50 natural numbers.
Algorithm: sum = 0
for i = 1 to 50
sum = sum + i
End of for
Program segment: sum = 0;
for ( i = 1; i <= 50; i++)
sum = sum + i;

122
Problem Solving Methodology

After you write the algorithm you must realize step-by-step simulation of the computer execution of
the algorithm
eÁw
in a so called desk-check process (verifying the algorithm).

5.8 Characteristics of a good program


The best program (or algorithm) to solve a given problem is one that requires less space in memory,
take less time to complete its execution, easy to modify and portable.
Modification: A good program is the one which allows any modifications easily whenever
needed.
Portability: A good program is the one which can be run on different type of machines with a
minimum or no change.

Figure 1: Life cycle of a computerized process

123
fileAdd the needed libraries or
Reregister them in register
Database and re-link
Problem Solving Methodology

124
Problem Solving Methodology

5.8.1 Types of Errors:


There
eÁw are four types of errors. They are,
• Syntax errors
• Semantic errors
• Logical error
• Run-time errors

Syntax error:
Syntax is the set of rules which should followed while creating the statements of the
program.
The grammatical mistakes in the statements of the program are called syntax errors.

Semantic error:
Semantic refers to the logic, which should be followed while representing the solution. The wrong
use of logic in the program is termed as semantic error.

Logical error:
If the correct translation of algorithm causes the program to produce wrong results, the error is called
as logical error.

Run-time error:
Errors that are detected during the execution of the program is called as runtime error.

5.9 Approaches to Problem Solving


5.9.1 Top-down Design:
Top-down design involves dividing a problem into sub-problems and further dividing the sub problems
into smaller sub-problems until it leads to sub-problems that can be implemented as program statements.
The top-down structure can be viewed as a tree structure, a typical of which is shown in following
figure. In this case main problem A is divided into three sub problems denoted by B, C and D. The sub
problems B and D require further divisions and in this process, the sub problems E, F, C, G and H are
assumed to be simple enough to be easily programmed in the source language.

125
Problem Solving Methodology

B C D

E F G H

Figure 3: A typical top-down structure.


Figure 3: A typical top-down structure.
The top-down approach has the following advantages:
1. It imitates the human tendency to solve a problem by outlining the broad concepts first and then
subsequently going into the details. The details can be worked out with no (or minimum) change.
2. The assumptions at a level continues and the development of next level sub problems can take
place in parallel.

These advantages suggests that if the top-down approach is taken for program design, the programs
can be developed easily, quickly, committing a minimum of errors.
Example: Convert a given temperature in Fahrenheit to and Centigrade and vice-versa.

Temperature
conversion

Selection
Menu

Fahrenheit to Centigrade to
Centigrade Fahrenheit

Input Convert the Output Input Convert the Output


Fahrenheit temperature C Centigrade temperature F

C = (F – 32) * 5/9 F = (9/5 * C) + 32

Figure 4: Top-down analysis of temperature conversion problem.

126
Problem Solving Methodology

5.9.2 Stepwise refinement


The
eÁwprocess of breaking down the problem at each stage to obtain a computer solution is called
stepwise refinement.
GENERAL
OUTLINE

Input condition Body of algorithm Output requirement

Sub task 1 Sub task 2 Sub task 3

Sub task 1a ------ Sub task 2a --------


--
Figure 5: Stepwise refinement

5.9.3 Bottom-up Design:


This approach is the reverse of top-down design. The process starts with identification of set of
modules which are either available or to be constructed. An attempt is made to combine the lower level
modules to form modules of high level. This process of combining modules is continued until the program
is realized. In this case, small subtasks are implemented and tested first and then such sub-problems are
combined together to give a larger solution to the entire problem. Examples include object oriented
programming using C++, small talk etc. The basic drawback of the bottom-up approach is the assumption
that the lowest level modules can be completely specified beforehand, which in reality is seldom possible.
Thus, in the bottom-up approach, quite often it is found that the final program obtained by combining the
predetermined lowest level modules does not meet all the requirement of the desired program.

5.9.4 Programming techniques:


Programming methods in practice since evolution of computer programming are as follows
i. Unstructured programming
ii. Procedural programming
iii. Modular programming
iv. Object-oriented programming

127
Problem Solving Methodology

i. Unstructured programming
Usually, people start learning Programming by writing small and simple programs consisting
only of one main program. Here “main program” stands for a sequence of commands or statements
which modify data which is global throughout the whole program. This can illustrate as shown in the
following figure.

Program

Main program
data

Figure 6: Unstructured programming. The main program directly operates on global data

This programming technique provides tremendous disadvantages once the program gets sufficiently
large. For example, if the same statement sequence is needed at different locations within the program, the
sequence must be copied. This has led to the idea to extract these sequences, name them and offering a
technique to call and return from these procedures.

ii. Procedural programming


This method allows us to combine the returning sequences of statements into one single place. A
procedure call is used to invoke the procedure. After the sequence is processed, flow of control proceeds
right after the position where the call was made.

Main program Procedure

Figure
Figure7: Execution
7: Execution of procedures
of procedures

With introducing parameters as well as procedures, procedures (sub procedures) programs can
now be written as more structured and error free. For example, if a procedure is correct, every time it
produces correct results. Consequently, in case of errors, you can search for errors in those places which
are not proven to be correct.

128
Problem Solving Methodology

Now a program can be viewed as a sequence of procedure calls. The main program is
responsible
eÁw
to pass data to the procedures; the data is processed by the procedure. Once the
program execution is finished, the resulting data is presented. Thus, the flow of data can be
illustrated as a hierarchical graph, a tree, as shown in following figure for a program with no sub
procedures.

Main program data

Procedure1 Procedure2 Procedure3

Figure 8: Procedural programming. The main program coordinates calls to procedures and
hands over appropriate data as parameters.

The above figure represents a single program which is divided into small pieces called
procedures. To enable usage of general procedures or groups of procedures also in other programs,
they must be separately available. For that reason, modular programming allows grouping of
procedures into modules.

i. Structured programming
Structured programming is a method of programming by using the following types of code
structures to write program:
1. Sequence of sequentially executed statements.
2. Conditional execution of statements (i.e., if statements)
3. Looping or iteration (i.e., for, do-while and while statements)
4. Structured subroutines calls (i.e., functions)
In particular, the following language usage is forbidden;
 Goto statements
 Break or continue out of middle of loops
 Multiple exit points to a function/procedure/subroutine ( i.e., multiple return
statements)
 Multiple entry points to a function/procedure/subroutine/method

ii. Modular programming


The process of splitting the lengthier and complex programs into number of smaller units
(modules) is called modularization. And programming with such an approach is called modular
programming. This technique provides grouping of procedures which are of common
functionality into separate modules. A program therefore no longer consists of only one single part.

129
Problem Solving Methodology

It is now divided into several small parts which interact through procedure calls and which form the
whole program (Fig).
main program data

module 1 module 2

data + data1 data + data2

procedure2 procedure1 procedure2


e

Figure 9: The main program coordinates calls to procedures in separate modules and
Hands over appropriate data as parameters

Each module can have its own data. This allows each module to manage an internal state which is
modified by calls to procedures of this module. However, there is only one state per module and each
module exists at most once in the whole program.
Advantages of modular programming
There are many advantages of using modularity in programming. Some of them are as
follows:
1. Reusability: If a particular set of instructions is to be executed repeatedly from several
different places within the program, then we can make this group of instructions as one
module and call it whenever necessary. This avoids rewriting the same function every time we
need it.
2. Debugging is easier: Since each module is smaller and clearer, the user can easily locate the
errors and correct them.
3. Building Library: It is possible for the programmer to build his/her own library of the
most commonly used functions. This reduces the time and space requirements of the
programs.
4. Portability: Since the functions and library are common across different Operating
Systems, it is easier for us to port and execute them without much or no modifications.

130
Problem Solving Methodology

Review Question
eÁw
One mark questions:
1. What are the steps involved in Problem Analysis?
2. What is Structured Programming?
3. Explain the sequential construct.
4. What are the tools used in the design of problems?
5. What is a flowchart?
6. What is an Algorithm?
7. Mention the rules for drawing a flowchart.
8. Give the advantage of flowchart.
9. What is testing?
10. Define Debugging?
11. What is syntax error?
12. What is Run time error?
13. What is Logical error?
14. What is Top down design?
15. What is Bottom up design?
16. Define Stepwise refinement.
17. Define coding.
18. Give the advantages of structured programming.
19. What is Multiple Selection?
20. What are the types of Iteration constructs?
21. What is Unconditional looping?
22. What are the types of selection constructs.
23. Explain single entry and single-exit concept structured programming.

Two marks questions:


1. Explain the concept of structured programming.
2. What are the advantages of structured programming?
3. Write the various symbols used in a flowchart.
4. Explain the various types of errors detected during testing.
5. What are the features of an Algorithm?
6. Explain Conditional looping.

Three marks questions:


1. What are the types of FOR loops?
2. Briefly explain the various stages of Problem Solving.
3. Explain the problem definition phase.

131
Problem Solving Methodology

4. Write a note on Testing and Debugging.


5. Briefly explain Documentation and Maintenance.
6. Explain Modular Design.
7. Explain top-down design ?
8. Give the syntax, flowchart for if-else construct explain, with an example.
9. Give the syntax and flowchart of if-else and else-if construct explain with an example.
10. Explain WHILE-DO construct with an example.
11. Explain DO-WHILE construct with an example.

132
eÁw

CHAPTER 6
Object Oriented Concepts

OBJECTIVES
To Understand the basic concepts of Object Oriented Methodology

133
134
Object Oriented Concepts

6.1 Introduction and Evolution of programming languages


The computer technology has evolved at such a fast rate that yesterday’s (i.e., some 25 years ago)
eÁw
mainframes are today’s personal computers. The software industry is also growing at the same
rate proportionally. The operations are becoming more and more complex but, more user friendly, and the
software engineers felt that it was difficult to implement these complex designs using traditional
programming languages (i.e., procedural languages or structured programming languages). The
programming languages that adopted the procedural and structured programming approach were PASCAL,
C, COBOL, etc. Generally these languages deal with two important aspects – data and algorithm.
Data is the main substance of the program and the algorithms are the methods that use these
programs. They found that these traditional methods of programming was lengthy, expensive,
error prone, lacked reusability, difficult to maintain and sometimes even disastrous. Therefore, this lead
to the revival of the third generation languages and the result was the fourth generation which
further gave birth to the fifth generation languages which was called as Object Oriented Programming
System concepts (OOP).

6.1.1 Procedural Programming


The procedural programming focuses on processing of instructions in order to perform a desired
computation. Therefore it emphasizes more on doing things i.e. on algorithms. Programming using
procedural languages set a threat as the length and complexity of the problem increased. For example,
procedural programs make use of branching statements, where the flow of control changes its path according
to the result of the test expression. Many programs had these routing and it was difficult to understand
and modify them.

6.1.2 Structured Programming


The difficulties in procedural programming languages gave a way to the scientists to develop
C language which was better language when compared to the procedural languages. It gave a new idea
of programming approach called as “Structured Programming”. Structured Programming
approach was a disciplined approach which limited the branching to a small set of well-behaved
construction (i.e., if – else statement, for loop, while loop, do while loop and so on). C followed the
top-down principle of programming. The idea of Top-down design is to break a large program into
smaller programs, and the smaller programs into still smaller sub-programs further until it can be
implemented for computer solution. However, the structured programming technique reflected the
procedural programming method itself, because it lacked the required clarity, reliability and ease of
program maintenance as the program length grew in its size. The major drawback of both the
procedural and structured programming is that it is very difficult to model the real world using these
methods.

135
Object Oriented Concepts

6.1.3 Object oriented Programming


OOP emphasizes on data unlike the structured programming which emphasizes on program. i.e., the
ideology here is to unite both the data and the functions that operate on that data into a single unit called as
"object". This can be pasteurized as shown in fig 6.1.

Object X Object Y

Data Data

Functions Functions

Object Z

Data

Functions

Figure 6.1 Objects

Therefore, an object is an identifiable entity with some characteristics and behavior.

Object Oriented Programming (OOP) is a concept that combines both the data and the functions
that operate on that data into a single unit called the object.

Object is an identifiable entity with some characteristics and behavior.

Top-down design is an approach of dividing a problem into sub problems and then dividing the
sub problems further into still smaller sub problems until it can be implemented for a computer
solution.

Bottom up design is the vice versa where solutions to smaller modules are integrated together to find
the solution of the overall program.

136
Object Oriented Concepts

Object oriented approach is simple and improves software reusability. OOPs view any problem as
object rather
eÁw
than as a procedure. For example, we can say ‘mobile’ is an object and its characteristics
are colour, weight, display, size etc. Its features include price, voice call, video call, memory size etc. Here
OOP considers the characteristics as data and features as functions.
Furthermore, OOP follows ‘Bottom-Up’ approach of programming which is exactly the vise-
versa of the Top-Down approach. Here, in Bottom-Up approach we integrate the solution of smaller
subprograms together in order to find the solution of the overall entire program.
Another important concept with respect to OOP is the ‘Class’. A class serves as a plan or blueprint
that specifies what data and what functions should be included in the objects of that class.

A class is a template that represents a group of objects which share common properties and
relationships.

6.2 OOPs characteristics


OOPs was designed in order to overcome the drawbacks of structured, modular programming
approach. The general concepts of OOPs includes
 Modularity
 Abstraction
 Data Encapsulation
 Inheritance
 Polymorphism
 Dynamic binding
 Message Passing

6.2.1 Modularity
Module: It is a logically self-contained unit that can be tested and executed independently.
Modularity: It is a technique adopted to divide a complex problem into a number of self-contained
independent program segments.

The very idea of dividing or partitioning the program in to smaller sub programs is to
reduce the complexity of the program to certain extent. Modularity helps in achieving this. It also helps
in creating clear cut boundary within a program. A module is a self-contained independent
unit of a program and it can be tested and executed separately even if it is has link with other
modules. For example, let us consider a mobile phone. It will have other features such as a camera to
take still picture or even to make a video, FM to tune on to listen to various channels, internet,
speaker, and memory to store. All of these units are independent modules for capturing pictures, for
listening to radio, sending mail…..etc. Therefore, this is what we actually call modularity. All of these
units are placed inside a case called the mobile phone. Similarly, in object oriented programming
the classes and objects form the logical structure of a system. As the complexity and the length of the
program increases we need to place them in logically contained units called the classes. C++ which is
object oriented programming language implements modularity by placing the programs in units
137
Object Oriented Concepts

called header files and these modules can be included in our application programs also. We need to
include them along in the macro using "#include". These files have an extension of .h and are called
header files. For example,
#include "iostream.h"
#include "math.h" etc.

Here #include is a macro and iostream and math are modules that contain some related files which
can be included in our application programs easily.

6.2.2 Abstraction
Abstraction is an act which represents the essential features of an entity without including explanations
or any background details about it.

This is one of the important characteristics adopted in all programming languages and OOP
implements abstraction using classes as a list of abstract attributes. Let us consider the same example of
the mobile phone. The attributes include the colour, Bluetooth, built in camera etc, we are not
considering how the Bluetooth works, or how the camera works or even how the circuit inside the mobile
is designed and what is happening inside. We are interested only in using the mobile and its features.
Therefore it is required to know how to operate the mobile phone and its other features without knowing
the background details of its design aspects.

6.2.3 Data Encapsulation


The wrapping of data and functions into a single unit called as class known as
encapsulation.
The concept of insulating the data from direct access by the program is called data
hiding

Another important feature of OOP is data encapsulation of a class. The wrapping of data and func-
tions into a single unit called as the class is known as encapsulation. The data is not directly accessible to
the outside world, except for those functions which are wrapped in the class. These functions provide
interface between the object’s data and the program. It is because of this feature that the data seems to be
hidden.

6.2.4 Inheritance
Inheritance is the process by which objects of one class acquires the properties of the objects of
another class.

138
Object Oriented Concepts

OOP support the feature of inheritance to provide the idea of reusability. It is possible to add additional
featureseÁw
to an existing class without modifying it. It supports the concept of hierarchical classification and
the new class is derived from an existing class. Therefore the new class will have the combined features of
both the classes. The fig 1.2 explains the inheritance where we find that student is a class and PUC
student and MBA STUDENT are sub classes derived out of the class student. Each sub class defines only
those features unique to it.

STUDENT

Attributes
Register No.
Name
Class

PUCSTUDENT MBASTUDENT

Attributes Attributes
Marks Grade
Subject Code Electives
………. ………..

Figure 6.2 Inheritance

6.2.5 Polymorphism
Polymorphism is the ability for a message to be processed in more than one form.
The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading.
Using a single function name to perform different types of tasks is known as function
overloading.

Polymorphism is another important concept of OOPs. It is derived from the Greek word, which
means to take more than one form. Just like how the human mind’s thinking pattern keeps changing, an
operation may also behave differently at different instances and the behavior depends on the types of data
used in the operation. For example, the addition operator can be used for adding numbers and also to
concatenate strings.Fig6.3 shows how the single function name is used to handle types and different
number of arguments.

139
Object Oriented Concepts

house object college object

Paint(house) Paint(college)

Items

Paint()

furniture object fabric object

Paint(furniture) Paint(fabric)

Figure 6.3 Polymorphism

Polymorphism allows objects to have different internal structures to share the same external interface.
It supports to implement inheritance to a great extent.

6.2.6 Dynamic Binding

Binding means linking of a procedure call to the code to be executed in response to the
call.
Dynamic Binding means that the code associated with a given procedure call is not known
until the time of the call at run-time. It is associated with polymorphism and inheritance.

A function call that has association with polymorphism depends on the dynamic type of that reference.
We find that each object will have its own task to perform, however it gets redefined to do some other
task when it is used in other class that uses this object. For example, in the fig.6.3 of polymorphism, we
find that the procedure paint ( ) is used to paint a college, house etc, and the procedure will be redefined
in each of these objects.

140
Object Oriented Concepts

6.2.7 Message Passing


In eÁw
OOPs concept message means a request for execution of a procedure for an object. Therefore a
message invokes a procedure in the receiving object to generate the desired output. For example, let us
consider that we have created an object by name ‘college’ and we have calculated the ‘result’
(information) of students by taking their marks (message) into consideration then it is possible to pass
message to this object as represented in the below fig.6.4

college.marks( result)

object message information

Fig. 6.4 Message passing

6.3 OOPs Benefits


OOPs is indeed a very beneficiary tool which help in efficient programming, because the very idea
of using OOPs technique was to overcome the drawbacks of procedural and structured programming
approach. This new technology provides the programmer with greater productivity, quality software at a
less maintenance cost. The major advantages include
 OOPs model the real world entities very well.
 Inheritance extends the use of existing classes and eliminates redundant code hence supports
code reusability.
 Data hiding helps to build secure programs that cannot be invaded by code in other parts of the
program.
 Multiple instances of an object co exist without any interference.
 The work can be divided easily since the projects are object based and each object can be
developed by different people resulting in faster code development.
 OOPS can be easily upgraded from small to large systems.
 Complexity of the software is easily manageable, tested and maintained.
 It is possible to map objects from the problem domain to program domain.
 Message passing technique for communication between the objects makes the interface
description simpler with external systems.
 Standard working modules communicate with one another and we can therefore build programs
from these modules which save development time and increases productivity.
 Data centered design approach helps to capture more details of the model in implementable
form.
We should understand one thing that to develop software, that is easy to use is extremely difficult and
even next to impossible. However object oriented programming tools helps to achieve this to some extent.

141
Object Oriented Concepts

6.4 OOP disadvantages


Every aspect in the universe has both advantages and disadvantages. But we need to understand that
when the percentage of advantages is more compared to disadvantages then there is no harm in accepting
it. However the disadvantages of OOPs are less and are identified below.
 OOPs use tricky methods to do the programming.
 Special skills such as thinking in terms design skills, programming skills and thinking in terms of
objects, are required for a programmer.
 Proper planning and design is required before programming using OOPs technique.

6.5 OOPs Applications


After coming to know the benefits it is required to know the applications also. The most popular
application of OOPs has been in the area of ‘user interface design’ of windows operating system. Many
of the windowing systems have been developed using this technique. Real time systems and embedded
systems are developed using complex attributes and methods. Some of the areas for applications of
OOPs are:
 Object oriented databases.
 Hypermedia, expert text and hypertext.
 Artificial Intelligence and expert systems.
 Decision support systems and office automation systems.
 Parallel programming and neural networks.
 CAD, CAM, CIM systems.
 Simulation and modeling.

Henceforth the OOPs approach has actually improved the quality of software and also has increased
productivity. This approach has magically brought about an evolution in the software world.

142
Object Oriented Concepts

Review Questions:
eÁw
One mark questions:
1. Define Structured Programming.
2. Define Top-down design.
3. What is Bottom up?
4. What is Top-down?
5. Define an Object.
6. What is Object Oriented Programming (OOP)?
7. What is Class?
8. Define a Module.
9. What is Bottom up approach?
10. What is Modularity?
11. What is Abstraction?
12. What is Data Encapsulation.?
13. What is Inheritance?
14. What is Polymorphism?
15. What is Dynamic binding?
16. What is Message Passing?
17. Mention any one benefit of OOP.
18. Mention any one advantage of OOP.
19. Mention any one disadvantage of OOP.
20. Mention any one application of OOP.

Two marks questions


1. Differentiate between structured programming and object oriented programming.
2. Mention any two characteristics of OOP.
3. Briefly explain about Data Encapsulation.
4. Briefly explain about Inheritance.
5. Briefly explain about Polymorphism.
6. Briefly explain about Dynamic binding.
7. Briefly explain about Message Passing.
8. Mention any two benefits of OOP.
9. Mention any two OOP advantages of OOP.
10. Mention any two OOP disadvantages of OOP
11. .Mention any two OOP applications of OOP.

Three marks questions


1. Explain in detail about any four characteristics of OOP.

143
Object Oriented Concepts

2. Explain in detail about Data Encapsulation and Inheritance.


3. Explain in detail about Polymorphism and Dynamic binding.
4. Briefly explain about Dynamic binding and Message Passing.
5. Mention any two advantages and two disadvantages of OOP.
6. Mention any four advantages of OOP.
7. Mention any four benefits of OOP.
8. Mention any four applications of OOP.

Five marks questions:


1. What is OOP? Describe in detail the various characteristics of OOP with suitable examples.
2. Mention the various advantages and two disadvantages of OOP.
3. Mention the various applications of OOP.
4. Mention the various benefits of OOP.

144
eÁw

CHAPTER 7
Introduction to C++

OBJECTIVES
To Understand the basic features of C++ as a OPP language/

145
146
Introduction to C++

7.1 Introduction and History


Until
eÁw 1980, C programming was widely popular, and slowly people started realizing the
drawbacks of this language and at the same time, the engineers had come up with a new programming
approach that was Object Oriented programming. This approach of programming was capable enough to
overcome the previous drawbacks. Using this concept, Bjarne Stroustrup developed C++at AT & T Bell
Laboratories in Murray Hill, New Jersey. He developed this language in early 1980’s and was very much
concerned in making C++ more efficient. He based C++on C because C was much suitable to system
programming, and was widely available. He has also based C++ on another OOP featured language
called Simula67.
C++ is a superset of C because, any valid C program is a valid C++ program too but the vice versa
is not true. This can be clearly understood when we look at the fig7.1where we can understand there
relationship between C and C++. C++ can make use of existing C software libraries with major addition
of ‘class construct’. Therefore, the C++ programmers not only make use of the new features but also
have the privilege of using the traditional C features.
In the early stages, this language was called ‘C with classes’ and later in 1983, it was named
‘C++’ by Rick Mascitti. The ++ comes from the increment operator ++ which means C++ is an augmented
version of C. Finally C++ obtained anew outlook in the year 1997 when the ANSI/ISO standards
committee standardized the language by adding new features to it.

Figure 7.1 OOPs features

7.2 Characteristics of C++


C++ has certain characteristics over other programming languages. It provides huge
Function Library, that’s why its popularity is increasing day by day and more programmers are inclining
towards C++ due to its multiple features. The most remarkable ones are:
 Object-oriented programming: The possibility to orient programming to objects allows the
programmer to design applications from a point of view more like a communication between
objects rather than on a structured sequence of code. In addition it allows a greater reusability of
code in a more logical and productive way.

147
Introduction to C++

 Portability: We can practically compile the same C++ code in almost any type of computer
and operating system without making any changes. C++ is the most used and ported programming
language in the world.
 Brevity: Code written in C++ is very short in comparison with other languages, since the use of
special characters is preferred to key words, saving some effort to the programmer (and
prolonging the life of our keyboards!).
 Modular programming: An application’s body in C++ can be made up of several source code
files that are compiled separately and then linked together saving time, since it is not necessary to
recompile the complete application when making a single change, but only in the file that contains
it. In addition, this characteristic allows to link C++ code with code produced in other languages,
such as Assembler or C.
 C Compatibility: C++ is backward compatible with the C language. Any code written in C can
easily be included in a C++ program without making any change.
 Speed: The resulting code from a C++ compilation is very efficient due to its duality as high-
level and low-level language and to the reduced size of the language itself.
 Machine independent: It is a Machine Independent Language.
 Flexibility: It is highly flexible language with Versatility.
 Wide range of library functions: It has huge Library Functions which in turn reduces the code
development time and also reduces cost of software development.
 System Software development: It can be used for developing System Software viz., operating
systems, compilers, editors and data bases.

7.3 C++ character set and tokens


Character set means the valid set of characters that a language recognizes. The character set includes
letters, digits or any other sign. The following are the character set in C++.
Digits : 0 -9
Alphabets : a – z (lowercase alphabets) and A – Z (uppercase alphabets)
Special characters : + - / { } ( )% “ ? : != * blank space \ |& (these are some
Of characters which are the building blocks and they form the basic
program elements).
However, C++ is designed in such a way that it is capable of processing any of the 256 ASCII
characters as data or as literals.

A token is a smallest individual unit in a program or a lexical unit.

The most fundamental elements of a C++ program are “tokens” or lexical elements. These elements
help us to construct statements, definitions, declarations, and so on, which in turn helps us to construct

148
Introduction to C++

complete programs. Indeed, all the programming languages are made up of these individual syntax ele-
ments called
eÁw
tokens .C++ has following tokens.
 Identifiers
 Keywords
 Constants or Literals
 Punctuators
 Operators

7.3.1 Identifiers

An identifier is a name given to the programming elements such as variables, arrays, functions etc. It can
contain letter, digits and underscore. C++ is case sensitive and henceforth it treats uppercase and
lowercase characters differently.

Identifiers are the names given to program elements (program elements include variables, arrays,
functions, etc.). It is important to note that C++ is case sensitive and it treats uppercase and lowercase
characters differently. The following are some of the valid identifiers in C++.
Student _amount marks1 total_ score
STUDENT _AMOUNT RANK5 _Ad12
The following are some of the invalid identifiers:
34data - starts with a digit
reg-no - contains a special character ‘-‘
public - reserved word
Therefore, we can summarize the rules for naming an identifier as

 Identifiers are a sequence of characters which should begin with the alphabet either from
A-Z (uppercase) or a-z (lowercase) or _(underscore).
 C++ treats uppercase and lowercase characters differently.
For example, DATA is not same as data.
 No special character is allowed except _ (underscore).
 A keyword cannot be used for naming an identifier.
 Identifiers should be of reasonable length (but ANSI C has not enforced any restriction on
this aspect).

C++ treats uppercase and lowercase differently. But we can use the keywords in uppercase as identifiers,
since the complier considers while, if etc. as keywords. But it does not consider the same words in
uppercase i.e., WHILE, IF etc. as identifiers. However it is not treated as a good programming practice
to make use of keywords as identifiers.

149
Introduction to C++

7.3.2 Keywords
Keyword is a predefined word that gives special meaning to the compiler. They are reserved words
which can be used for their intended purpose and should not be used as normal identifier. There are
keywords in C++ (developed by Stroustrup) as mentioned in Table7.1.
alignas (since C++11) enum return
alignof (since C++11) explicit short
and export signed
and_eq extern sizeof
asm false static
auto(1) float static_assert(since C++11)
bitand for static_cast
bitor friend struct
bool goto switch
break if template
case inline this
catch int thread_local(since C++11)
char long throw
char16_t(since C++11) mutable true
char32_t(since C++11) namespace try
class new typedef
compl noexcept(since C++11) typeid
const not typename
constexpr(since C++11) not_eq union
const_cast nullptr (since C++11) unsigned
continue operator using(1)
decltype(since C++11) or virtual
default(1) or_eq void
delete(1) private volatile
do protected wchar_t
double public while
dynamic_cast register xor
else reinterpret_cast xor_eq

Table7.1 Keywords NOTE: In Table 7.1 (since C++11)means revised in the year 2011.

Keyword is a predefined word and has special meaning to the compiler. The programmer is not allowed
to change its meaning,

150
Introduction to C++

Invariant program elements are called “literals” or “constants.” The terms “literal” and “constant” are
used interchangeably.Figure7.2
eÁw
shows the clear classification of literals. They are program elements whose
value does not change during program execution. A literal may be any of the following:
 Integer constant
 Floating constant
 Character constant
 String literal

Figure 7.2 Constants and its types

Constant is a fixed value that does not change during the execution of the program.

7.3.3.1 Integer constants


Integer constants are constants that have no fractional parts or exponents. They always begin with a
digit. We can specify integer constants in decimal, octal, or hexadecimal form. They can specify signed or
unsigned types and long or short types. When we want to specify integer constants using octal or hexadecimal
notation, we use a prefix that denotes the base and when we want to specify an integer constant of a given
integral type, we use a suffix that denotes the type.
Decimal constants: We specify a decimal constant with a nonzero digit.

Example 7.1:
int a = 1587; // Decimal constant
int b = -148; // A negative decimal constant
int c = 065; // Leading zero specifies octal constant, not decimal
151
Introduction to C++

Octal constant:
When we specify an octal constant, we should always begin with 0 followed by a sequence of digits
in the range 0 through 7. The digits 8 and 9 are errors in specifying an octal constant.

Example 7.2:
int a = 0374; // Octal constant
int j = 095; // Error: 9 is not an octal digit

Hexadecimal constants:
When we specify a hexadecimal constant, we should always begin the specification with 0x or 0X
(the case of the “x” does not matter), followed by a sequence of digits in the range 0 through 9 and a (or
A) through f (or F). Hexadecimal digits a (orA) through f(or F) represents values in the range 10 through
15.

Example 7.3:
int a = 0x5fff; // Hexadecimal constant
int b = -0X3FFF;

Unsigned constants:
To specify an unsigned type, use either the u or U suffix. To specify a long type, use either the l or L
suffix.

Example 7.4:
unsigned val= 328u; // Unsigned value
long val= 0x7FFFFFL; // Long value specified as hex constant
unsigned long val = 0776745ul; // Unsigned long value as octal constant

7.3.3.2 Floating point constants


Floating-point constants are also called as ‘real constants’. These values contain decimal
points (.) and can contain exponents. They are used to represent values that will have a fractional
part and can be represented in two forms (i.e., fractional form and exponent form).
Floating-point constants have a “mantissa,” which specifies the value of the number, an
“exponent” which specifies the magnitude of the number, and an optional suffix that specifies the
constant’s type. The mantissa is specified as a sequence of digits followed by a period, followed by an
optional sequence of digits representing the fractional part of the number.

152
Introduction to C++

Example 7.5
eÁw
18 . 45

Integer part Decimal point Fractional part

The exponent, if present, specifies the magnitude of the number as a power of 10, as shown in the
following example 7.6.

Example 7.6
23.46e0 // means it is equal to 23.46 x 100 = 23.46 x 1 = 23.46
23.46e1 // means it is equal to23.46 x 101= 23.46 x10 = 234.6
23.46e-1 // means it is equal to23.46 x 10-1= 23.46 x1/10 =2.346
- 0.2346e-1 // means it is equal to -0.2346 x 10-1= -0.2346x 1/10= -0.02346

The exponent may be specified using e or E, which have the same meaning, followed by an
optional sign (+ or -) and a sequence of digits. If an exponent is present, the trailing decimal point is
unnecessary in whole numbers such as 23E0.
Floating-point constants default to type double. By using the suffixes f or l (or F or L — the
suffix is not case sensitive), the constant can be specified as float or long double, respectively.

7.3.3.3 Character constants


Character constants are specified as single character enclosed in pair of single quotation
marks. For example:
char ch = ‘p’; // Specify normal character constant.

A single character constant such as ‘D’ or ‘r’ will have char data type. These character
constants will be assigned numerical values. The numerical values are the ASCII values which are
numbered sequentially for both uppercase and lowercase characters. For example, ASCII value of A is
65, B is 66,….,Z is 90 (uppercase characters), a is 97, b is 99,….z is 122 (lowercase characters), 0 is
48, 1 is 49,…9 is 57 (for digits). Indeed all the characters on the keyboard are assigned with an ASCII
value.
There is another class of characters which cannot be displayed on the screen (non-graphic characters)
but they have special meaning and are used for special purpose. For example, tab key, carriage return,
backspace and such character constants are called as escape sequences. The following table7.2 shows
the list of escape sequences in C++.

153
Introduction to C++

Escape Description
sequence
\’ single quote
\” double quote
\? question mark
\\ backslash
\0 null character
\a audible bell
\b backspace
\f form feed - new page
\n line feed - new line
\r carriage return
\t horizontal tab
\v vertical tab
\nnn arbitrary octal value
\xnn arbitrary hexadecimal value
Table 7.2 Escape sequences in C++

Escape sequence is a special string used to control output on the monitor and they are represented by
a single character and hence occupy one byte space.

7.3.3.4 String constants


A string literal consists of zero or more characters enclosed by double quotation marks (“). Multiple
character constants are called String constants and they are treated as an array of char. By default the
compiler adds a special character called the ‘null character’ (‘\0’) at the end of the string to mark the end
of the string. For example, the string literal has to be represented as
char str[15] =” C++ Programming”;
This is actually represented as char str[15] =” C++ Programming\0" in the memory.

7.3.4 Punctuators
Punctuators in C++ have syntactic and semantic meaning to the compiler but do not by themselves
specify an operation that yields a value. Some punctuators can be either alone or in combination, and they
can be significant to the preprocessor. The following characters are considered as punctuators:
! % ^ &* ( ) – + = { } | ~
[ ] \ ; ‘ : “<> ? , . / #

154
Introduction to C++

The functions of some of the punctuators is given in the below table 7.3.
eÁw
symbols Illustration
! used along with ‘=’ to indicate ‘not equal to’
% used along with format specifier
& used to represent address location or bitwise and operation
; used to represent statement terminator
[] used to represent array subscript
{} used to represent the starting and ending of a block of code
() used to represent function calls, group expressions, etc.
# used to represent preprocessor directive
\ used to represent escape sequence

Table 7.3 Punctuators

7.3.5 C++ Operators


An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and there are almost 45 different operators. These opera-
tors can be either ‘unary’ or ‘binary’ or even ‘ternary’ operators. The following are the different types
of operators as shown in the figure 7.3.

An operator is a symbol that represents an operation to the compiler.

Operator Name

! Logical NOT. Use to reverses the logical state of its operand. If a


condition is true then Logical NOT operator will make false.
& Address-of. Used to give the address of the operand.
~ One’s complement. Converts 1 to 0 and 0 to 1.
* Pointer dereference. Used along with the operand to represent the
pointer data type.

Figure 7.3 C++ operators

Let us examine all these mentioned operators one by one.

155
Introduction to C++

7.3.5.1 Unary operators


Unary operations have only one operand they are evaluated before any other operations containing
them gets evaluated. The following are the list of unary operators.

Operator Name

! Logical NOT. Use to reverses the logical state of its operand. If a


condition is true then Logical NOT operator will make false.
& Address-of. Used to give the address of the operand.
~ One’s complement. Converts 1 to 0 and 0 to 1.
* Pointer dereference. Used along with the operand to represent the
pointer data type.
+ Unary plus. Used to represent a signed positive operand.
++ Increment. Used to increment an operand by 1.
– Unary negation. Used to represent a signed negative operand.
–– Decrement. Used to decrement an operand by 1.

Table 7.4 Unary operators

In C++, it becomes absolutely necessary to understand about the increment and decrement operators
under unary operators and they operate on a single variable.++ is used to increment the value of the
variable by 1 and the operator can appear before or after the variable and — is used to represent
decrement the value of the operator by 1. Just like the increment operator the decrement operator can
also appear before or after the variable as shown below. Therefore,
a++ or ++a means a=a+1
b— or —b means b=b-1
If the ++/— operator is to the left of the variable then, it is called pre- increment/decrement operator
and if the ++/— operator is to the right of the variable then, it is called post increment/decrement operator.
However, in both the cases of incrementing and decrementing there will be significant change in their
values during the course of the program execution.
Consider the following statements in a program:
int a = 5,b;
…..
b = ++a;
b = a++;
In the first statement, the value of b will be 6 and in the second statement the value of b will be
still 6 and not 7 because in case of post incrementing the value is considered first and then incremented.
b = a++;

156
Introduction to C++

then, the value of b will be still 6 and not 7 because the operator is to the right of the variable
considers
eÁw
the value and then increments it.

Unary operators operate on single operand.

Example7.7 Let b=10, c=20. Evaluate the expression a = ++b + c++;


Solution:
Step1: identify the operands and its associated signs.
Here operand b is pre incremented. Therefore we need to first increment and consider the value.
Hence the value of b = 11.
The operand c is post incremented and therefore first considers the value and then increments.
Hence the value of c=20.

Step 2: Now add both b and c.


We get, a=11+20
=31.
Therefore, a=31 is the answer.

7.3.5.2 Binary operators


The binary operators are those operators that operate on two operands. They are as arithmetic
operators, relational, logical operators, bitwise, assignment operators.

7.3.5.2.1 Arithmetic Operators


The operators supported by C++ are: + - * / %
Let us assume that variable a=10 and variable b=20 then:

Operator Description Example

+ Adds two operands a + b will give 30


- Subtracts second operand from the first a - b will give -10
* Multiply both operands a * b will give 200
/ Divide numerator by denominator b / a will give 2
% Modulus Operator and remainder of after an
integer division b % a will give 0

Table 7.5 Arithmetic Operators

157
Introduction to C++

7.3.5.2.2 Relational Operators


The relational operators supported by C++ are: == !=><>= <=
Let us assume that variable a=5 and variable b=10 then:

Operator Description Example


== Checks if the value of two operands is equal or (a == b) is false.
not.
!= Checks if the value of two operands is equal or (a != b) is true.
not.

> Checks if the value of left operand is greater than (a > b) is false.
the value of right operand.

< Checks if the value of left operand is less than the (a < b) is true.
value of right operand.

>= Checks if the value of left operand is greater than (a >= b) is false.
or equal to the value of right operand.

<= Checks if the value of left operand is less than or a <= b) is true.
equal to the value of right operand.

Table 7.6 Relational Operators

158
Introduction to C++

7.3.5.2.3 Logical Operators


The logical operators supported by C++ are: &&, || and !
eÁw
Let us assume that variable a=0and variable b=1 then:

Operator Description Example


&& Called as Logical AND operator. If both the operands (a && b) is false.
are non-zero then condition becomes true.

|| Called as Logical OR Operator. If any of the two (a || b) is true.


operands is non-zero then condition becomes true.

! Called as Logical NOT Operator. Use to reverses !(a && b) is true.


the logical state of its operand. If a condition is !(a) is true. !(b) is false.
true then Logical NOT operator will make false.

Table7.7 Logical Operators

7.3.5.2.4 Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. The truth tables for bitwise
and(&),bitwise or(|), and bitwise xor (^) are as follows:

a b a&b (Bitwise and) a | b ( Bitwise or) a ^ b ( Bitwise xor)


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Table 7.8 Truth Table

Example 7.8:
Assume that if a = 60; and b = 13; the following operations takes place:
Step 1: converts a and b both to its binary equivalent.
a = 0011 1100
b = 0000 1101
Step 2: then performs the bitwise and, or and not operations. The result is given below.
a&b = 0000 1100 (bitwise and) = 12
a|b = 0011 1101 (bitwise or) = 61
a^b = 0011 0001 (bitwise xor) = 49
~a = 1100 0011 (bitwise not) = -60
159
Introduction to C++

The Bitwise operators supported by C++ are listed in the following table 7.9.

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists (A & B) will give 12 which
in both operands. is 0000 1100
| Binary OR Operator copies a bit if it exists in either oper- (A | B) will give 61 which is
and. 0011 1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is
operand but not both. 0011 0001

~ Binary Ones Complement Operator is unary and has the (~A ) will give -60 which is
effect of ‘flipping’ bits. 1100 0011

<< Binary Left Shift Operator. The left operands value is A << 2 will give 240 which
moved left by the number of bits specified by the right is 1111 0000
operand.

>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15 which is
moved right by the number of bits specified by the right 0000 1111
operand.
Table7.9 Bitwise Operators

7.3.5.2. C++ Shorthands


C++ offers special shorthands that simplify the coding of a certain type of assignment statements.

Example 7.9 a=a+10; Can be written as a+=10;


The operator pair += tells the compiler to assign to the value of a+10. This shorthands works for all
the binary operates in C++(those that require two operands).
The general form of C++ shorthand is
Variable operator= expression
Following are some examples of C++ shorthands:
x-=10 equivalent to x =x-10;
x*=5 equivalent to x =x*5;
x/=2 equivalent to x = x/2;
x%=z equivalent to x =x%z

All assignment operators have lower precedence than the conditional operator (?).

160
Introduction to C++

7.3.5.2.5 Assignment Operators


The
eÁwassignment operators supported by C++ are listed in the table 7.10:

Operator Description Example


= Simple assignment operator, Assigns values from right c = a + b will assign value of
side operands to left side operand a + b into c
+= Add AND assignment operator, It adds right c += a is equivalent to
operand to the left operand and assign the result to left c=c+a
operand
-= Subtract AND assignment operator, It subtracts right c - = a is equivalent to
operand from the left operand and assign the result to left c=c–a
operand

*= Multiply AND assignment operator, It multiplies c *= a is equivalent to


right operand with the left operand and assign the result to c=c*a
left operand
/= Divide AND assignment operator, It divides left c /= a is equivalent to
operand with the right operand and assign the result to left c=c/a
operand

%= Modulus AND assignment operator, It takes c %= a is equivalent to


modulus using two operands and assign the result to left c=c%a
operand

<<= Left shift AND assignment operator c <<= 2 is same as


c = c << 2

>>= Right shift AND assignment operator c >>= 2 is same as


c = c >> 2

&= Bitwise AND assignment operator c &= 2 is same as


c=c&2

^= bitwise exclusive OR and assignment operator c ^= 2 is same as


c=c^2
|= bitwise inclusive OR and assignment operator c |= 2 is same as c = c | 2

Table7.10 Assignment Operators

161
Introduction to C++

7.3.5.2.6 Special Operators


The other operators supported by C++ are listed in the table 7.11:

Operator Description
sizeof () sizeof operator returns the size of a variable. For example
sizeof(a), where a is integer, will return 2.
Comma operator causes a sequence of operations to be
, performed. The value of the entire comma expression is the value
of the last expression of the comma-separated list.
. (dot) and -> (arrow) Member operators used to reference individual members of
classes, structures, and unions.
cast Casting operators convert one data type to another. For example,
int(2.2000) would return 2.

& Address operator & returns the address of a variable.


For example &a; will give actual address of the variable a.
* Pointer operator * is pointer to a variable. For example *a; will
pointer to a variable a.

Table7.11 Other Operators

7.3.5.3 Ternary operators


The ternary operators are those operators that operate on three or more operands. Ternary operator
is also called as conditional operator. The ternary operators are as follows.

Operator Description
? Conditional operator. If condition is true, expression in the TRUE
is selected, otherwise the expression in the FALE part is selected.
Table7.12 Ternary Operator

162
Introduction to C++

The operator that operates on three operands is called the conditional operator or ternary
operator.
eÁw

7.4 Precedence of operators or Hierarchy of operators


At the first it becomes absolutely necessary to know as to what is an expression? An expression is a
combination of opcode and operands. The operators could be arithmetic, relational, and logical or any
one just discussed in the previous section.
If the expression contains multiple operators, the order in which operations are carried out is called
precedence of operators. It is also called as priority or hierarchy.
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:

If the expression contains multiple operators, the order in which operations are carried out is
called precedence of operators. It is also called as priority or hierarchy.

Example 7.9: x = 7 + 3 * 2;

Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get
multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table and those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first. The
precedence of operators along with its associativity is given in the below table 7.13.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ — (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right

163
Introduction to C++

Logical AND && Left to right


Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>=<<= &= ^= |= Right to left
Comma , Left to right
Table7.13 Precedence of operators

What is operator precedence in C++?


“The order in which different types of operators are evaluated is called as operator precedence “. It
is also known as hierarchy of operators. All operators in C++ have their own level of precedence. In any
expression, Operators having higher precedence are evaluated first. The expression is evaluated in
following sequence.
1. Arithmetic
2. Relational
3. Logical
Table 11.14 Shows the Level of Precedence.

Priority Operator Precedence


1 ! Logical Not (highest)
2 ( ) Parenthesis
3 *, /, %
4 +, -
5 >, >=, <, <=
6 ==, !=
7 && ( and)
8 || (or)
9 ! not
Table 7.14 Levels of precedence

The expression in parenthesis is evaluated first. In case of nested parenthesis the part of
expression in the inner most parenthesis is evaluated first. Next, multiplication and division operators are
evaluated. Then, plus and minus operators are evaluated. Relational operators, Logical AND, OR,
NOT and finally the assignment operator are respectively evaluated.

164
Introduction to C++

If the expression contains the operators of equal priority then the operations are performed as first-
come-first-serve
eÁw
basis.

Example 7.10: Consider the expression 5*(4+ (10-6)/2) +5.


 First of all, the expression in inner most parentheses (10-6) is evaluated.
 Second step, result of this expression is divided by 2. It results 2.
 Third step, 2 is added to 4, the entire values in parenthesis gives result equal to 6.
 Last step, 6 is multiplied by 5 which is equal to 30 then finally, added to 5 and final
result is 35.

 Any algebraic expression has to be converted to C++ expression before evaluation.


 All the variables on to the right hand side of the expression should be assigned values before
evaluation.
 If in an expression any two operators have same precedence then, the evaluation is done from
left to right.
 If nested parenthesis is encountered then the innermost parentheses is evaluated first and the
evaluated first.
 Some equivalent C++ expressions are:
 ab – cd is written as a*b – c*d
 is written as x1 =( -b + sqrt(b*b – 4*a*c)) / (2*a) and the other
expression will be x2 =( -b - sqrt(b*b – 4*a*c)) / (2*a)

7.5 Type Conversion


Converting an expression of a given type into another type is known as type-casting or type
conversion.
Type conversions are of two types, they are
 Implicit conversion
 Explicit conversion

7.5.1 Implicit conversion


Implicit conversions do not require any operator. They are automatically performed when a
value is copied to a compatible type. The C++ compiler will implicitly convert or promote values if it can
be done safely. If not it will generate a warning or an error depending on the conversion required. For
example,
short a = 2000;
int b;
b = a;

165
Introduction to C++

Here, the value of a has been promoted from short to int and we have not had to specify any type-
casting operator. This is known as a standard conversion. Standard conversions affect fundamental data
types, and allow conversions such as the conversions between numerical types (short to int, int to float,
double to int...), to or from Boolean, and some pointer conversions. Some of these conversions may
imply a loss of precision, which the compiler can signal with a warning. For example,

const int big =110232343;


const short int small = big;

Here in the above example, the compiler will most likely generate a warning about truncation as
trying to put a large number into a small variable will lose part of the number’. The compiler will make
numbers bigger (never smaller) when evaluating expressions. If you add a float to a double, it will treat
both as doubles. Add an int to a float and both are treated as floats. Add a short int to an int and both will
be added as int, and the same is true with char. For example,

char a = '2';
int b = a + 9;

This is poor code but it compiles and runs. The implicit promotion of ‘2’ to an int with a value of 50
results in it outputting 59.this is because the compiler considers the ASCII value of ‘2’ which is 50 and
therefore it outputs 59. This can be avoided with an explicit conversion.

7.5.2 Explicit conversion


C++ is a strong-typed language. Many conversions, especially those that imply a different
interpretation of the value, require an explicit conversion.

short a = 2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation

Implicit conversion will be performed by the compiler itself, without user intervention. Explicit
conversion will be performed by the user, as his need.

166
Introduction to C++

7.6 Structure of C++ Program


ForeÁw
understanding purpose let us start with a simple C++ program that prints a sentence on the
screen.

Program 7.1 A sample program

#include<iostream.h>
void main()
{
cout<<"This is first C++ program";
}

Sample run: This is first C++ program

The above program contains certain basic elements that all C++ programs possess. In The next
section, we will be able to understand in depth about the actual structure of a C++ program.

7.7 C++ program structure


Let us analyze the structure of a C++ program after knowing about the tokens and operators of
C++. From the below figure 7.4 we will get a clear idea of a C++ program structure. This figure not
only explains the structure but also gives the explanation about each statement simultaneously along with a
simple example beside it.

167
Introduction to C++

Figure 7.4 Detailed Structure of C++ Program

Let us understand each section one by one in detail by considering the above figure 7.4.

Comments or Documentation section


This is generally a comment section as discussed earlier. This section allows us to write comments
about what each statement is doing. Indeed, the comments can be added at the end of each statement in
the program. They are not executed by the complier. But, they definitely provide the required explanation
about the program to the programmers. Single line comments begin with double slash (//) and multiline
comments are enclosed between slash and asterisk ( /* ………*/ ).

Linker Section
#include<iostream.h>
#include<conio.h>
The linker section begins with a hash (#) symbol and #include…. is a preprocessor directive and
these statements are processed first by the compiler and then the rest of the statements are
compiled. These statements tells the compiler to include the header files iostream.h and conio.h into the
program.

168
Introduction to C++

Definition Section
eÁw #define PI 3.14
In this section, we can define constants, expressions, structures, functions, classes and objects. After
the linker section gets executed, the definition section is executed by the compiler and this section is
optional. In the above example, we find that PI is a constant identifier which takes the value 3.14 and
wherever this identifier is used the compiler replaces the value with 3.14 in the program.

Global declaration section


We can declare variables here and those variables which are declared before the main function
or any other function then the life or scope of such variables remain throughout function and can be used
by other functions of the program. This section is also optional and depends on the needs of the applica-
tion that is being developed. Even in the above example we have no variables declared under this section.

main ( ) function
void main( )
This instruction marks the beginning of the main function and it contains the statements that perform
the required task. This statement is executed first by the compiler when the program starts. It is also
important to note that there will be only one main( ) function in a program.

Braces {}
{ Opening braces
…..
…..
…..
} Closing braces

The statements inside any function including the main ( ) function is enclosed with the opening and
closing braces. Therefore we find the { } in the above figure 7.4 also.

Variable declaration section


In the above example program, we have declared variables and also its data types. This helps the
compiler to allocate the memory space inside the computer memory. Those variables declared inside the
function block, the life or scope of such variables remains till the end of that block only.

Executable statements section


Generally, in C++ the statements are written inside the main( ) function or any other function. These
statements can be expressions, input-output functions, conditional statements, looping statements, function
call and so on. In the above fig 7.4, we have seen the example to compute the area and circumference of
the circle.
The cout function statement is a user prompt which tells the user to input the value for the

169
Introduction to C++

radius and the text present inside the double quotes “ input the value of radius: ” is displayed on the output
screen.
The next is thecin function statement which takes the input that is given by the user. The
next two statements are C++ expressions that calculate the area and circumference of the circle
respectively.
Finally, the next two output statements display the computed area and circumference
respectively.

7.7 Importance of iostream.h


As discussed earlier, we have included some other files to our source programs using
the ‘#include<______ .h>’directive in the linker section of the program. The preprocessor is an
instruction to the compiler itself so that it deals with these directives before starting with the real
compilation process for example the first statement in the figure 7.4.

#include directive
The #include directive instructs the compiler to read and include another file in the current file.
The compiler compiles the entire code. A header file may be included in one of two ways.
#include<iostream.h>
or
#include "iostream.h"
The header file in angle brackets means that file reside in standard include directory. The header files
in double quotes means that file reside in current directory.

7.8 LIBRARY FUNCTION


C++ provides many built-in functions that save the programming time. They include
mathematical functions, character functions, string functions, console input–output functions and
some general standard library functions. Some of them are given below and also discussed in detail in
Functions chapter.

7.8.1 Mathematical Functions

170
Introduction to C++

Some of the important mathematical functions in header file math.h are


eÁw
Function Meaning
sin(x) Sine of an angle x (measured in radians)

cos(x) Cosine of an angle x (measured in radians)

tan(x) Tangent of an angle x (measured in radians)

asin(x) Sin-1 (x) where x (measured in radians)

acos(x) Cos-1 (x) where x (measured in radians)

exp(x) Exponential function of x (ex)

log(x) logarithm of x

log 10(x) Logarithm of number x to the base 10

sqrt(x) Square root of x

pow(x, y) x raised to the power y

abs(x) Absolute value of integer number x

fabs(x) Absolute value of real number x

 All of the trigonometric functions take double arguments and have double
return types.
 The trigonometric functions work in radiansrather than degrees.
 Radians =

171
Introduction to C++

7.8.2 Character Functions


All the character functions require ctype.h header file. The following table lists the
function.

Function Meaning

isalpha(c) It returns True if C is an uppercase letter and False if c is lowercase.

isdigit(c) It returns True if c is a digit (0 through 9) otherwise False.

isalnum(c) It returns True if c is a digit from 0 through 9 or an alphabetic character (either upper
case or lowercase) otherwise False.

islower(c) It returns True if C is a lowercase letter otherwise False.

isupper(c) It returns True if C is an uppercase letter otherwise False.

toupper(c) It converts c to uppercase letter.

tolower(c) It converts c to lowercase letter.

7.8.3 String Functions


The string functions are present in the string.h header file. Some string functions are given
below:

strlen(s) It gives the no. of characters including spaces present in a string S.

strcat(s1, s2) It concatenates the string s2 onto the end of the string s1. The string s1 must
have enough locations to hold s2.

strcpys(s1, s2) It copies character string s2 to string s1. The s1 must have enough storage
locations to hold s2.

strcmp((s1, s2)==0)
strcmp((s1, s2)>0) It compares s1 and s2 and finds out whether s1 equal to s2, s1 greater than
strcmp((s1, s2) <0) s2 or s1 less than s2.

strcmpi((s1, s2)==0) It compares s1 and s2 ignoring case and finds out whether s1 equal to s2,
strcmpi((s1, s2)>0) s1 greater than s2 or s1 less than s2.
strcmpi((s1, s2) <0)

strrev(s) It converts a string s into its reverse

strupr(s) It converts a string s into upper case

strlwr(s) It converts a string s into lower case

172
Introduction to C++

7.8.4 Console I/O functions


The following are the list of functions is in stdio.h
eÁw

getchar() It returns a single character from a standard input device (keyboard). It takes no
parameter and the returned value is the input character.
putchar() It takes one argument, which is the character to be sent to output device. It also returns
this character as a result.
gets() It gets a string terminated by a newline character from the standard input stream stdin.
puts() It takes a string which is to be sent to output device.

7.8.5 General purpose standard library functions


The following are the list of functions is in stdlib.h

randomize() It initializes / seeds the random number generator with a random number
random(n) It generates a random number between o to n-1
atoi(s) It converts string s into a numerical representation.
itoa(n) It converts a number to a string

7.8.6 Some More Functions


getch() and getche() functions
The general form of the getch() and getche () is
ch = getche();
ch1 = getch();
ch and ch1 are the variables of type character. They take no argument and require the conio.h
header file. On execution, the cursor blinks, the user must type a character and press enter key.
The value of the character returned from getche() is assigned to ch. The getche() function echoes
the character to the screen. Another function, getch(), is similar to getche() but does not echo character to
the screen.

173
Introduction to C++

Review questions
One mark questions:
1. Who developed C++?
2. C++ is a subset of C. True or false?
3. Mention any two characteristics of C++.
4. Mention the characteristics of C++.
5. Define token.
6. Mention any two tokens of C++.
7. What is an identifier?
8. Keyword can be used to name an identifier. True/false
9. Mention any two keywords in C++.
10. What is a keyword?
11. What is a constant?
12. What is an integer constant?
13. What is an octal constant?
14. What is a hexadecimal constant?
15. Give an example for integer constant.
16. Give an example for octal constant.
17. Give an example for hexadecimal constant.
18. Give an example for float constant.
19. Give an example for character constant.
20. Give an example for string constant.
21. What are escape sequence?
22. Mention any two escape sequences.
23. What are punctuators?
24. Mention any two punctuators.
25. What is an operator?
26. What are unary operators?
27. Mention any two unary operators.
28. Give the output for the expression y=++x-x++ if x=10.
29. What are binary operators?
30. Mention any two binary operators.
31. Mention the operators supported by arithmetic operators.
32. Mention the operators supported by relational operators.
33. Mention the operators supported by logical operators.
34. Mention the operators supported by bitwise operators.
35. Give an example for assignment operators.
36. Give an example for sizeof operator.

174
Introduction to C++

37. What are ternary operators?


38. What
eÁw is an expression?
39. What is operator precedence?
40. Convert the expression l= 2 into equivalent C++ expression.
41. Convert the expression a + b + b = c2 into equivalent C++ expression.
2 2 2

42. Convert the expression into equivalent C++ expression.


43. What is type casting?
44. Mention the types of type casting.
45. Mention any two math.h functions.
46. Mention any two ctype.h functions.
47. Mention any two string.h functions.
48. Mention any two functions of stdio.h.
49. Mention any two functions of stdlib.h.
50. Differentiate between getch() and getche().

Two marks questions:


1. Mention any two characteristics of C++.
2. Mention any four tokens of C++.
3. Mention any two rules for naming an identifier.
4. Mention the types of constants of C++.
5. Explain integer constant with suitable example.
6. Explain octal constant with suitable example.
7. Explain hexadecimal constant with suitable example.
8. Explain float constant with suitable example.
9. Explain character constant with suitable example.
10. What are escape sequences? Mention any two escape sequences.
11. Explain string constant with suitable example.
12. Explain unary operators with suitable example.
13. Explain arithmetic operators with suitable example.
14. Explain logical operators with suitable example.
15. Explain bitwise operators with suitable example.
16. Explain the type conversions briefly.
17. Give an example of a simple C++ program.
18. Mention any two math.h functions.
19. Mention any four ctype.h functions.
20. Mention any four string.h functions.
21. Mention any four functions of stdio.h.
22. Mention any four functions of stdlib.h.

175
Introduction to C++

Three marks questions:


1. Mention any four characteristics of C++.
2. Explain about character set and tokens I C++.
3. Summarize the rules for naming an identifier.
4. Explain about Integer constants with suitable examples.
5. What are escape sequences? Mention any four escape sequences.
6. Explain any four unary operators.
7. What is an expression? Explain the precedence of operators with suitable example.
8. Explain implicit and explicit type conversions with suitable examples.
9. Explain the detailed structure of a C++ program.
10. Explain mathematical and character library functions.
11. Explain string and stdlib.h functions.

Five marjks questions


1. Who developed C++? Explain the characteristics in detail.
2. Explain the various tokens of C++.
3. Explain the constants in C++ with suitable examples.
4. What are escape sequences. Explain the various escape sequences.
5. What are binary operators? Explain the various binary operators with suitable examples.
6. Explain unary and ternary operators with suitable examples.
7. Explain the precedence of operators with suitable examples.
8. Explain the detailed structure of C++ program with suitable programming example.
9. Explain the various library functions of C++.

176
eÁw

CHAPTER 8
Data types

OBJECTIVES
To Understand the types of data,
Representation
Features
Usage

177
178
Data types

8.1 Introduction
Though
eÁw we have already come across about char, int, float under constant section of the previous
chapter it becomes extremely important to understand in depth about these elementary building blocks of
C++ programs.
To understand any programming language we need to first understand the elementary concepts
which form the building block of that program. The building blocks include the variables, data types, etc.
Therefore it becomes absolutely necessary to concentrate and understand about data types, variables,
expressions. C++ provides a set of data types to handle the data that is used by the program. It is
categorized as fundamental and derived data types. The derived data type is further classified as built – in
and user –defined types. These types are applied on the identifiers called as variables and these variables
actually represent the real world data.

8.2 Variables
C++ encourages you to use meaningful names for variables according to what they represent in the
real world. Variables are generally declared in the declaration section of the program and their values can
be manipulated during program execution. In C++, the variable names actually represent the storage
location, the type of the value that it can hold and also the maximum range of value that can be held by that
variable.

A variable is an object or element and it is allowed change during the execution of the program. Variable
represent the name of the memory locations.

8.2.1 Declaration of a variable


The syntax for declaring a variable is
datatype variable_name;
The variable_ name is an identifier and the rules for naming an identifier is already discussed in
the previous chapter 7. These variables are used to denote constants, arrays, functions, structures, classes
and files. The variables are named storage locations whose values can be manipulated during program
run.
Some valid variables are
reg_no marks student1 doj
Some invalid variables are
Double - keyword cannot be a name of the variable
Total marks - empty spaces are not allowed between variable names
2 sudent - variable name should begin with an alphabet
?result - variable should begin with alphabet or underscore only

179
Data types

8.2.2 Initializing a variable


The syntax to initialize a variable is
datatype variable_name = value;

Example 8.1Let b be a variable declared of the type int. Then,


int b =100;
 There are two values associated with a variable pknown as lvalue and rvalue. It means, for
example, let p be a variable declared of the type int. Then,
int p = 100; 100

name of the variable is p 2000

value assigned to variable is 100


(rvalue)
memory address location 2000
(1 value)

 lvalue is the location value. It holds the memory address location at which the data value is
stored. i.e., lvalve of p = 2000 in the above example.
 rvalueis the data value. It holds the value assigned to the variable by the programmer. i.e., rvalve
of p=100 in the above example.
 C++ compiler allows us to declare a variable at run time. This is dynamic initialization. They can
be initialized anywhere in the program before they are used.

Example 8.2:
int a, b;
.
.
int temp = a;
a = b; In the body of the program note that variable temp is
initialized inside it.
b = a;
.
.
.

 The access modifier ‘const’ prefixed along with the data type for a variable does not allow the

180
Data types

value to be changed at all throughout the program.


eÁw
Example 8.3:
int a = 100;
In the above example, a is a variable with value equal to 100. But, this value can be changed at any
time. It is also possible to retain this value unchanged by using the keyword const. when we use this
keyword before the variable’s declaration then it modifies its access type and the value remains unchanged
for the variable. It is as shown below.
const int a = 100;
Thus the keyword const becomes an access modifier for the variables.

 A value can be assigned to lvalue only in an expression.


 Value can be assigned to a variable using the assignment operator ‘=’.
 The expression to the left of an assignment operator should always be an lvalue (memory
location) because that memory location should be available to store the rvalue.
 Constant identifiers can appear to the right of the assignment operator only since are not
lvalues.

8.3 Data types

Figure 8.1 Classifications of Data Types

181
Data types

8.3.1 Data types classification


Data type means to identify the type of data and associated operations of handling it. C++ provides
various facilities to handle different types of data. The classification of data types is as shown in fig8.1. We
find that it is of two types:
i. Simple or fundamental data types
ii. Complex or Derived data types
The simple data types include int, float, char double and void. These types are used to
represent integer, floating point, long floating point (with higher precision) and character types respectively.
Derived data types are constructed using the simple data types and they are further
classified as linear data structure and non-linear data structures. In linear data structure the data
elements are arranged in sequential manner. C++ includes arrays, structures, unions, pointers, linked
list in linear structure type. In non-linear structure the data elements are arranged in non-sequential
manner which includes graphs and trees. The other category of derived data types includes user defined
data type.
Data type can be defined as the set of values which can be stored in a variable along with the
operations that can be performed on those values.

Data type can be defined as the set of values which can be stored in a variable along with the operations
that can be performed on those values.

Now let us study about the different data types in detail. The simple or fundamental data types are
the primary data types which are not composed of any other data types.
The simple data types/fundamental data types include int, char, float and double.
i. int: Integers are whole numbers without any fractional parts. These includes numbers such as
10, -20, 0 etc. The integers can be positive or negative values and the range of numbers we can
store are from -32768 to 32767. They occupy two bytes of memory space. The possible
operations include addition, subtraction, multiplication, division, remainder etc.
ii. char: It is character data type to store any character from the basic character set. It includes
characters such as ‘a’, ‘Y’, ‘5’, ‘&’ etc. Note that the character should be enclosed within single
quotes. When a variable of the type char is declared, the compiler converts the character to its
equivalent ASCII code. The ASCII code stores number codes for 256 known characters
(digits, alphabets, special characters, etc.). They occupy 1-byte of memory space. The possible
operations are input and output.
iii. float: This represent the numbers with fractional part. i.e., real numbers. It includes numbers
such as 10.5, 45.0, -5.75 etc. It can also be both positive and negative. The range of numbers
we can store from -3.4e-38 to 3.4e38. Here, e represents scientific(exponential) notation. They
occupy 4-bytes of memory space. The possible operations are addition, subtraction,
multiplication and division.

182
Data types

iv. double: This is same as float with double precision (significant numbers after decimal point).
They occupy 8-bytes of memory space (~15 digits). The range of numbers we can store
eÁw
are from - 1.7e-308 to 1.7e308.The possible operations are addition, subtraction,
multiplication and division. The float and double data types can be represented in
scientific(exponential) notation.
v. void: This datatype represents an empty set of values. It is used as return type
for functions and they do not return a value. Void will be discussed in detail in
chapter 13.

The below table 8.1 gives the details of the data types with suitable examples.

Type Size in bytes Range Examples


int 2 -32768 to 32767 8, 100, -39
char 1 -128 to 127 ‘d’, ‘6’, ‘#’
float 4 3.4 x 10-38 to 3.4 x 1038 - 1 45.345, 0.123, -23.45
double 8 1.7 x 10-308 to 1.7 x 10308-1 3.1415677888888888,12e-2000

Table 8.1 Data types in detail

8.4 Modifiers
C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is
used to alter the meaning of the base type so that it more precisely fits the needs of various situations.
The data type modifiers are listed here:
 signed
 unsigned
 long
 short

The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition,
signed and unsigned can be applied to char and long can be applied to double. The modifiers signed
and unsigned can also be used as prefix to long or short modifiers. For example, unsigned
long int.
C++ also allows a shorthand notation for declaring unsigned, short, or long integers. You can
simply use the word unsigned, short, or long, without the int. The int is implied.

183
Data types

Example 8.4:
The following two statements both declare unsigned integer variables.
unsigned a;
unsigned int b;

Type Size in bytes Range


char 1 -128 to 127 or 0 to 255
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65,535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65,535
signed short int 2 -32768 to 32767
long int 4 -2,147,483,647 to 2,147,483,647
signed long int 4 -2,147,483,647 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
float 4 +/- 3.4e +/- 38 (~7 digits)
double 8 +/- 1.7e +/- 308 (~15 digits)
long double 10 +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character

Table 8.2 C++ Modifiers

The size of variables might be different from those shown in the above table 8.2, depending on the
compiler and the computer you are using.

8.5 Derived data types


These data types are constructed using simple or fundamental data types. They include arrays,
functions, pointers and references. The details of these will be dealt in detail in later chapters.

8.6 User defined data types


These data types are also constructed using simple or fundamental data types. Some user defined
data types include structure, union, class and enumerated. We shall study about structure, union, class in
later chapters and concentrate on enumerated data type now.

8.6.1 Enumerated data type


An enumeration is a user-defined type consisting of a set of named constants called
enumerators. enum is a keyword that assigns values 0, 1, 2,… automatically. This helps in providing
an alternative means for creating symbolic constants.
184
Data types

The syntax for enum is as follows:


enum[tag]
eÁw {enum-list}; // for definition of enumerated type
enumtagdeclarator; // for declaration of variable of type tag
Example 8.5: enum choice{very_bad, bad, satisfactory, good, very_good, , excellent };
//definition of enumerated type
choice mychoice; // declaration of variable of type choice

The above example 8.5 depicts how another variable of the type enum can be created.

Example 8.6 enum MyEnumType { ALPHA, BETA, GAMMA };


Here, ALPHA takes the value of 0,
BETA takes the value of 1,
GAMMA takes the value of 2.
We can also provide explicit values for enum constants, as in example 8.7.

Example 8.7 enum footSize{ SMALL = 10, MEDIUM = 100, LARGE = 1000 };
SMALL takes the value of 10,
MEDIUM takes the value of 100,
LARGE takes the value of 1000.

C++ enum type conversion rules:


 These rules apply to C++ only.
 There is an implicit conversion from any enum type to int. Suppose this type
exists:
enum MyEnumType { ALPHA, BETA, GAMMA };
Then the following lines are legal
int i = BETA; // give i a value of 1
int j = 3 + GAMMA; // give j a value of 5
 On the other hand, C++ does not support an implicit conversion from int to an enum type. This
type conversion is always illegal
MyEnumType x = 2; // should not be allowed by compiler
MyEnumType y = 123; // should not be allowed by compiler
Note that it does not matter whether the int matches one of the constants of the enum
type.

185
Data types

Review questions:
One mark questions:
1. Define variables.
2. Give the syntax of declaring a variable.
3. Give the syntax of initializing a variable.
4. Differentiate between lvalue and rvalue.
5. Mention the data types of C++.
6. Mention the types of modifiers.
7. What are derived data types.
8. What are user-defined data types.
9. What is an enumerated data type.

Two marks questions:


1. What is a variable and give its declaration.
2. Explain lvalue and rvalue with an example.
3. What is a data type and mention the different data types.
4. Explain the various data types.
5. What are modifiers and mention the different modifiers.
6. What is an enumerated data type. Give an example.

Three marks questions.


1. Explain the variables in detail.
2. Explain the data types and its classification.
3. Explain the modifiers in detail.
4. Explain enumerated data types with suitable examples.
5. Give the C++ enum type conversion rules.

Five marks questions.


1. Explain the variables in detail with suitable examples.
2. What is a data type? Explain the classification of data types in detail.
3. Explain the user-defined data type in detail.

186
eÁw

CHAPTER 9
Input and Output operators

OBJECTIVES
To Know the operators used for performing basic input operations
Output operations

187
188
Input and Output operators

9.1 Introduction
After
eÁwunderstanding about the structure of C++ programming and about its data types, it becomes
necessary to understand more about formatting the input and outputs of a program. The input output
operations are done using library functions cin and cout objects of the class iostream. Using the standard
input and output library, we will be able to interact with the user by printing messages on the screen and
getting the user’s input from the keyboard.
C++ makes use of convenient abstraction called streams to perform input and output operations in
sequential media such as the monitor or the keyboard. A stream is an object where a program can either
insert/extract characters to/from it. We do not really need to care about many specifications about the
physical media associated with the stream - we only need to know that it will accept or provide characters
sequentially. The standard C++ library includes the header file iostream, where the standard input and
output stream objects are declared.

9.2 Input Operator “>>”

cin >> Variable


KEYBOARD

Figure 9.1 Input Using cin

The standard input device is usually the keyboard as shown in figure 9.1. Input in C++ is done by
using stream extraction (>>) on the cin stream. The operator must be followed by the variable that will
store the data that is going to be extracted from the stream.

Example 9.1:
int age;
cin>>age;
The first statement in example 9.1 declares a variable of type int called age, and the second one waits
for an input from cin (the keyboard) in order to store it in this integer variable. cin stands for “console
input”. It can only process the input from the keyboard once the RETURN key has been pressed.
Therefore, even if we request a single character, the extraction from cin will not process the input until the
user presses RETURN after the character has been introduced.
We must always consider the type of the variable that we are using as a container with cin extractions.
If we request an integer we will get an integer, if we request a character we will get a character and if we
request a string of characters we will get a string of characters.

189
Input and Output operators

Program 9.1 To find the sum of any two integers


#include <iostream.h>
#include <iomanip.h>
void main()
{
int a, b, sum;
clrscr();
cout<<“Enter two numbers: “;
cin>>a>>b;
sum = a+b;
cout<<“The sum is “<<sum<<endl;
getch();
}
Sample Run: Enter two numbers: 5 -10
The sum is -5

9.3 Output Operator “<<“

MONITOR cout << Variable

Figure 9.2 Output using cout

The standard output device is the screen (monitor) as shown in figure9.2, and outputting in
C++ is done by using the object followed by the “stream insertion” which is written as <<
(two “less than” signs). cout stands for console output.

Example 9.2:

cout<< “ Let us learn C++”; // prints Let us learn C++ on the screen.

The << operator inserts the data that follows it into the stream preceding it. In the examples
above it inserts the constant string “Let us learn C++”. Notice that the sentence in the instruction is
enclosed between double quotes (“), because it is a constant string of characters. Whenever we
want to use constant strings of characters we must enclose them between double quotes (“) so that
they can be clearly distinguished from variable names.

190
Input and Output operators

Example 9.3:
eÁw cout<< “ Compilation”; // prints Compilation
cout<< Compilation; // prints the content of the variable Compilation

In order to perform a line break on the output we must explicitly insert a new-line character into
cout. In C++ a new-line character can be specified as’ \n’ (backslash, n): the newline character is an
escape sequence character and helps in formatting the output statement. We have already discussed
about escape sequences in the previous chapter.

Program 9.2 To demonstrate output


#include <iostream.h>
void main ()
{
<<“C++ makes use of OBJECT ORIENTED PROGRAMMING “<<“\n”;
cout<<“C++ is a superset of C “<<“\n”;
cout<<“Writing Algorithms is great fun “ ;
}
Sample Run: C++ makes use of OBJECT ORIENTED PROGRAMMING
C++ is a superset of C
Writing Algorithms is great fun

Cascading of I/O operators:


C++ supports the use of stream extraction (>>) and stream insertion (<<) operators many times in a
single input (cin) and output (cout) statements. If a program requires more than one input variable then it
is possible to input these variables in a single cin statement using multiple stream extraction operators.
Similarly, when we want to output more than one result then this can be done using a single cout statement
with multiple stream insertion operators. This is called as cascading of input output operators.

Example 9.4:
cout<<“ enter the value for x”;
cin>> x;
cout<<“ enter the value for y”;
cin>>y;
Instead of using cin statement twice, we can use a single cin statement and input the values for the
two variables x and y using multiple stream extraction operator as shown below.
cout<<“ enter the value for x and y”;
cin>>x>>y;
Similarly, we can even output multiple results in a single cout statement using cascading of stream
insertion operator as shown below.
cout<<“ the sum of” <<x<<“ and “<<y<<“=”<<x+y;
191
Input and Output operators

• The multiple uses of input/output operators (<< and >>) in a single


statement is called cascading of input/ output operators.

• The input operator is also known as "stream extraction” operator >>" means
to "get from" is used to read value from the standard input device.

• The output operator is also known as "stream insertion operator << " means
to "put to" is used to send the value to the standard output device.

• cin/cout are keywords which are predefined objects in C++ that corresponds
to standard input output stream.

• Manipulators are operators used along with the insertion operator to


manipulate or modify the output. Some of them are endl and setw.

• endl is same as the escape sequence \n. It causes a line feed to be inserted
into the stream.

• setwcauses the number that follows in the stream to be printed within


ancharacter wide field and the value is right justified within the field.

• iomanip.his aheader file that holds the objects endl and setw.

Program 9.3 Convert the temperature in Fahrenheit into Celsius


#include <iostream.h>
#include<iomanip.h>
void main ()
{
float Fahrenheit, Celsius;
cout<< “Enter the value of Fahrenheit: “;
cin>> Fahrenheit;
Celsius = ((5.0 / 9.0) * Fahrenheit- 32.0);
cout<<Fahrenheit<<“F = “<<Celsius<<“C”<<endl;
}
Sample Run: Enter the value of Fahrenheit: 105
105F = 26.3333C

192
Input and Output operators

Program
Program 9.4 9.5 To interchange
To interchange the values
the values of two variables
of two variables without
using third using third variable
variable
#include<iostream.h>
eÁw #include<iostream.h>
#include<conio.h>
#include<conio.h>
#include<iomanip.h> Practical
Practical
void main()
#include<iomanip.h> program
{ program
intvoida,main()
b, temp;
clrscr();
{
cout<<“ Enter two numbers: “;
cin>>a>>b; int a, b, temp;
cout<<“Before interchanging: a = “<<a<<“ and b= “<<b<<endl;
temp = a;clrscr();
a = b;
cout<<” Enter two numbers: “;
b = temp;
cout<<“After interchanging: a = “<<a<<“ and b= “<<b<<endl;
cin>>a>>b;
getch();
Sample
} Run: cout<<”Before interchanging:
Enter two numbers: 60 100 a = “<<a<<” and b= “<<b<<endl;
Sample Run: Before
aEnter
= a +twob; numbers: 50 100
interchanging: a = 60 and b= 100
Before interchanging: a = 50 and b= 100
bAfter
= a -interchanging:
After b;
interchanging: a =a100 andand
= 100 b= b=
60 50

Program 9.5 To interchange the values of two variables without using third variable
Program 9.5 To interchange the values of two variables without using third variable
#include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<conio.h>
#include<iomanip.h> Practical
Practical
void main()
#include<iomanip.h> program
{ program
void main()
int a, b;
clrscr();
{
cout<<“ Enter two numbers: “;
cin>>a>>b;
int a, b, temp;
cout<<“Before interchanging: a = “<<a<<“ and b= “<<b<<endl;
a = a + clrscr();
b;
b = a - b;
cout<<” Enter two numbers: “;
a = a – b;
cout<<“After interchanging: a = “<<a<<“ and b= “<<b<<endl;
cin>>a>>b;
getch();
Sample
} Run: cout<<”Before interchanging:
Enter two numbers: 60 100 a = “<<a<<” and b= “<<b<<endl;

Sample Run:Before
a =Enter two numbers: 60 a100
a + interchanging:
b; = 60 and b= 100
Before interchanging: a = 60 and b= 100
bAfter
=After
a -interchanging:
b;interchanging: aa==100
100and
and b=
b= 60
60
193
Input and Output operators

Program
Program 9.6 9.5 Tothe
To find interchange the values ofoftwo
area and circumference variables without using third variable
a circle
#include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<conio.h>
#include<iomanip.h> Practical
Practical
void main()
#include<iomanip.h> program
{ program
float rad,main()
void area, circum;
clrscr();
{
cout<<“ Enter radius: “;
cin>>rad; int a, b, temp;
area = 3.142 * rad * rad;
circum = 2clrscr();
* 3.142 * rad;
cout<<“Area = “<<area<<endl;
cout<<” Enter two numbers: “;
cout<<“Circumference = “<<circum<<endl;
getch(); cin>>a>>b;
}
Sample Run: Enter cout<<”Before interchanging:
two numbers: 60 100 a = “<<a<<” and b= “<<b<<endl;
Sample Run: Enter radius: 5.5
Area
a = a=+95.0455
Before b;
interchanging: a = 60 and b= 100
Circumference = 34.562
b = a -interchanging:
After b; a = 100 and b= 60

Program
Program 9.7 9.5 To the
To find interchange
area of thethe values
triangle of two
given threevariables
sides without using third variable
#include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<conio.h>
#include<iomanip.h>
Practical
Practical
#include<math.h>
#include<iomanip.h> program
void main() program
{ void main()
float s1, s2, s3, s, area;
{
clrscr();
cout<<“ Enter the length of three sides: “;
int a, b, temp;
cin>>s1>>s2>>s3;
s = (s1+s2+s3)/2;
clrscr();
area = sqrt(s*(s-s1)*(s-s2)*(s-s3));
cout<<”
cout<<“Area Enter two numbers: “;
= “<<area<<endl;
getch(); cin>>a>>b;
}
Sample Run: cout<<”Before
Sample Run: Enter twolength
Enter the interchanging:
numbers: sides: 5 3 a6 = “<<a<<” and b= “<<b<<endl;
60 100
of three
aArea
=a+
Before
= b;
7.48331
interchanging: a = 60 and b= 100

b = a -interchanging:
After b; a = 100 and b= 60

194
Input and Output operators

Program 9.5 To interchange the values of two variables without using third variable
Program 9.8 To convert days into years, months and days
eÁw #include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<conio.h>
#include<iomanip.h> Practical
Practical
void main()
#include<iomanip.h> program
{ program
voidintmain()nodays, days, years, months;
clrscr();
{
cout<<“ Enter the total days: “;
cin>>days;
int a, b, temp;
nodays = days;
yearsclrscr();
= days/365;
days = days%365;
cout<<” Enter two numbers: “;
months = days/30;
dayscin>>a>>b;
= days%30;
cout<<nodays<<“days = “<<days<<“days- “<<months<<“months-”
Sample Run: cout<<”Before
Enter two numbers: interchanging:
60 100
<<years<<“years”<<endl;a = “<<a<<” and b= “<<b<<endl;
getch();
a = a + interchanging:
Before b; a = 60 and b= 100
}
Sample Run: bAfter= a -interchanging:
Enter b; total days: 1005
the a = 100 and b= 60
1005days = 5days- 9months-2years

195
Input and Output operators

Program
Program 9.9 9.5 To interchange
To convert thehours,
seconds into values of twoand
minutes variables
secondswithout using third variable
include<iostream.h>
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
#include<conio.h>
Practical
Practical
void main()
{ #include<iomanip.h> program
program
int main()
void totalsecs, minutes, hours, seconds;
clrscr();
{ cout<<“ Enter the total seconds: “;
cin>>seconds;
int a, b, temp;
totalsecs = seconds;
hoursclrscr();
= seconds/3600;
seconds = seconds%3600;
cout<<” Enter two numbers: “;
minutes = seconds/60;
cin>>a>>b;
seconds = seconds%60;
Sample Run: cout<<”Before
Enter interchanging:
two numbers: 60=100 a = “<<a<<” and b= “<<b<<endl;
cout<<totalsecs<<“seconds “<<seconds<<“seconds-
“<<minutes<<“minutes-”<<hours<<“hours”<<endl;
a = a + interchanging:
Before b; a = 60 and b= 100
getch();
} b = a -interchanging:
After b; a = 100 and b= 60
Sample Run: Enter the total seconds: 10000
10000seconds = 40seconds- 46minutes-2hours

196
Input and Output operators

Review questions:
eÁw
One mark questions:
1. Give the other name for cin( ).
2. Give the other name for cout( ).
3. What is cascading?
4. What are manipulators?
5. Give the header file that holds setw( ) and endl.
6. What is the purpose of setw( ).

Two marks questions:


1. Explain the input operator in c++.
2. Explain the output operator in C++.
3. Explain the cascading of input output operators.

Long answer Questions:


1. Explain the input output operators in C++.
2. Write a C++ program to find the sum of two numbers.
3. Write a C++ program to convert Fahrenheit to Celsius.
4. Write a C++ program to demonstrate the cout .
5. Explain the cascading of input output operators with suitable example.

197
Control Statements

198
Control Statements

eÁw

CHAPTER 10
Control Statements

OBJECTIVES
To Understand the various control statements
Usage
Implementation

199
200
Control Statements

10.1 Introduction
A program
eÁw is usually not limited to a sequence of instructions. During its process it may bifurcate,
repeat or take decisions. For that cause, C++ provides us control structures, statements that can alter
the flow of a sequence of instructions. In C++program, statements are executed sequentially in the order
in which they are written. Such programs are called as sequential structures.
With the introduction of control structures we are going to introduce a new concept calledcompound
statement or block. Block is a group of statements which are separated by semicolons ( ; ) like all C++
Statements, but grouped together in a block enclosed in braces { and };
Most of the control structures that we will see in this chapter require syntax. A statement can be a
simple statement or compound statement. The order of execution of statements may be changed depending
on certain conditions to make a proper decision.
The order in which statements are executed in a program is called flow of control. C++ provides
control structures that serve to specify what has to be done by the program, when and under what
circumstances.

 Control statements are statements that alter the sequence of flow of instructions.
 Any single input statement, assignment and output statement is simple statement.
 A group of statements that are separated by semicolon and enclosed within curled braces {and}
is called a block or compound statement.

10.2 Types of control statements


C++ supports two basic control statements.
 Selection statements
 Iteration statements

10.3 Selection statements


This statement allows us to select a statement or set of statements for execution based on some
condition.
The different selection statements are:
i. if statement
ii. if-else statement
iii. Nested statement
iv. switch statement

201
Control Statements

10.3.1 if statement
This is the simplest form of if statement. This statement is also called as one-way branching.
This statement is used to decide whether a statement or a set of statements should be executed or not.
The decision is based on a condition which can be evaluated to TRUE or FALSE.
The general form ofif statement is
if (condition) if (condition)
OR {
statement1
; statement-1;
statement-2;
…….
statement-n;
}

Is F Is F
condition? condition?

T T

Statement-1 statement-1
statement-2
-------
Next statement statement-n

next-statement

In the above syntax


 The condition gives 0 (FALSE) or 1 (TRUE).
 If the condition is true, it has value1 and statement-1 is executed.
 If the condition is false, it has value 0 and statement-1 is not executed.
 The expression (or condition) must be put inside the parentheses.
 statement-1 will be executed only when the condition is true (some time it may be block of
statements).
 If the condition is false then control skips statement-1 and executes next the statement in the
program. i.e., statement-2

Example 10.1 if ( n = = 100)


cout<< “ n is 100 “;

202
Control Statements

Program 10.1 To find largest of two numbers using if statement


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int a, b, large;
clrscr();
cout<< “ Enter two numbers: “;
cin>> a>>b;
large = a;
if ( b > large )
large = b;
cout<<”Largest number is ” << large;
getch( );
}

Sample run: Enter two numbers


20 10
Largest number is 20

203
Control Statements

Program 10.2 To findthe largest, smallest and second largest of three numbers
usingsimple if statement.
#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) Program
{
int a, b, c, largest, seclargest, smallest ;
clrscr( );
cout<< " Enter three numbers: ";
cin>> a>>b>>c;
largest = a;
smallest = a;
if ( b > largest)
largest = b;
if (c > largest)
largest = c;
if ( b < smallest)
smallest = b;
if (c < smallest)
smallest = c;
seclargest = (a+b+c) - (largest + smallest);
cout<<"Largest number is " << largest<<endl;
cout<<"Second largest number is " <<seclargest<<endl;
cout<<"Smallest number is " << smallest<<endl;
getch( );
}

Sample run: Enter three numbers: 10 50 30


Largest number is 50
Second largest number is 30
Smallest number is 10

204
Control Statements

Program10.3Input the total amount in a bill, if the amount is greater than 1000, the
eÁw discount of 8% is given. Otherwise, no discount is given. Output the total
amount, the discount and the final amount.

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ Program
float amount, discount, netdiscount, netamount;
clrscr( );
cout<< "Enter amount: ";
cin>>amount;
discount = 0.0;
if (amount >= 1000)
discount = 8/100;
netdiscount = amount * discount;
netamount = amount – netdiscount;
cout<<”Net discount = “<<netdiscount<<endl;
cout<<”Net amount = “<<netamount<<endl;
getch();
}

Sample run: Enter amount: 2000


Net discount = 160
Net amount = 1840

205
Control Statements

10.3.2 The if–else statement


This statement is also called as two-way branching. It is used when there are alternative statements
need to be executed based on the condition. It executes some set of statements when the given condition
is TRUE and if the condition is FALSE then other set of statements to be executed.
The general form of if- else statement is.

if (condition )
statement1;
else
statement2;

 If the given condition is TRUE then statement1 will be executed. Otherwise statement2 will be
executed.
 Only the code associated with if or the code associated with else will be executed, never both.
 Both statement1andstatement2may be single or compound statements.
 It is important to note that after executing either statement1 or statement2, the compiler control
goes to the next statement in the program.

206
Control Statements

Program 10.4 To determine whether the shape is square or rectangle


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int breadth, height;
clrscr();
cout<< "Enter value of breadth and height : ";
cin>> breadth>>height;
if ( breadth == height )
cout<< "It is a square ….";
else
cout<< "It is a rectangle ….";
getch();
}

Sample run: Enter value of breadth and height : 5 5


It is a square ….
Sample run: Enter value of breadth and height : 5 10
It is a rectangle ….

207
Control Statements

Program 10.5 To find greatest of two numbers


#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int a, b;
clrscr();
cout<< "Enter two numbers: ";
cin>> a>>b;
if ( a>b )
cout<<a<<" is the greatest … .";
else
cout<<b<<" is the greatest ….";
getch();
}

Sample run: Enter two numbers: -10 10


10 is the greatest

Program 10.6 To determine whether the year is a leap year

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ Program
int year;
clrscr( );
cout<< " Enter the year: ";
cin>> year;
if ( year%4 == 0 && year%100!= 0 || year%400 == 0 )
cout<<"It is a leap year"<<endl;
else
cout<<"It is not leap year"<<endl;
getch( );
}

Sample run: Enter the year: 2012


It is a leap year
Sample run: Enter the year: 1900
It is not leap year

208
Control Statements

Leap year program


A leap
eÁw year is a year in which one extra day (February 29) is added to the regular calendar. Most of
us know that the leap years are the years that are divisible by 4. For example, 1992 and 1996 are leap
years. There is an exception to this rule: centennial years are not leap years. For example, 1800 and 1900
are not leap years. But, there is exception to the exception: centennial years that are divisible by 400 are
leap years. Thus, year 2000 is a leap year.

Program 10.7 To determine whether the input character is lower-case or upper-case

#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) Program
{
char ch;
clrscr( );
cout<< " Enter the character: ";
cin>>ch;
if ( ch>=’A’ &&ch<=’Z’)
cout<<"It is an upper-case character"<<endl;
else
cout<<"It is a lower-case character"<<endl;
getch( );
}

Sample run: Enter the character: G


It is an upper-case character
Sample run: Enter the character: j
It is a lower-case character

10.3.3 Nested-if statement


If the statement of an if statement is another if statement then such an if statement is called as nested
if statement. Nested-if statement contains an if statement within another if statement.
There are two forms of nested if statements

Format I: if-else-if statement


This structure is also called as else-if ladder. This structure will be used to verify a range of values.
This statement allows a choice to be made between different possible alternatives. A choice must be
made between more than two possibilities.

209
Control Statements

The general form of if- else-if statement is

if (condition1 )
statement1;
else
if (condition2)
statement 2;
else
-------------
else
if(condition-n)
statementn;
else
defaultstatement;

T F
Is
condition1?
1

statement1 T F
Is
condition1?
1

statement2

T F
Is
condition-n?

statementn defaultstatement

First condition1 is tested. If condition1 is TRUE then statement1 is executed. Otherwise, condition2
is tested. If condition2 is TRUE then statement2 is executed. Otherwise, condition3 is tested and so on.
Finally, condition-n is tested. If it is TRUE, statement-n is executed. If none of the conditions is TRUE
then default statement is executed.

210
Control Statements

Program to declare the result based on the following rules:


eÁw
Marks Grade
85 – 100 Distinction
60 – 84 First class
50 – 63 Second class
35 – 49 Pass class
0 – 34 Fail

Program 10.8 To find grade of the student

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ program
int marks;
clrscr();
cout<< "Enter marks: ";
cin>>marks;
if ( marks >= 85 && marks <= 100 )
cout<<”Distinction”<<endl;
else
if ( marks >= 60 )
cout<<”First class”<<endl;
else
if ( marks >= 50)
cout<<”Second class”<<endl;
else
if ( marks >= 35)
cout<<”Pass class”<<endl;
else
cout<<”Fail”<<endl;
getch();
}

Sample run: Enter marks: 71


First class
Sample run: Enter marks: 32
Fail

211
Control Statements

Format II:
. This structure contains an if-else statement within another if-else statement.
The general form of if- else-if statement is
if (condition1 )
if (condition2)
statement1;
else
statement2;
else
if(condition3)
statement3;
else
statement4;

F T
Is
condition1?

F T F T
Is Is
condition3? condition2?

statement4 statement3 statement2 statement1


2

212
Control Statements

Program 10.9 To find the greatest of three numbers


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int a, b, c;
clrscr();
cout<< "Enter three numbers: ";
cin>>a>>b>>c;
if(a>b)
if (a>c)
cout<<a<<” is the greatest”<<endl;
else
cout<<c<<” is the greatest”<<endl;
else
if (b>c)
cout<<b<<” is the greatest”<<endl;
else
cout<<c<<” is the greatest”<<endl;
getch();
}

Sample run: Enter three numbers: 10 20 30


30 is the greatest
Sample run: Enter three numbers: 10 30 20
30 is the greatest
Sample run: Enter three numbers: 30 10 20
30 is the greatest

10.3.4 switch statement


C++ has a built-in multiple-branch selection statement, switch. This successively tests the value of
an expression against a list of integer or character constants. When a match is found, the statements
associated with that constant are executed.

213
Control Statements

The general form is


switch (Expression)
{
case label-1: statement-1;
break;
case label-2: statement-2;
break;
………
case label-n: statement-n;
break;
default : default-statement;
}

Is
expression

=label-1? =label-2? =label-n? default

statement-1 statement-2 statement-n default-statement

This statement checks the values of the variable or expression given within the parenthesis with a list
of case constants.
 Each case value must be unique within a switch statement.
 After the word case, a space is given then label or constant is to be written followed by
colon (:).
 All cases must be enclosed with in curled braces.
 While executing, depending on the label/constant, the corresponding set of statements are executed.
 If the value of the expression is not matched with label/constant then default statement is executed.
 Every case must consist of break statement to terminate corresponding cases. Otherwise, the
following statements are executed until break is encountered.

214
Control Statements

Program
eÁw 10.10Program todisplay a day number in a week using switch statement

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int dayno;
clrscr();
cout<< “Enter day number of the week: “;
cin>>dayno;
switch(dayno )
{
case 1 : cout<< “SUNDAY ”<<endl;
break;
case 2 : cout<< “MONDAY”<<endl;
break;
case 3 : cout<< “TUESDAY ”<<endl;
break;
case 4 : cout<< “WEDNESDAY”<<endl;
break;
case 5 : cout<< “THURSDAY”<<endl;
break;
case 6 : cout<< “FRIDAY ”<<endl;
break;
case 7 : cout<<“SATURDAY”<<endl;
break;
default : cout<< “ Invalid day number ”<<endl;
break;
}
getch();
}

Sample run: Enter day number of the week: 5


THURSDAY
Sample run: Enter day number of the week: 10
Invalid day number

215
Control Statements

The switch statement is a bit peculiar within the C++ language because it uses labels instead
of blocks. This forces us to put break statements after the group of statements that we want to execute
for a specific condition. Otherwise the remainder statements including those corresponding to
other labels will also be executed until the end of the switch selective block or a break statement is
reached.
For example, if we do not include a break statement after the first group of case one, the program
will not automatically jump to the end of the switch statement and it would continue executing the rest of
statements until it reaches either a break instruction or the end of the switch statement. This makes it
unnecessary to include braces { and} surrounding the statements for each of the cases.

10.4 Iteration statements or loops


Iteration statements are also called as loops. Loop is a statement that allows repeated execution of
a set of instructions certain condition is satisfied. This condition may be predefined or post-defined.
Loops have a purpose to repeat a statement or set of statements a certain number of times or while a
condition is fulfilled. We use three types of looping structures in C++.
 while loop
 do- while loop
 for loop

10.4.1 while loop


This looping structure is also called as pre-tested looping structure. This statement repeats the
execution of a set of statements while the condition is TRUE.
The general form of while loop is

while (test-condition ) while ( test-condition)


statement1; OR {
statement 1;
statement 2;
………
statement n;
}

216
Control Statements

eÁw

This looping structure works as follows:


i. The condition is tested.
ii. If the condition is TRUE, the statement or set of statements inside the loop are executed.
iii. The condition is tested again.
iv. The process is repeated until the condition becomes FALSE.
v. When the condition becomes FALSE, control goes to the next statement of the loop.

217
Control Statements

Program 10.11 To print numbers in descending order

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n;
clrscr();
cout<< "Enter the starting number: ";
cin>> n ;
while ( n > 0 )
{
cout<<setw(4)<<n ;
--n;
}
cout<< " end of loop \n ";
getch();
}

Sample run: Enter the starting number: 10


10 9 8 7 6 5 4 3 2 1 end of loop

When creating a while-loop, one must always consider that it has to end at some point, therefore we
must provide within the block some method to force the condition become FALSE at some point, and
otherwise the loop will continue looping forever. This case is called as infinite loop.

218
Control Statements

Program 10.12 To find sum of digits in a given number


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ program
int n, sum=0, digit ;
clrscr();
cout<< "Enter the number: ";
cin>> n ;
while ( n != 0 )
{
digit = n%10;
sum = sum+digit;
n = n/10;
}
cout<< "Sum of digits = "<<sum<<endl;
getch();
}

Sample run: Enter the number: 7039


Sum of digits = 19

219
Control Statements

Program 10.13To find the compound interest given amount, rate of interest and time

#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) program
{
float priamt, netamt, rate, ci;
int time, year;
clrscr();
cout<< "Enter the principal amount, rate of interest and time: "<<endl;
cin>>priamt>>rate>>time;
netamt = priamt;
year = 1;
while ( year <= time )
{
netamt = netamt*(1+rate/100);
year++;
}
ci = netamt - priamt;
cout<<"Compound interest = "<<ci<<endl;
cout<< "Nett amount = "<<netamt<<endl;
getch();
}

Sample run: Enter the principal amount, rate of interest and time:
1000 10 5
Compound interest = 610.51
Nett amount = 1610.51

220
Control Statements

10.4.1 do-while loop


This
eÁwlooping structure is also called as post-tested looping structure. Unlike while loop that test
the loop condition at the beginning, the do-while loop checks the condition after the execution of the
statement. This means that a do-while loop always executes at least once. Its functionality is exactly the
same as the while loop, except that the condition in the do while loop is evaluated after the execution of
statement, instead of before.
The general form of the while loop is:

do do
{ {
statement 1; statement 1;
} while ( test-condition ); OR statement 2;
…….
statement-n;
} while ( test-condition );

statement1 statement1

statement2
T Is OR
condition?
n
F
nextStatemen statementn
t1

T
f Is
condition?

F
f

Although the curly braces are not necessity when only one statement is present, they are usually
used to avoid confusion. The do-while loop iterates until condition becomes FALSE.

221
Control Statements

Program 10.14 To print all even numbers from 1 to 25 using do-while loop

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int i;
clrscr();
i = 2;
do
{
cout<<setw(4)<<i ;
i = i+2;
}while ( i <= 25);
getch();
}

Sample Run : 2 4 6 8 10 12 14 16 18 20 22 24

Program 10.15 To determine whether the given number is an Armstrong number

#include <iostream.h>
#include <conio.h>
#include<iomanip.h> Practical
void main( ) program
{
int n, sum, num, digit ;
clrscr();
cout<<”Enter the number: ”;
cin>>n;
num = n;
sum = 0;
do
{
digit = num%10;
sum = sum+digit*digit*digit;
n = n/10;
}while (n != 0);
if (sum == num)
cout<<”It is an Armstrong number”<<endl;
else
cout<<”It is not an Armstrong number”<<endl;
getch();
}

222
Control Statements

Sample Run :Enter the number: 153


eÁw
It is an Armstrong number

Sample Run :Enter the number: 175


It is not an Armstrong number

If the number can be expressed as the sum of cube of its digits, the number is called an Armstrong
number.

10.4.3 Comparison of while and do-while statements

while do-while

 It is a pre-tested looping structure.  It is a post-tested looping


 It tests the given condition at initial structure.
pint of looping structure  It tests the given condition at the
 If given condition is TRUE then last of looping structure.
body of the loop will be executed  If the given condition is TRUE
again and again. then body of the loop will be
 If the condition becomes FALSE, executed again and again.
controller will comes out of loop  If the condition becomes FALSE,
and executes next set of statements controller will comes out of loop
 If condition is FALSE, it will not and executes next set of statements
allow controller to execute the  Even the condition is FALSE at
statements. initial point, then also this loop
 The statements may not be executes statements once, then
executed even once. terminates it.
 while(test_condition)  The statements are executed atleast
{ once.
statement1;  do
statement2; {
: statement1;
: statement2;
statementn; ------
} statement;
} while(test_condition);

223
Control Statements

10.4.4 The for loop


This statement is called as the fixed execution looping statement. It is normally used when we
know in advance exactly how many times a set of statements should be repeatedly executed again and
again. It provides initialization, loop-end-condition and increment/decrement process statements in a single
line. When one is aware of fixed number of iterations, then this looping structure is best suited.
The general form of for statement is

for ( initialization ; condition ; increment/decrement)


{
statement1;
statement2;
……..
statement;
}

for counter = IV to FV

statement1
statement2
……..
statementn

NEXT
counter

 The initialization is as n assignment statement that is used to set the loop control variable.
 The condition is a relation a relational expression that determines when the loop exits.
 The increment/decrement defines how the loop-control variables changes each time the loop
is repeated.
 You must separate these three major sections by semicolon.
 This for loop continues to execute as long as the condition is TRUE. Once the condition
becomes FALSE, the program execution continues on the statement following for structure.

224
Control Statements

For loop allow two initialization statements. It is one of the most common variations that
useseÁw
the comma operator to allow two or more variables to control the loop.

For example, for( x=0, y=0; x+y<10; ++y)

Its main function is to repeat the execution of statements while condition remains TRUE, like the
while loop. But in addition, the for loop provides specific locations to contain an initialization statement
and an increment/decrement statement. So this loop is specially designed to perform a repetitive action
with a counter which is initialized and increased/decreased on each iteration.
This looping structure works as follows.
1. Initialization is executed. Generally it is an initial value setting for a counter variable and is ex-
ecuted only one time.
2. Condition is checked. If it is TRUE the loop continues, otherwise the loop ends and control
exits from for structure.
3. Statement is executed as usual, it can be either a single statement or a block enclosed in curled
braces { and}.
4. At last, whatever is specified in the increase field is executed and the loop gets back to execute
step 2.
5 The initialization and increase fields are optional. They can remain empty, but in all cases the
semicolon sign between them must be written compulsorily.
6 Optionally, using the comma operator we can specify more than one expression in any of the
fields included in a for loop.

Program 10.16 To print all the odd numbers upto the given limit

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, i ;
clrscr();
cout<<”Enter the limit: “<<endl;
cin>>n;
for (i=1; i<=n; i=i+2)
cout<<setw(4)<<i;
getch();
}

Sample Run : Enter the limit: 25


1 3 5 7 9 11 13 15 17 19 21 23 25

225
Control Statements

Program 10.17 To find the factorial of a given number

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( ) Practical
{ program
int n,fact, i ;
clrscr();
cout<<”Enter the number: “;
cin>>n;
fact = 1;
for (i=1; i<=n; i++)
fact = fact * i;
cout<<n<<”! = “<<fact;
getch();
}

Sample Run : Enter the number: 7


7! = 5040

Program 10.18 Tofind all the integer divisors of a number

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n,i ;
clrscr();
cout<<”Enter the number: “;
cin>>n;
cout<<”The integer divisors are “<<endl;
for (i=2; i<=n/2; i++)
if (n% i == 0)
cout<<setw(5)<<i;
getch();
}

Sample Run : Enter the number: 108


The integer divisors are
2 3 4 6 9 12 18 27 36 54

226
Control Statements

10.5 Jump statements or Transfer of control from within loop


Transfer
eÁw of control within looping are used to
 Terminate the execution of loop
 Exiting a loop
 Half way through to skip the loop.

All these can be done by using break, exit, and continue statements.

10.5.1 break statement


The break statement has two uses. You can use it to terminate a case in the switch statement. And
you can also uses it to force immediate termination of a loop like, while, do-while and for, by passing the
normal loop conditional test. When the break statement is encountered inside a loop, the loop is
immediately terminated and program control resumes at the next statement.
The general format of break statement is:
break;

Example 10.5 for( n = 0; n < 100; n++ )


{
cout<< n;
if ( n ==10 ) break;
}

Above program segment prints the numbers 0 through 10 on the screen. Then the
loop terminates because break causes immediate exit from the loop, overriding the conditional test
n < 100.

227
Control Statements

Program 10.19 To test whether a given number is prime or not using break statement.

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, i, status;
clrscr();
cout<<”Enter the number: ”;
cin>>n;
status = 1;
for(i=2 ; i <=n/2; i++)
{
if(n % i == 0)
{
status = 0;
cout<<”It is not a prime “<<endl;
break;
}
}
if(status)
cout<< “ It is a Prime Number”;
getch();
}

Sample Run : Enter the number: 53


It is a Prime Number

Sample Run : Enter the number: 49


It is not a prime

10.5.2 exit( ) function


Just as you can break out of a loop, you can break out of a program by using the standard library
function exit( ). This function causes immediate termination of the entire program, forcing a return to the
operating system. In effect, the exit( ) function acts as if it were breaking out of the entire program.
The general form of the exit( ) function is:
exit ( ); OR void exit ( int return _code);

228
Control Statements

The return code is used by some operating systems and may be used by calling programs. By
convention,
eÁw
an exit code of 0 means that the program finished normally and any other value means that
some error or unexpected results happened.

Program 10.19 To test whether a given number is prime or not. Using exit( ) function

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, i;
clrscr();
cout<<”Enter the number: ”;
cin>>n;
for(i=2 ; i <=n/2; ++ i)
if(n % i == 0)
{
cout<<”It is not a prime “<<endl;
exit(0);
}

cout<< “It is a Prime Number”;


getch();
}

Sample Run : Enter the number: 17


It is a Prime Number

Sample Run : Enter the number: 25


It is not a prime

10.5.2 continue statement


The continue statement causes the program to skip the rest of the loop in the current iteration
as if the end of the statement block had been reached, causing it to jump to the start of the
following iteration.
The continue statement works somewhat like break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any code in
between.
The general form of the continue statement is:
continue;

229
Control Statements

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n;

clrscr();
for( n = 10; n > 0; n-- )
{
if ( n == 5 ) continue;
cout<<setw(5)<< n ;
}
cout<< “ END OF COUNT \n “ ;
getch();
}

Sample Run :10 9 8 7 6 4 3 2 1 END OF COUNT

10.5.3 goto statement


The goto allows to make an absolute jump to another point in the program. This statement
execution causes an unconditional jump or transfer of control from one statement to the other
statement with in a program ignoring any type of nesting limitations. The destination point is identified
by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier
followed by a colon ( : )
The general format of goto statement is:

statement1;
statement2;
gotolabel_name;
statement3;
statement4;
label_name: statement5;
statement6;

230
Control Statements

Program 10.21Program to print numbers from 10 to 1 usinggoto statement


eÁw
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n = 10;

loop: cout<<setw(5)<< n;
n--;
if ( n > 0 ) goto loop;
cout<< “END OF LOOP“ ;
getch();
}

Sample Run :10 9 8 7 6 5 4 3 2 1END OF LOOP

231
Control Statements

One mark questions:


1. What is compound statement?
2. What is block?
3. Name the types of control statements.
4. What are the three different constructs?
5. What is selection statement?
6. What is iterative statement?
7. What is the numerical equivalent of TRUE and FALSE?
8. Which selection statements does C++ provide?
9. What are the rules associated with if statement?
10. What is the purpose of else clause?
11. What is two way branching statement?
12. Correct the following code fragment:
if( x = 1 )
k = 100;
else
k = 10;

13. Consider the following program segment.


x = 10; y = 5;
if ( x > y) w = 15;
w = 25
cout<< " value of w is ";
cout<< w;
find the output.

14. What will be the output of the following code fragment?


;
cin>>a;
if( a == 50 )
cout<< “ FIFTY “;
else
cout<< “ NOT FIFTY “;
If the input given is i. 70 ii. 50, what is the output?

232
Control Statements

14. What will be the output of the following code fragment?


eÁw ;
int year;
cin>> year;
if ( year % 100 == 0)
if ( year % 400 == 0)
cout<< “ LEAP “;
else
cout<< “ NOT CENTURY YEAR “;

if the input given is i. 2000. ii. 1900. iii. 1971. ?

15. State the use of nested if statement.


16. What is the purpose of switch statement?
17. How does the switch statement differ from if statement.
18. What type of value can be taken by case labels?
19. What is the significance of default clause in a switch statement?
20. Define the term looping.
21. Name the iteration statements provided by C++.
22. When should we use while and do while loop?
23. What is pre-tested looping structure?
24. What is post-tested looping structure?
25. Write a program fragment to display numbers 2, 4, 6, 8, 10, ………..18, 20.
Using while loop.
26. Write a program fragment to display numbers 1,3,5,7,9,………….17,19.
Using do while loop.
27. Which structure is called as fixed-execution looping statement?
28. When should we use for loop?
29. What is the output of the following code fragment?
for ( int i = 1; i< 10; i ++ )
cout<< i;
30. Why does “ Hellow” not print even once ?
for ( i = 0 ; i > 10 ; i ++ )
cout<< “ Hellow “;

31. Write a for loop that display the numbers from 50 to 61.
32. Name the jump statements provided by C++.
33. What is purpose of break statement?
34. Why is the continue statement used?
35. What is the function of exit( ) ?
36. Which header file must be included in the program for using the exit( )function?.
233
Control Statements

Two marks questions:


1. What is the purpose of if – else statement?
2. What are the nested statements?
3. Write syntax of if- else statement.
4. What is the purpose of switch statement?
5. What are the case labels? What type of labels must be used in case labels?
6. What will be the output of following code when i. ’A’ ii. ‘C’. iii. ’D’. iv. ‘F’.
cin>> choice;
switch(choice)
{
case ‘A’ :cout<<“ GRADE A \n”;
case ‘B’ : cout<< “ GRADE B \n”;
case ‘C’ : cout<< “GRADE C \n”;
break;
case ‘D’ : cout<< GRADE D \n”;
default: cout<< GRADE F \n”;
}

7. Explain the syntax of the while loop with a suitable example.


8. Explain working of do while loop with an example.
9. Compare the working of while and do while loop.
10. Write a short program using while to print 14710………. 40.
11. Write a program segment using do while to print all odd numbers from 1 to 24
12. Write a short program to find largest of three numbers.
13. Write a short program to test the given number is even or odd.
14. Explain the syntax of for loop with a suitable example.
15. Compare break and continue statements.
16. Write the function of goto statement with general format.

Five marks questions:


1. Explain the working of if statement and if else statement with suitable program fragments.
2. Explain if else if statement with general format and suitable example.
3. Explain the working of switch statement with an example.
4. Write general format of while loop with a suitable programming example.
5. Explain working of do while statement with an example.
6. Write a program to find the sum of the series 1+1/3!+1/5!+…….1/n! using while loop.
7. Differentiate between while looping with do while looping structure
8. Explain working of for looping structure with a programming example.
9. Write a program to find sum of digits of a given number using while loop
10. Write a program to find GCD of two numbers using while loop

234
Control Statements

11. Write a program to find the sum occurrence of a digit of a given number using do while.
12.eÁw Write a program to find all the integer divisors of a given number using for loop.
13. Write a program to find factorial of a given number using for loop.
14. Write a program to print Fibonacci series using for loop.
15. Write a program to find sum of the series s = 1+x+x2+…………+xn using for loop.

235
236
eÁw

CHAPTER 11
Arrays

OBJECTIVES
To Understand the need of arrays
Usage
Implementation

237
238
Arrays

11.1 Introduction
In eÁw
everyday life we commonly group similar objects into units. We buy peas by the can and eggs by
the carton. In computer languages we also need to group together data items of the same type. The most
basic mechanism that accomplishes this in C++ is the array. Arrays can hold a few data items or tens of
thousands. The data items grouped in an array can be simple types such as int or float, or they can be
user-defined types such as structures and objects.
Arrays exist in almost every computer language. Arrays in C++ are similar to those in other languages,
and identical to those in C.
In this chapter we’ll look first at arrays of basic data types such as int and char. Then we’ll examine
arrays used as data members in classes and arrays used to hold objects. Thus, this chapter is intended not
only to introduce arrays, but to increase your understanding of object oriented programming.

11.1.1 Array fundamentals


An array is collection of objects and all the objects have the same name. Each object is called
an element. The elements are numbered as 0, 1, 2,…,n-1. These numbers are called as indices or subscripts.
These numbers are used to locate the positions of elements within the array.
If a is the name of the array, the elements can be directly accessed as a[0], a[1], a[2], ..., a[n-1].
a[0] is the name of the first element present at position 0, a[1] is the name of the second element present
at position 1 and so on. In general, a[i] is the element present at position i.
An array can be represented as

a 10 20 30 40 50

0 1 2 3 4

In the above array, a is the name of the array, a[0] contains the element 10, a[1] contains the element
20, a[2] contains the element 30, a[3] contains the element 40 and a[4] contains the element 50. The
diagram represents a region of the memory, because the array elements are always stored in a contiguous
sequence.
The method of numbering the ith element with index i-1 is called as zero-based indexing.
That is, the element is always same as the number of “steps” from the initial element a[0] to that element.
For example, the element a[3] is 3 steps from the element a[0].

An array is collection of elements where all the elements are same datatype and under the same
name.

In C++, the subscripts always start with 0. For example, if b is the name of the array b[0], b[1],
b[2], ….. are the elements and 0, 1, 2, …. are the subscripts.

239
Arrays

11.2 Types of arrays


There are three types of arrays.
i. One-dimensional array
ii. Two-dimensional array
iii. Multi-dimensional array

11.2.1 One-dimensional array


It is an array in which each element is accessed by using only one subscript. The only one subscript
represents the position of the element in the array.

11.2.2 Two-dimensional array


It is an array in which each element is accessed using 2-subsripts. The subscripts represent the
position of element in the array.

11.2.3 Multi-dimensional array


A multidimensional array is an array of n-dimensions. In other words, an array of arrays is called a
multidimensional array. A one-dimensional array of one-dimensional arrays is called a two-dimensional
array; a one-dimensional array to two-dimensional arrays is called a three-dimensional array and so on.

11.3 One-dimensional array:


It is an array in which each element is accessed by using only one subscript. The only one subscript
represents the position of the element in the array.
Like other variables, the array should also be defined before it is used to store elements. An array
can be defined by specifying the datatype of the elements followed by name of the array and the number
of elements that can be stored in the array. The number of elements that can be stored in the array is called
the size of the array. The size of the array must be a constant or an expression that evaluates to a
constant, and should also be an integer. The size should be enclosed within square brackets.

11.3.1 Declaration of one-dimensional array


Syntax datatype array-name[size];

Example 11.1: int marks[50];


This example defines an array marks that can store 50 elements and all the elements are of int
datatype.

11.3.2 Initialization of one-dimensional arrays


You can give values to each array element when the array is first defined.

240
Arrays

Example 11.2: int a[5] = {9, -5, 6, 2, 8};

In eÁw
the above example, value 9 is stored in a[0], value -5 is stored in a[1], value 6 is store in a[2],
value 2 is stored in a[3] and value 8 is store in a[4].

a 9 -5 6 2 8

0 1 2 3 4

If there is less number of elements specified than the size of the array, the remaining elements are filled
with 0 by the compiler.

Example 11.3: float weight[5] = {1.5, 2.8, 2.5};

In the above example, value 1.5 is stored in weght[0], value 2.8 is stored in weght[1], value 2.5 is
store in weight[2]. The elements weight[3] and weight[4] are initialized with 0. Thus, in the initialization,
the default value is 0.

weight 1.5 2.8 2.5 0.0 0.0

0 1 2 3 4

If an array does not include an initialization, then the array elements may contain the unexpected
values called “garbage values”.
When an array has an explicit initialization, its size can be omitted from the declaration.

Example 11.4: int a[5] = {9, -5, 6, 2, 8};


is equivalent to int a[] = {9, -5, 6, 2, 8};

11.3.3 Accessing the elements


Consider the declaration int a[5];
We can read 5 elements into the array through the input device by writing the following program
fragment.
cout<<“Enter the elements: “;
for(i=0; i<5;i++)
cin>>a[i];
To print the 5 elements of the above array, we write the following program fragment.
cout<<“The elements are: “;
for(i=0; i<5;i++)
cout<<setw(5)<<a[i];

241
Arrays

In general, to read n elements into the array and print the elements, we write the following
program.

Program 11.1: To read the elements into the array and printing the elements

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, n;

clrscr( );
cout<<”How many elements?”<<endl;
cin>>n;

cout<<”Enter the elements: “;


for(i=0; i<n; i++)
cin>>a[i];

cout<<”The elements are: “;


for(i=0; i<n ;i++)
cout<<setw(5)<<a[i];

getch( );
}

Sample run: How many elements?


5
Enter the elements: 10 20 50 40 30
The elements are: 10 20 50 40 30

242
Arrays

Program11.2: To find the sum and average of n numbers of the array


eÁw

#include<iostream.h>
#include<conio.h>
#include<iomanip.h> Practical
void main( ) program
{
int a[50], i, n, sum;
floatavg;

clrscr( );
cout<<”How many elements?”<<endl;
cin>>n;

cout<<”Enter the elements: “;


for(i=0; i<n; i++)
cin>>a[i];

sum = 0;
for(i=0; i<n ;i++)
sum = sum + a[i];
avg = (float)sum/n;
cout<<”Sum = “<<sum<<endl;
cout<<”Average = “<<avg<<endl;

getch( );
}

Sample run: How many elements?


5
Enter the elements: 10 20 50 40 30
Sum = 150
Average = 30

243
Arrays

Program11.3:To find the second largest of n numbers in the array

#include<iostream.h>
#include<conio.h>
#include<iomanip.h> Practical
void main( ) program
{
int a[50], i, n, largest, secondlar;

clrscr( );
cout<<”How many elements?”<<endl;
cin>>n;

cout<<”Enter the elements: “;


for(i=0; i<n; i++)
cin>>a[i];

if(a[0] > a[1])


{
largest = a[0];
secondlar = a[1];
}
else
{
largest = a[1];
secondlar = a[0];
}
for(i=2; i<n ;i++)
if(a[i] > largest)
{
secondlar = largest;
largest = a[i];
}
else
if(a[i] >secondlar)
secondlar = a[i];

cout<<”Largest = “<<largest<<endl;
cout<<”Second Largest = “<<secondlar<<endl;

getch( );
}

Sample run: How many elements?


5
Enter the elements: 10 20 50 40 30
Largest = 50
Second Largest = 40

244
Arrays

We can search the position of an element in the array. The following program compares the search
elementeÁw
with each element of the array to find the position.

Program 11.4:To find the position of an element in the array using linear search method

#include<iostream.h>
#include<conio.h>
Practical
#include<iomanip.h>
program
void main( )
{
int a[50], i, pos, ele, n;

clrscr( );
cout<<”Enter the number of elements: ”;
cin>>n;

cout<<”Enter the elements: “;


for(i=0; i<n; i++)
cin>>a[i];

cout<<”Enter the search element: ”;


cin>>ele;

pos=-1;
for(i=0; i<n ;i++)
if(ele == a[i])
{
pos = i;
break;
}
if(pos>= 0)
cout<<”The element “<<ele<<” is present at position ”<<pos<<endl;
else
cout<<”The search element “<<ele<<” is not present”<<endl;

getch( );
}
Sample run: Enter the number of elements: 5
Enter the elements: 10 20 50 40 30
Enter the search element: 40
The element 40 is present at position 3

Sample run: Enter the number of elements: 5


Enter the elements: 10 20 50 40 30
Enter the search element: 25
The search element 25 is not present

245
Arrays

We can sort the elements of the array. The following program will sort the elements of the array by
using a technique called bubble sort.

Program 11.5:To sort the elements of the array

#include<iostream.h>
#include<conio.h>
#include<iomanip.h> Practical
void main() Program
{
int a[50], i, temp, n, j;

clrscr();
cout<<”Enter the number of elements: ”;
cin>>n;

cout<<”Enter the elements: “;


for(i=0; i<n; i++)
cin>>a[i];

for(i=1; i<n; i++)


for(j=0; j<n-i; j++)
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}

cout<<”The sorted elements are: “;


for(i=0; i<n ;i++)
cout<<setw(5)<<a[i];

getch( );
}

Sample run: Enter the number of elements: 5


Enter the elements: 30 20 50 40 10
The sorted elements are: 10 20 30 40 50

246
Arrays

Memory representation of one-dimensional arrays:


The elements of one-dimensional arrays are stored in contiguous memory locations.
eÁw

Example 11.5: Consider the declaration, char a[5];

The element a[0] is allocated at a particular memory location, the element a[1] is allocated
at next memory location and so forth. Since the array is of the type char, each element requires
1-byte.

5000 5001 5002 5003 5004

a[0] a[1] a[2] a[3] a[4]

Example 11.6: Consider the declaration, inta[3];

The element a[0] is allocated at a particular memory location, the element a[1] is allocated
at next memory location and so forth. Since the array is of the type int, each element requires
2-bytes.

5000 5001 5002 5003 5004 5005

a[0] a[1] a[2]

The amount of storage space required to hold an array is directly related to its type and size of the
array. The total size can be calculated using the relation:
Total-size = sizeof( type ) * size_of_array
Example 11.6: The total size to char array required is 1 * 5 = 5-bytes
The total size to int array required is 2 * 3 = 6-bytes

247
Arrays

11.4 Two-dimensional arrays


It is an array in which each element is accessed using 2-subsripts. The subscripts represent the
position of the elements in the array.
The elements of two dimensional arrays are represented as rows and columns. To identify any
element, we should know its row-number and column-number.

Column-numbers
0 1 2 3 …. n-1
0

R 1
o 2 a[2][3]
w …
s
m-1 Row-number Column-number

The above array contains m-rows and n-columns.

11.4.1 Declaration of two-dimensional array:


A two-dimensional array can be defined by specifying the datatype of the elements followed by
name of the array followed by the number of rows (i.e., row-size) and number of columns (i.e., column-
size) in the array. The row-size and column-size of the array must be constants or expressions that
evaluates to an integer. The row-size and column-size should be separately enclosed within square brack-
ets.
Syntax datatype array-name[row-size][column-size];

Example 11.7: int a[2][3];

This example defines an array a that can store 6 elements and all the elements are of int datatype.
The elements are arranged as 2-rows and 3-columns.

11.4.2 Initialization of two-dimensional arrays


Similar to the one dimensional array, we can initialize a two-dimensional array either by initializing it
in its declaration or by using assignment statement.

Example 11.8: int a[2][3] = {1, 2, 3, 4, 5, 6};

a is a two dimensional array which contains 2 rows and 3 columns and these assignments
would be

248
Arrays

a[0][0] = 1 a[0][1] = 2 a[0][2] = 3


eÁw a[1][0] = 4 a[1][1] = 5 a[1][2] = 6
if the values are missing in an initialize, they are automatically set to 0.
Example 11.9: int b[2][3] = {
{1, 2},
{3}
};
will initialize the first two elements to the first row, the next element to the second row. The remaining
elements are automatically set 0.
b[0][0] = 1 b[0][1] = 2 b[0][2] = 0
b[1][0] = 3 b[1][1] = 0 b[1][2] = 0

Example 11.10: int c[2][3] = {{0},{0}};

will set all the elements of the array to 0.


c[0][0] = 0 c[0][1] = 0 c[0][2] = 0
c[1][0] = 0 c[1][1] = 0 c[1][2] = 0

11.4.3 Accessing the elements


Consider the declaration int a[2][3];
We can read 6 elements into the array, we need to use nested for loops. One loop processes the
rows and another loop processes the columns. If outer loop is for rows and inner loop is for columns, then
for each row index, all the columns are processed and then the same process is repeated for next row
index. To understand this, let us consider the following program fragment.
cout<<“Enter the elements: “;
for(i=0; i<2; i++) //outer loop to control the rows
for(j=0; j<3; j++) //inner loop to control the columns
cin>>a[i][j];

The above code first reads all the columns for row-no 0.

a[0][0]

a[0][1]

a[0][2]

Row-index 0 Column-index from 0 to 2

249
Arrays

The above code then reads all the columns for row-no 1.

a[1][0]

a[1][1]

a[1][2]

Row-index 1 Column-index from 0 to 2

To print the above 6 elements as 2-rows and 3-columns, we write the following program
fragment.
cout<<“The elements are: “<<endl;
for(i=0; i<2 ;i++)
{
for(j=0; j<3; j++)
cout<<setw(5)<<a[i][j]; //Each element is printed using 5-columns
cout<<endl;
}

250
Arrays

In general, to read mxn elements into the array and print the elements, we write the following
program.
eÁw

Program 11.6: To read the elements into the array and printing the elements

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[5][5], i, j, m, n;

clrscr( );
cout<<”Enter the order: ”;
cin>>m>>n;

cout<<”Enter the elements: “<<endl;


for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];

cout<<”The elements are: “<<endl;


for(i=0; i<m ;i++)
{
for(j=0; j<n; j++)
cout<<setw(5)<<a[i][j];
cout<<endl;
}

getch( );
}

Sample run: Enter the order: 2 3


Enter the elements:
121
101
The elements are:
1 2 1
1 0 1

251
Arrays

Program 11.7: To find the transpose of a matrix

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[5][5], t[5][5], i, j, m, n;
clrscr( );
cout<<“Enter the order: “;
cin>>m>>n;
cout<<“Enter the elements: “<<endl;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];
for(i=0; i<m; i++)
for(j=0; j<n; j++)
t[j][i] = a[i][j];
cout<<“The transposed matrix is: “<<endl;
for(i=0; i<n ;i++)
{
for(j=0; j<m; j++)
cout<<setw(5)<<t[i][j];
cout<<endl;
}
getch( );
}

Sample run: Enter the order: 2 3


Enter the elements:
123
456
The transposed matrix is:
1 4
2 5
3 6

252
Arrays

Program 11.8: To find the sum of two compatible matrices


eÁw
#include<iostream.h>
#include<conio.h> Practical
#include<iomanip.h> Program
void main( )
{
int a[5][5], b[5][5], s[5][5], i, j, m1, n1, m2, n2;

clrscr( );
cout<<”Enter the order of the of the first matrix: ”;
cin>>m1>>n1;

cout<<”Enter the order of the of the second matrix: ”;


cin>>m2>>n2;

cout<<”Enter the elements of the first matrix: “<<endl;


for(i=0; i<m1; i++)
for(j=0; j<n1; j++)
cin>>a[i][j];

cout<<”Enter the elements of the second matrix: “<<endl;


for(i=0; i<m2; i++)
for(j=0; j<n2; j++)
cin>>b[i][j];

if( (m1==m2) && (n1==n2) )


{
for(i=0; i<m1; i++)
for(j=0; j<n1; j++)
s[i][j] = a[i][j] + b[i][j];

cout<<”The resultant matrix is: “<<endl;


for(i=0; i<m1 ;i++)
{
for(j=0; j<n1; j++)
cout<<setw(5)<<s[i][j];
cout<<endl;
}
}
else
cout<<”Matrices are not compatible … “<<endl;
}

253
Arrays

Sample run: Enter the order of the of the first matrix: 2 3


Enter the order of the of the second matrix: 2 3
Enter the elements of the first matrix:
123
456
Enter the elements of the second matrix:
251
211
The resultant matrix is:
3 7 4
6 6 7

Sample run: Enter the order of the of the first matrix: 2 3


Enter the order of the of the second matrix: 3 3
Enter the elements of the first matrix:
123
456
Enter the elements of the second matrix:
251
211
413
Matrices are not compatible …

The following program finds the product of two matrices. Two matrices can be multiplied only
if they are compatible. Otherwise, an error message should be displayed. Two matrices are compatible
for multiplication if the number of columns of the first matrix is same as the number of rows of the second
matrix.

254
Arrays

Program 11.9: To find the product of two compatible matrices


eÁw
#include<iostream.h>
#include<conio.h> Practical
#include<iomanip.h> program
void main()
{
int a[5][5], b[5][5], p[5][5], i, j, k,m1, n1, m2, n2;

clrscr();
cout<<”Enter the order of the first matrix: ”;
cin>>m1>>n1;
cout<<”Enter the order of the second matrix: ”;
cin>>m2>>n2;

cout<<”Enter the elements of the first matrix: “<<endl;


for(i=0; i<m1; i++)
for(j=0; j<n1; j++)
cin>>a[i][j];
cout<<”Enter the elements of the second matrix: “<<endl;
for(i=0; i<m2; i++)
for(j=0; j<n2; j++)
cin>>b[i][j];

if( n1==m2 )
{
for(i=0; i<m1; i++)
for(j=0; j<n2; j++)
{
p[i][j] = 0;
for(k=0; k< n1; k++)
p[i][j] = p[i][j] + a[i][k] * b[k][j];
}

cout<<”The resultant matrix is: “<<endl;


for(i=0; i<m1 ;i++)
{
for(j=0; j<n2; j++)
cout<<setw(5)<<p[i][j];
cout<<endl;
}
}
else cout<<”Matrices are not compatible … “<<endl;
}
255
Arrays

Sample run: Enter the order of the first matrix: 2 3


Enter the order of the second matrix: 2 3
Enter the elements of the first matrix:
1 2 3
4 5 6
Enter the elements of the second matrix:
2 5 1
2 1 1
The matrices are not compatible…

Sample run: Enter the order of the first matrix: 2 3


Enter the order of the second matrix: 3 3
Enter the elements of the first matrix:
123
456
Enter the elements of the second matrix:
251
211
413
The resultant matrix is:
18 10 12
42 31 27

256
Arrays

Program 11.10: To find the sum of all the rows and sum of all the columns in a matrix
eÁw
#include<iostream.h>
#include<conio.h>
#include<iomanip.h> Practical
void main( ) program
{
int a[5][5], m, n, i, j, rsum, csum;

clrscr( );
cout<<”Enter the order of the first matrix: ”;
cin>>m>>n;

cout<<”Enter the elements of the matrix: “<<endl;


for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];

for(i=0; i<m; i++)


{
rsum = 0;
for(j=0; j<n; j++)
rsum = rsum + a[i][j];
cout<<”Sum of row-no:“<<i+1<<” = “<<rsum<<endl;
}

for(i=0; i<n; i++)


{
csum = 0;
for(j=0; j<m; j++)
csum = csum + a[j][i];
cout<<”Sum of column-no:“<<i+1<<” = “<<csum<<endl;
}
}

Sample run: Enter the order of the first matrix: 2 3


Enter the elements of the matrix:
121
305
Sum of row-no:1 = 4
Sum of row-no:2 = 8
Sum of column-no:1 = 4
Sum of column-no:2 = 2
Sum of column-no:3 = 6

257
Arrays

Program 11.11: To find whether the matrix is a rectangular or a square or a scalar matrix

#include<iostream.h>
#include<conio.h> Practical
#include<iomanip.h> program
void main( )
{
int a[5][5], m, n, i, j, scalar, scalarele;

clrscr( );
cout<<”Enter the order : ”;
cin>>m>>n;

cout<<”Enter the elements of the matrix: “<<endl;


for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];
if(m == n)
{
cout<<”It is a square and “;
scalar = 1;
scalarele = a[0][0];
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(i == j)
{
if(a[i][j] != scalarele)
{
scalar = 0;
break;
}
}
else
if(a[i][j] != 0)
{
scalar = 0;
break;
}
if(scalar)
cout<<“scalar”<<endl;
else
cout<<”not scalar”<<endl;
}

258
Arrays

else
eÁw cout<<”It is a rectangular matrix”<<endl;
getch();
}

Sample run 1: Sample run 2: Sample run 3:


Enter the order: 2 3 Enter the order: 3 3 Enter the order: 3 3
Enter the elements Enter the elements Enter the elements
3 0 0 3 0 0 3 0 0
0 3 0 0 3 0 0 3 0
It is a rectangular matrix 0 0 3 3 0 3
It is a square and scalar It is a square and not scalar

A scalar matrix is square matrix in which all the principal diagonal elements are same (called scalar
element) and all the remaining elements are zeroes.

11.2.3 Multi-dimensional array


A multidimensional array is an array of n-dimensions. In other words, an array of arrays is
called a multidimensional array. A one-dimensional array of one-dimensional arrays is called a two-
dimensional array; a one-dimensional array to two-dimensional arrays is called a three-dimensional array
and so on.

259
Arrays

Review questions:

One mark questions:


1. What is an array?
2. Why do we need arrays?
3. How arrays are different from normal variables?
4. What is zero based indexing?
5. What is the subscript of the first element of the array?
6. What is the data type of the array subscript?
7. How are the elements of one-dimensional array accessed?
8. What is the significance of subscript in the array?
9. Name the different types of arrays.
10. Define one-dimensional array.
11. Give the syntax of one-dimensional array.
12. Write the array declaration to store 100 elements of data type int.
13. Give the initialization of one-dimensional array.
14. What type of values will be before the initialization of the array?
15. Define two dimensional array.
16. Give one example of initialization of two-dimensional array.
17. Give the declaration of two-dimensional array.
18. How are the elements of two-dimensional array accessed?
19. What are multi-dimensional arrays?

Two marks questions:


1. What is the need for arrays?
2. Give the declaration of one-dimensional array with an example.
3. Give the initialization of one-dimensional arrays.
4. Give the initialization of declaration of two-dimensional array.
5. How do you initialize two-dimensional arrays?
6. What are the operations on arrays?
7. Write the program fragment to initialize the elements of the array and display the elements.

Three mrks questions:


1. What are arrays? Explain the different types of arrays.
2. Write the program fragment to read and write the elements of one-dimensional array.
3. Write the C++ program to search an element in the array.
4. Write C++ program to read n elements of the array and find total and average of all the elements.
5. Write a C++ program to read and write the elements of two-dimensional array.

260
Arrays

Five marks questions:


1. Write a C++ program to find the position of element in the array.
eÁw
2. Write a C++ program to sort the elements of one-dimensional array.
3. Write a C++ program to find the second highest element of the array.
4. Write a C++ program to find the sum of two compatible matrices.
5. Write a C++ program to find the transpose of a matrix.
6. Write a C++ program to find the product of two compatible matrices.
7. Write a C++ program to find the row-sum and column-sum of a matrix.
8. Write a C++ program to determine whether the matrix is a scalar matrix.

261
262
eÁw

CHAPTER 12
Functions

OBJECTIVES
To Understand the concept of functions
 Needs
 Types of functions

263
264
Functions

12.1 Introduction
If the
eÁw programs are complex and lengthy, they can be modularized into subprograms. The
subprograms are called as functions. The subprograms can be developed independently, compiled and
tested. They can be reused in other programs also.

A function is a named group of statements developed to solve a sub-problem and returns a value to
other functions when it is called.

12.1.1 Types of functions


There are two types of functions:
i. Library functions
ii. User-defined functions.

i. Library functions

A standard library is a collection of pre-defined functions and other programming elements which are
accessed through header files.

Header files are the files containing standard functions that our programs may use. This chapter
contains the information about some header files of C++ standard library and some functions of it. The
header files should be written within angled brackets and its functions are included into our programs by
#include directive.

ii. User-defined functions


We can create our own functions or sub-programs to solve our problem. Such functions are normally
referred to as user defined functions.
A user-defined function is a complete and independent program, which can be used (or invoked) by
the main program or by the other sub-programs. The user-defined functions are written to perform definite
calculations, after performing their task they send back the result to the calling program or sub-program.

 A user-defined function is a complete and independent program, which can be used (or invoked)
by the main program or by the other sub-programs.
 Header files are the files containing standard functions that our programs may
use.

265
Functions

12.2 Different header files


As said earlier, header files are the files containing standard functions that our programs may use.
C++ contains many header files and is listed below.

12.2.1 stdio.h
This header file contains functions and macros to perform standard i/o operations. When we include
the header file iostream.h, the header file stdio.h is automatically included into our program. The standard
i/o functions of the header file stdio.h are listed below in the table 12.1.

clearer fclose fcloseall fdopen fiof


ferror fflush fgetc fgetchar fgetpos
fgets fileno flushall fopen fprintf
fputc fputchar fputs fread freopen
fscanf fseak fsetpos -fsopen ftell
fwrite getc getchar gets getw
perror printf putc putchar puts
putw remove rename rewind rmtmp
scanf stbuf setvbuf sprintf _streror
strerror tempnam tmpfile tmpram ungetc
vfprintf vfscanf vprintf vscamf vsprintf
Table 12.1

12.2.2 string.h
This header file declares functions to manipulate strings and memory manipulation routines. The
functions contained in the header file string.h are listed below in the table 12.2.Further details about the
string functions are discussed in detail in the section 12.4.

memccpy memchr memcmp memcpy


memicmp memmove memset movedata
strcmp strcoll strcpy strcspn
strudp strerror stricmp strcmpi
strlen strlwr strncat strcmp
strcmpi strncpu strnicmp strnset
strpbrk strchr strrev strset
strspm strstr strtok strupr

Table 12.2

266
Functions

Macro
eÁw
12.2.3 stdlib.h
This header file is used to declare conversion routines, search/sort routines and other miscellaneous
things. The functions are listed below in the table 12.3.

_fullpath _makepath _searchenv _splitpath


atof atoi atol ecvt
fcvt gcvt itoa ltoa
_strdate _strtime strtod strtol
_strtoid strtoul ultoa mblen
mbtowc wcstombs wctomb abs
labs _irotl _irotr calloc
coreleft free malloc realloc
Table 12.3

12.2.4 iostream.h
This header file contains C++ streams and i/o routines andarelisted below in the table 12.4.

open close get getline read


write put seekg seekp tellg
rdstate bad eof fail good
clear
Table 12.4

12.2.5 iomanip.h
This header file contains functions and macros for I/O manipulators for creating parameterized
manipulations. The functions are listed below in the table 12.5.

doc endl ends flush


hex oct reset/osflags setbase
setfile setiosflags setprecision setw
ws
Table 12.5

267
Functions

12.2.6 math.h
This header file declares prototypes for the mathematical functions and error handlers. The
functions that are used to perform mathematical calculations and conversions are listed below in
the table 12.6.

acos acosl asin asinl atan


atanl atan2 atan2l atof cabs
cosh coshl div exp expl
fabs fabsl fevt floor floorl
fmod fmol frexp fexpl hypot
hypoll dexp ldexpl ldiv log
logi logio log101 matherr _matherrl
modf mofl poly polyl pow
polywl powlo powl0l sin sinl
asinh sinhl sqrt sqrtl tan
tanl tanh tanhl
Table 12.6

12.3 Mathematical library functions


C++ provides many mathematical functions. These functions can be used in mathematical
expressions and statements. The various functions are ceil(), exp(), fabs(), floor(), log(), pow() etc.
These functions are already covered in chapter 7.

12.4 Character and string functions


A character is any single character enclosed within single quotes. Some functions accept a character
as argument. The argument is processed as an int by using its ASCII code. To use these functions, the
header file ctype.h should be included.
Any character enclosed within single quotes is called as a single character constant or simply, a
character constant.
These functions will be of the form: int function-name(int character)

Any character enclosed within single quotes is called as a single character constant or simply, a character
constant.

268
Functions

Some functions that perform operations on characters are given below in the
table 12.7.
eÁw
Function Description Example

isalpha() It returns a nonzero value if the character is a isalpha(‘h’)returns1


letter. Otherwise it returns zero. isalpha(‘9’) returns 0

isdigit() It returns a nonzero value if the character is a digit. isdigit(‘9’) returns 1


Otherwise it returns zero. isdigit(‘h’) returns 0

isalnum() It returns a nonzero value if the character is a isalnum(‘9’) returns 1


letter or digit. Otherwise it returns zero. isalnum(‘!’) returns 0

isupper() It returns a nonzero value if the character is an isupper(‘S’) returns 1


upper-case letter. Otherwise it returns zero. isupper(‘h’) returns 0

islower() It returns a nonzero value if the character is a lower- islower(‘s’) returns 1


case letter. Otherwise it returns zero. isalpha(‘h’) returns 0
isspace() It returns a nonzero value if the character is a space, isspace(‘\n’) returns 1
tab, vertical tab, carriage return, form feed or isalpha(‘5’) returns 0
newline. Otherwise it returns zero.
ispunct() It returns a nonzero value if the character is a ispunct(‘%’) returns 1
special character. ispunct(‘\n’) returns 0
toupper() It converts a lowercase letter into uppercase. toupper(‘s’) returns S

tolower() It converts an uppercase letter into lowercase. tolower(‘S’) returns s


toascii() It converts the character into its ASCII value. toascii(‘z’) returns 122
Table 12.7
12.4.1 Inputting single character
We can input a character using the function get( ).
The general form is

char ch; char ch;


cin = get(ch); OR ch = cin.get(ch);

12.4.2 Outputting single character


put() function is used to display single character.
The general form is cout.put(ch);

Example 12.1: char ch;


ch = cin.get();
cout.put(ch);
269
Functions

Program12.1: To determine the type of character.

#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;

clrscr();
cout<<”Type-in a character: “;
ch = cin.get();

if((ch>= ‘A’ &&ch<= ‘Z’) || (ch>= ‘a’ &&ch<= ‘z’))


cout<<”It is an alphabet”<<endl;
else
if(ch>= ‘0’ &&ch<= ‘9’)
cout<<”It is a digit”<<endl;
else
cout<<”It is a special character”<<endl;

getch();
}

Sample run: Type-in a character: f


It is an alphabet

Sample run: Type-in a character: 5


It is a digit

Sample run: Type-in a character: *


It is a special character

270
Functions

Program12.2: To convert a character from upper-case to lower case and vice versa.
eÁw
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;

clrscr();
cout<<”Type-in a character: “;
ch = cin.get();

if(isupper(ch))
{
ch = tolower(ch);
cout<<”The lower-case letter is ”<<ch<<endl;
}
else
if(islower(ch))
{
ch = toupper(ch);
cout<<”The lower-case letter is ”<<ch<<endl;
}
else
cout<<”It is not an alphabet”<<endl;
getch();
}
Sample run: Type-in a character: f
The upper-case letter is F

Sample run: Type-in a character: S


The lower case letter is s

Sample run: Type-in a character: 9


It is not a character

12.4.3 String functions


A string is sequence of characters enclosed within double quotes. Strings are manipulated as one-
dimensional array of characters and terminated by null(‘\0’) character. C++ provides many functions to
manipulate strings. To use these functions, the header file string.h should be included.

271
Functions

 Sequence of characters that are enclosed within double quotes is called a string
constant or simply, a string.
 The number of characters present in the string is called a length of the string or size
of the string.
 Each character of a string is 1-byte long.

12.4.3.1 Declaring a string variable


The general form to declare a string is
char string_name[size];
 string_name is the name of the string variable
 size is the number of characters in the string. The size helps the compiler to allocate required
number of memory locations to store the string.

Example 12.2: char st[50];

This declaration reserves 50-bytes to store the characters of the string variable st.

12.4.3.2 Initializing a string


Like other variables, strings can also be initialized when they are declared.

Example 12.3: char s[10] = “Karnataka”;

There are only 9 characters in the string. The null character (‘\0’) is automatically appended to the
end of the string.

Example 12.4: char st[] = “Bangalore”;

The string st is initialized without specifying its size. The size is determined automatically which is 9 in
the above example.

Example 12.5: char st[] = {‘E’, ‘m’, ‘p’, ‘r’, ‘e’, ‘s’, ‘s’, ‘\0’};

The string is initialized character-wise. In this case, we must specify the null character.

Example 12.6: char st[10] = “Book”;

The string is initialized with only 4-characters and the null character is appended to the end of the
string.

272
Functions

 If an entire string is initialized to a string-variable then the null character is


automatically appended to end-of-string.
eÁw
 If sting is initialized by giving the characters, then we must explicitly specify the
string terminator. i.e., null character.

12.4.3.3 Inputting a string


C++ provides the function getline() to read a string.
The general form is

cin.getline(string, size);

Example12.7 cin.getline(st, 25);


 getline() function terminates reading characters on reading a newline character or when
number of characters read is equal to size.
 The newline character is read, but replaced by null character.

12.4.3.4 Outputting a string


C++ provides the function write() to output a string.
The general form is

cout.write(string, size);

Example 12.8 cout.write(st, 25);

 write() function display the specified number of characters.


 This function does not stop displaying the characters when encountering the null character.
As a result, if the size specified is greater than the length of the string, it displays beyond the
bounds of the line.

 getline() function terminates reading characters on reading a newline character.


 write() function does not stop displaying the characters when encountering the null
character.

273
Functions

Program 12.3: To read a string and print the string.

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{
char s[50];
int l;

clrscr();
cout<<”Enter the string: “;
cin.getline(s, 50);

l = strlen(s);

cout<<”The given string is “;


cout.write(s, l);
getch();
}

Sample run: Enter the string: Tumkur


The given string is Tumkur

Some string manipulation functions are given below:

12.4.3.5 strlen() function


This function returns the length of the string. i.e., the number of characters present in the string,
excluding the null character.
The general form is variable = strlen(string);
A string of length 0 is called a null string.

Example 12.9: l = strlen(“Empress”); Returns 7.

A string of length 0 is called a null string.

274
Functions

Program12.4: To find the length of the string using the library function.
eÁw
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{
char st[100];
int l;

clrscr( );
cout<<”Enter the string: “;
cin.getline(st, 100);

l = strlen(st);

cout<<”Length = “<<l<<endl;
getch();
}

Sample run: Enter the string: Bjarnestroustrup


Length = 17

Program12.5: To find the length of the string without using the library function.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{
char st[100];
int i;

clrscr( );
cout<<”Enter the string: “;
cin.getline(st, 100);

for(i = 0; st[i] != ‘\0’; i++); // for loop is terminated

cout<<”Length = “<<i<<endl;
getch( );
}

Sample run: Enter the string: Bjarnestroustrup


Length = 17

275
Functions

12.4.3.6 strcat() function


This function is used to concatenate two strings. The process of combining two strings to form a
string is called as concatenation.
The general form is strcat(string1, string2);

Example 12.10: char str1[] =”Win”;


char str2[] =”dows 8";
strcat(str1,str2);
str1 becomes “Windows 8”.

Program12.6: To concatenate two strings without using the library function.


#include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{
char f[100], s[100]; // f is the first string and s is the second string
int l1, l2, i;

clrscr( );
cout<<”Enter the first string: “;
cin.getline(f, 100);

cout<<”Enter the second string: “;


cin.getline(s, 100);

l1 = strlen(f); // l1 is the length of the first string


l2 = strlen(s); // l2 is the length of the second string

for( i = 0; i < l2; i++)


f[l1+i] = s[i]; // Characters of second string is copied to first

f[l1+l2] = ‘\0’; // Adding null character to the end of first string

cout<<”Concatenated string: “;
cout.write(f, l1+l2);
getch();
}
Sample run: Enter the first string: Love
Enter the second string: lace
Concatenated string: Lovelace

276
Functions

12.4.3.7 strcpy() function


A string
eÁw cannot be copied to another string by using assignment statement. The function strcpy() is
used to copy a string into another string.
The general form is strcpy(string1, string2);
It copies all the characters of string2 to string1.

Example 12.11: char str1[] =”Computer”;


char str2[] =”Science”;
strcpy(str1,str2); str1 becomes “Science”.

Program12.7: To copy a string into another string without using the library function.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{
char s[100], d[100]; // s and d are the source destination strings
int l, i;

clrscr( );
cout<<”Enter the source string: “;
cin.getline(s, 100);

l = strlen(s); // l is the length of the source string


for( i = 0; i < l; i++)
d[i] = s[i]; // Copying from source to destination

d[l] = ‘\0’; // Append null character to the end of string

cout<<l<<” characters are copied to destination string…”<<endl;

cout<<”Copied string: “;
cout.write(d, l);
getch();
}
Sample run: Enter the Source string: Charles Babbage
14 characters are copied into destination string…
Copied string: Charles Babbage

277
Functions

12.4.3.8 strcmp() function


This function is used to alphabetically compare a string with another string. This function is case-
sensitive. i.e., it treats the uppercase letters and lowercase letters as different.
The general form is strcmp(string1, string2);
It compares all the characters of str2 with str1. This function returns a positive value if string1>string2,
a negative value if string1<string2 or 0 it string1 is same as string2.
Example 12.12: char str1[] =”There”;
char str2[] =”there;”;
strcmp(str2,str1); gives a positive value
But, strcmp(str1,str2); gives a negative value

12.4.3.9 strcmpi() function


This function is used to alphabetically compare a string with another string. This function is
not case-sensitive. i.e., it treats the uppercase letters and lowercase letters as same.
The general form is strcmpi(string1, string2);

It compares all the characters of str2 with str1. This function returns a positive value if string1>string2,
a negative value if string1<string2 or 0 it string1 is same as string2.

Example 12.13: char str1[] =”There”;


char str2[] =”there;”;
strcmpi(str2,str1); gives 0

 The process of joining a string with another string is called as string


concatenation.
 If we copy string into another string, only the destination string changes and the
source string does not change.
 The function strcmp() is case-sensitive.
 The function strcmpi() is non-case-sensitive.

278
Functions

Program12.8: To determine whether the string is a palindrome.


eÁw
#include<iostream.h>
#include<conio.h>
#include<string.h> Practical
void main( ) program
{
char s[100], r[100]; // s is the string and r is the reversed string

clrscr( );
cout<<”Enter the string: “;
cin.getline(s, 100);

strcpy(r, s); // Copy the characters of the string s to r


strrev(r); // Reverse the characters of the string r

if(strcmpi(s, r) == 0)
cout<<”It is palindrome”<<endl;
else
cout<<”It is not palindrome”<<endl;

getch();
}

Sample run: Enter the string: REFER


It is palindrome

Sample run: Enter the string: Pascal


It is not palindrome

 Palindrome is word that does not change the character in it is reversed.


 It is suggestible to use strcmpi() function to check whether the word is a
palindrome. Thus, the strings “Malayalam” and “MALAYALAM” are both
palindromes.

279
Functions

Program12.9: To count the number of vowels and consonants in a string.


#include<iostream.h>
#include<conio.h>
#include<string.h> Practical
#include<ctype.h> program
void main( )
{
char s[100];
int l, i, cons = 0, vow = 0;

clrscr( );
cout<<”Enter the string: “;
cin.getline(s, 100);

l = strlen(s);
for( i = 0; i < l; i++)
if(isalpha(s[i]))
switch(toupper(s[i]))
{
case ‘A’:
case ‘E’:
case ‘I’ :
case ‘O’:
case ‘U’: vow++;
break;
default: cons++;
}

cout<<”Number of vowels: “<<vow<<endl;


cout<<”Number of consonants: “<<cons<<endl;
getch( );
}

Sample run: Enter the string: Enter the string: Dr. A P J Abdul Kalam
Number of vowels: 5
Number of consonants: 10

12.5 Other functions


C++ provides some useful functions under the library stdlib.h. Some functions are
rand( ), srand( ), random( )and randomized( ). These functions are used to generate pseudo-random
numbers. i.e., numbers that are uniformly distributed within a given interval and for which there is no
particular pattern.computer will generate a number by itself !! randomly, using this randomized( ).

280
Functions

eÁw
Review questions
One mark questions:
1. What is standard library?
2. Why is C++ standard library required?
3. What is the function of the header file iostream.h?
4. What is the function of the header file iomanip.h?
5. What is the function of the header file sring.h?
6. What is the function of the header file ctype.h?
7. What is the function of the header file math.h?
8. Name the function that converts a lowercase letter into uppercase?
9. Name the function that converts an uppercase letter to lowercase?
10. Name the function that returns the square root of a number.
11. Name the header file, to which the function toascii() belong.
12. Name the header file, to which the function sin() belong.
13. Name the header file, to which the function setw() belong.
14. Name the header file, to which the function toupper() belong.
15. Name the header file, to which the function strcat() belong.
16. Name the header file, to which the function fabs() belong.
17. Name the header file to perform operations on characters.
18. Name the header file to perform operations on strings.
19. Name the header file to perform mathematical operations.
20. What is a function?
21. What are the different types of functions?
22. What are library functions?
23. Give the syntax of get() function.
24. Give the syntax of put() function.
25. Why do we use strcat() function?
26. Why do we use strcmp() function?
27. Why do we use pow() function?
28. Name any one function to generate pseudo-random number.
29. Name the header file to be included to use the functions for generation of random numbers.

Two marks questions:


1. What is the need to use functions?
2. Distinguish between isupper() and tolower() functions.
3. Distinguish between islower() and toupper() functions.
4. Distinguish between strcmp() and strcmpi() functions.
281
Functions

5. Give the syntax of strcmp() function. Give an example.


6. What are the different types of values strcmp() function return?
7. Give the syntax of strcat() function. Give an example.
8. Name any two functions to generate the pseudo-random numbers.

Three marks questions:


1. Explain any four functions of the header file math.h.
2. Explain any four functions of the header file ctype.h.
3. Explain any four functions of the header file string.h.
4. Write a C++ program to convert a lowercase letter into uppercase and vice-versa.
5. Write a C++ program to find the length of string without using library function.
6. Write a C++ program to concatenate two strings using library function.
7. Explain any four character manipulation functions.
8. Explain any four string manipulation functions

Five marks questions:


1. Explain any five functions of the header file math.h.
2. Explain any five functions of the header file ctype.h.
3. Explain any five functions of the header file string.h.
4. Write the C++ program to find the length of the string without function.
5. Write the C++ program to concatenate two strings without function.
6. Write the C++ program to determine whether the given string is palindrome.
7. Write the C++ program to count number of vowels and consonants in a string.
8. Write the C++ program to copy a string into another string without function.

282
eÁw

CHAPTER 13
User Defined Functions

OBJECTIVES
To Understand the concept of functions
Their needs
Types of functions

283
284
User Defined Functions

13.1 Definition
User-defined
eÁw function is a function defined by the user to solve his/her problem. Such a function can
be called (or invoked) from anywhere and any number of times in the program.
The purpose of using a function is to make the program design process easy, understandable and
thereby avoiding ambiguity.
The type of functions called library functions are already discussed in the previous chapter 12. In this
chapter, we study the functions that are defined by the user.

13.2 Advantages of user-defined functions


i. If there is a set of statements to be repeated several times in the program, these statements can
be replaced as a function and called (or invoked) whenever and wherever required.
ii. If a task is needed in more than one program or to a group of programmers, a function can be
developed and made available to other programs or other programmers.
iii. Programs can be modularized into functions. Each function can be developed independently,
debugged and tested.
iv. If a problem is divided into sub-problems, a team of programmers can be formed to solve each
sub-problem, rather solving by a single person.
v. If functions are developed in a program, the number of lines decreases.

13.3 Function definition or structure of user-defined function


Any user-defined function has the following structure.

Function-header

return-type-specifier function-name(argument-list with declaration)


{
Local-variable-declarations;
Executable-statement-1;

Executable-statement-2; Body of the function


………..
Executable-statement-n;
return(expression);
}

285
User Defined Functions

 Return-type-specifier is the datatype of the value return by the function to anther


function when it is called. The return-type-specifier can be char, int, float or void.
data type void is used when the function return no value to the calling function.
 Function-name is the name of the function. It is an identifier to identify the particular
function in a program. The rules to form an identifier are already discussed in the introductory
section.
 Argument-list with declaration is the list of arguments or parameters or variables
with their declaration. Each argument should be declared separately. Each declaration
should be separated by comma. The list should be enclosed within parenthesis.
 The complete line is called the function header. Note that there is no semicolon at
the end.
 Local-variable declaration is the declaration of the variables that are used within the
function. Since these variables are local to the function, these variables are called as local variables.
 Executable-statements are the statements that perform the necessary operations to solve the
problem. If the function is returning a value, a return statement should be included. Otherwise,
return statement is not necessary.
 Local declaration and executable statements are together called as body of the function. The
body of the function should be enclosed within the curled braces.

 User-defined function is a function defined by the user to solve his/her problem.


 There can be more than one user-defined function in a program.
 To execute a user-defined function, it must be called by another function or the main
function.

286
User Defined Functions

Program 13.1: To find the greatest of three numbers.


eÁw

#include<iostream.h>
#include<conio.h>
void main()
{
int biggest(int,int,int); //function-prototype
int a, b, c,big;
clrscr();
Calling function Calling function
cout<<“Enter three numbers: “;
cin>>a>>b>>c;
big=biggest(a,b, c); //function-call statement
cout<<“Biggest= “<<big<<endl;
getch();
}
int biggest(int x, int y, int z)
{
int big; Called function
big=x>y?(x>z?x:z):(y>z?y:z);
return(big);
}
Sample run: Enter the numbers: 2 5 4
Biggest=5

13.4 Calling a function


The definition of the program can come either before the main() function or after the main()
function.
A function can be called by specifying its name, followed by list of arguments enclosed within the
parenthesis. The arguments should be separated by commas. If the function does not pass any arguments,
then an empty pair of parenthesis should follow the name of the function.

287
User Defined Functions

 Calling function is a function that transfers control from it to another function by


specifying the name of that function and passing arguments.
 Called function is a function that receives the call and arguments from another
calling function.
 Function call is the statement that is used to call or make another function execute.
 When a function call is made, the control jumps from calling function to the called
function.

The general form of function call is:.

variable = function-name(argument-list);
OR
variable=function-name();

The function call should be a simple expression such as an assignment statement or it may be part of
a complex expression.

Example 13.1 big = biggest(a,b,c);

288
User Defined Functions

Program 13.2: To find the cube of a number.


eÁw
#include<iostream.h>
#include<conio.h>
void main()
{
int cube(int);
int n;

cout<<”Enter the number: ”<<endl;


cin>>n;

cout<<”Cube of ”<<n<<”is = ”<<cube(n)<<endl;


getch();
}

int cube(int x)
{
return(x*x*x);
}

Sample run: Enter the number:


5
Cube of 5 = 125

13.4.1 main() function


In C++, the main() function returns a value of type int to the operating system. If the program runs
successfully, 0 is returned. Otherwise, a non-zero value is returned to the operating system, indicating that
the program contains errors.
If the main() function is not returning a value, the datatype void can be used as return-type-specifier.

The general form of main() function is:

int main() void main()


{ {
Executable-statements; OR Executable-statements;
return 0; }
}

289
User Defined Functions

13.5 Returning a value


When a function is called, the statements in the called function are executed. After
executing the statements, the function returns a value to the calling function. The return statement is
used to return a value. A function can return only one value or none to the calling function, for
every function call.
The general form of return statement is

return(expression); OR return 0;

 The usage of the return statement is not compulsory.


 A function can have many return statements depending on the situation. But only one return
statement is executed, since the execution of a return statement terminates the execution of the
function.
For example:
if(prime)
return ‘y’;
else
return ‘n’;
 Functions declared as void do not return a value. Hence the return statement need not be
included.
 The datatype of the returning value must be same as that of the return-type-specifier in the
function header.
 If return type is omitted, the function assumes that the return type is int by default. Therefore, in
C++ it is compulsory to declare the function prototype.
 The return statement terminates the execution of the function and the control is transferred back
to the calling function along with the value.

290
User Defined Functions

Program 13.3: To find the factorial of a number.


eÁw
#include<iostream.h>
#include<conio.h>
void main()
{
int factorial(int);
int n, fact;

clrscr();
cout<<”Enter a non-negative number: ”;
cin>>n;

fact=factorial(n);

cout<<n<<”! = ”<<fact<<endl;
getch();
}

int factorial( int n)


{
int f;

f=1;
for(int i=1; i <= n; i++)
f = f * i;

return(f);
}

Sample run: Enter a non-negative number: 5


5! = 120

291
User Defined Functions

13.6 Function prototypes


Like all variables are declared before they are used in the statements, the function should also be
declared. The function prototype is a declaration of the function in the calling function.
The general form of function prototype is

return-type-specifier function-name(type arg1, type arg2, ……);

OR

return-type-specifier function-name(type , type , ……);

Example 13.2: float volume(int x, float y, float z);


Or float volume(int, float, float);
 The function prototype describes the function interface to the compiler.
 The function prototype gives details such as name of the function to be called, number of
arguments, datatype of arguments and datatype of the returning value.
 With function prototyping, a template is created when declaring and defining a function.
When a function is called, the compiler checks the template to ensure that proper arguments are
passed and correct type of value is returned. Any violation in matching the arguments or the
return type will be caught by the compiler at the time of compilation.
 The difference between the function prototype and function header is that the function
prototype ends with semicolon.
 In the function declaration, the names of the arguments are dummy variables and therefore they
are optional. The variable names in the prototype act as just placeholders and therefore the
names can be included or excluded. If names are included, they do not have to match the names
used in the function call or function definition.

A function prototype is a declaration of the function that tells the program about the type of
the value return by the function and the number and type of arguments.

292
User Defined Functions

13.7 Types of arguments


A variable
eÁw in a function header is called an argument. The arguments are used to pass information
from the calling function to the called function.

13.7.1 Actual arguments


The function call statement contains name of the function and list of arguments to be passed. These
arguments or parameters are called as actual arguments. The arguments can be constants, variables or
expressions.

Example 13.3:In the function call g =gcd(a, b);

a and b are the actual arguments. Actual arguments have values stored in them before the function
call hence the name actual.

13.7.2 Formal arguments


The function header contains return-type-specifier, function name and list of arguments with their
declaration. These arguments are called as formal arguments or dummy arguments. Formal arguments get
their values from the actual arguments.

Example: In the function header int gcd(int x, int y)


x and y are the formal arguments.

 The actual arguments and formal arguments should same in number and order.
 The names of actual arguments and formal arguments can be same or different.
 Formal arguments should always be names of variables.

13.7.3 Local variables


The variables declared inside function or block is said belong to that block. These variables are
called as Local variables. Values of local variables are accessible only in that block. The function’s formal
arguments are also considered as local variables.

function (int a, int b)


{
int x, y; // x and y are local variables

293
User Defined Functions

13.7.4 Global variables


The variables declared outside the function are called as global variables. These variables are referred
by the same datatype and same name throughout the program in both the calling function and called
function. Whenever if some variables are to be treated as same value in both main() and in other functions,
it is advisable to use global variables.

int a,b; //a and b are global variables


void main()
{
int p, q; // p and q are local variables

The availability of the values of global variables starts from the point of definition to the rest of the
program. The following program illustrates this.

294
User Defined Functions

eÁw
Program 13.4: To find the lcm of two numbers

#include <iostream.h>
#include<conio.h>
int a, b; // a and b are global variables

int gcd( int x, int y)


{
int r; // r is a local variable

while(b != 0)
{
r = a % b;
a = b;
b = r;
}
return(a); Practical
} program
void main()
{
int gcd(int x, int y);
int product, lcm, g;

clrscr();
cout<<”Enter two numbers: “;
cin>>a>>b;

product = a * b;
g = gcd(a, b);
lcm = product / g;

cout<<”GCD = “<<g<<endl;
cout<<”LCM = “<<lcm<<endl;
getch();
}

Simple run: Enter two numbers: 18 24


GCD = 6
LCM = 72

295
User Defined Functions

13.8 Scope of variables


Scope of the variable refers to the part of the program where the value of the variable can be used.
The scope of a variable begins from where the variable declared. If the declaration is inside a function, the
scope extends to the end of the innermost block that contains the declaration.

13.8.1 Nested and parallel scopes


The scope of the variables or functions can be nested.
In the following example, f() and g() are global functions, and x is a global variable. Therefore, their
scope is to the entire program. The second x is declared inside main(), so it has local scope. i.e., it is
accessible only from within main(). The third x is declared inside an internal block, so its scope is restricted
to that internal block. Each scope overrides the scope of the previously declared x, so there is no ambiguity
when the identifier x is referenced. The scope resolution operator is used to access the last x whose scope
was overridden.

296
User Defined Functions

Program 13.5: To illustrate scope of variables


eÁw
#include<iostream.h>
#include<conio.h>

void f();
void g();
int x = 10;

void main()
{
int x = 20;
{
int x = 30;
cout<<”In block inside main(): x = “<< x <<endl;
}
cout<<”In main(): x = “ << x <<endl;
cout<<”In main: ::x = “ << ::x <<endl;
f();
g();
}
void g()
{
cout<<”In g(): x = “ << x<<endl;
}
void f()
{
int x = 40;

cout<<”In f(): x = “ << x <<endl;


}

Sample run: In block inside main(): x = 30


In main(): x = 20
In main(): ::x = 10;
In f(): x = 40
In f(): x = 10

297
User Defined Functions

13.9 TYPES OF FUNCTIONS


There are different types of functions.
i. Functions with no arguments and no return values
ii. Functions with arguments and with no return values
iii. Functions with no arguments and with return values
iv. Functions with arguments and with return values
v. Recursive functions

13.9.1 Functions with no arguments and with no return values


In this method, the function simply performs an independent task. The function does not receive or
send any arguments. The general form is

void function-name() void function-name(void)


{ {
statements; OR statements;
} }

Example 13.4: void natural( )


{
for(int i=1; i <= 10; i++)
cout<<setw(4)<<i;
}

13.9.2 Functions with arguments and with no return values


In this method, the function receives some arguments and does not return any value.
The general form is

void function_name(argument list)


{
statements;
}

298
User Defined Functions

Example 13.5: void average(int x, int y, int z)


eÁw
{
float sum, avg;

sum = x + y + y;
avg = sum/3.0;
cout<<“Average = “avg<<endl;
}

13.9.3 Functions with no arguments and with return values


In this method, the function receives no arguments but return a value.
return-type function-name()
{
statements
return(value);
}

Example 13.6: int greatest()


{
if(a>b)
return(a); else
return(b);
}

13.9.4 Functions with arguments and with return values


In this method, the function receives some arguments and returns a value.
return-type function-name(argument-list)
{
statements;
return(value);
}

Example 13.7: float interest(float p, float t, float r)


{
si = (p * t * r)/100;
return(si);
}

299
User Defined Functions

13.9.5 Recursive functions


Recursive function is a function that calls itself. The process of calling a function by itself is called as
recursion.

return-type function-name(argument-list)
{
statements;
return(function-name(argument-list));
}

Recursive functions must have one or more terminating conditions to terminate recursion. Otherwise,
recursion will become infinite.

300
User Defined Functions

Program 13.5 To find x^y using recursion


eÁw
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
float expo(float a, int n) Practical
{ Program
if (a == 0)
return 0.0;
else
if (n == 0)
return 1.0;
else
if (n > 0)
return(a*expo(a, n-1));
else
return(1/a*expo(a, n+1));
}
void main()
{
float expo(float, int);
float x;
int y;

clrscr();
cout<<”Enter the base: “;
cin>>x;
cout<<”Enter the Exponent: “;
cin>>y;

cout<<setprecision(3)<<x<<” ^ “<<y<<” = “<<expo(x,y)<<endl;


getch();
}

Sample Run 1: Enter the base: 0


Enter the Exponent: 3
0^3=0

301
User Defined Functions

Sample Run 2: Enter the base: 2


Enter the Exponent: 0
2^0=1

Sample Run 3: Enter the base: 2


Enter the Exponent: 3
2^3=8

Sample Run 4: Enter the base: 2


Enter the Exponent: -3
2 ^ -3 = 0.125

13.9.5 Passing default arguments to functions


In C++, to call a function we need not pass all the values for the arguments to a function from the
calling function. It allows us to assign default values to the formal arguments.
 Default values can be assigned to the arguments which does not have a matching argument in the
function call;
 Default values are assigned only in the function prototype.
 The default values are assigned to the arguments as we initialize variables.

Example 13.8: Consider the prototype


float interest (float amt, int time, float rate = 0.15);
0.15 is the default value provided to the argument rate.
The function call statement can be as follows:
si = interest( 5000,5 ); // third argument is missing
This statement passes the value 5000 to amt, 5 to time and uses default value 0.15 to
rate, because the third argument is missing in the function call statement. When all three
arguments are passed as:
si = interest(5000, 5, 0.2); // No missing parameters
passes 5000 to amt, 5 to time and 0.2 to rate.
Default arguments are used when a matching argument is missing in the function call
statement.

302
User Defined Functions

 Any argument in the prototype cannot have a default value. An argument in a prototype can have
default value if and only if all arguments appearing on its right have default values. Thus, default
eÁw
values should be added from right to the left. The following are valid examples of function
prototypes with default values:
float interest (float amt, int time, float rate = 0.15); //legal
float interest (float amt, int time=7, float rate = 0.15); // legal
float interest (float amt = 9500, int time=7, float rate = 0.15); //legal
float interest (float amt = 9000, int time, float rate = 0.15); //illegal
float interest (float amt = 9000, int time = 8, float rate); //illegal
 Default values should be assigned only in the function prototype. It should not be repeated in the
function definition.
 Default value for an argument can be a global variable, a global constant or even a function call;

Example 13.9: int default_funnction(int value = fun_call());


It is a legal prototype. The default function obtains a default value to its argument by calling
fun_call.
 Default arguments can be used with inline functions.

13.9.6 Uses of default arguments


i. Default arguments are useful in situations where some arguments always have the same
value.
ii. Default arguments provide flexibility to the programmers.
iii. Default arguments are used to add new arguments to the existing functions.
iv. Default arguments are used to combine similar functions into one.

303
User Defined Functions

Program 13.6: To illustrate default arguments

#include<iostream.h>
#include<conio.h>
void main()
{
float interest( float p, int t, float r =10.0);
floatamt;

clrscr();
amt = interest(7000.00, 5);
cout<<“By passing principle and time: Simple interest: “<<amt<<endl;
amt = interest(7000.00, 5, 11.0);
cout<<“By passing principle, time and rate: Simple interest: “<<amt<<endl;
getch();
}

float interest( float p, int t, float r )


{
return( (p * t * r ) / 100.0);
}

Simple run: By passing principle and time: Simple interest: 3500


By passing principle, time and rate: Simple interest: 3850

13.9.7 Passing constant arguments


In C++, we can declare some arguments as constants. The compiler cannot modify the arguments
marked as constants.

Example 13.10: int strlen(const char *p);


int total( const int x, const int y);
The qualifier const tells the compiler that the function should not modify the arguments marked as
constants. This type of declaration is used in standard library functions and when we pass arguments by
reference or pointers.

304
User Defined Functions

Program 13.7: To copy a string into another string using constant arguments
eÁw
#include<iostream.h>
#include<conio.h>
#include<string.h>
void copying(char *, const char *);
void main()
{
char s[50], d[50];

clrscr();
cout<<”Enter the string: “;
cin.getline(s,50);

copying(d,s);
cout<<”Copied string: “<<d<<endl;
getch();
}

void copying(char *d, const char *s)


{
for(; *s != ‘\0’; s++, d++)
*d = *s;
*d = ‘\0’;
}

Sample run: Enter the string: Stroustrup


Copied string: Stroustrup

13.10 Pass by value or Call by value


A function can be called by passing arguments from the calling function into the called function. Thus
the data is transferred through argument list.
The calling function sends the data to the called function through actual parameters. The called
function receives the data into its corresponding formal parameters. This is pass-by-value. In pass by
value, a copy of the data sent by the calling function is stored in temporary storage locations. The called
function uses these values as the initial values of the formal parameters. The formal arguments are
processed or changed to generate the required results. However, these changes are affected to the original
values stored in the actual parameters.

305
User Defined Functions

Program 13.8: To illustrate pass by value


#include<iostream.h>
#include<conio.h>

void main()
{
void swap(int , int);
int a, b;

clrscr();
cout<<”Enter two numbers: “;
cin>>a>>b;

cout<<”Before calling the function: a = “<<a<<” and b = “<<b<<endl ;


swap(a, b);
cout<<”After calling the function: a = “<<a<<” and b = “<<b<<endl ;
getch();
}
void swap(int x, int y)
{
int temp;

temp = x;
x = y;
y = temp;
}
Sample run: Enter two numbers: 10 20
Before calling the function: a = 10 and b = 20
After calling the function: a = 10 and b = 20

Observe that in the above program, even though the formal arguments x and y changed, the original
values in the actual arguments are not changed.

13.11 Pass by reference or call by reference


Sometimes we need to change the values of the actual arguments in the calling function. This is not
possible in the pass by value method.
C++ allows us to pass parameters to the function by using reference variables. When we pass
arguments by reference, the formal arguments in the called function become the aliases to the actual
arguments of the calling function. i.e., the called function is actually uses the original data with a different
name.

306
User Defined Functions

Program 13.9: To illustrate pass by value


eÁw
#include<iostream.h>
#include<conio.h>

void main()
{
void swap(int&, int&);
int a, b;

clrscr();
cout<<”Enter two numbers: “;
cin>>a>>b;

cout<<”Before calling the function: a = “<<a<<” and b = “<<b<<endl ;


swap(a, b);
cout<<”After calling the function: a = “<<a<<” and b = “<<b<<endl ;
getch();
}
void swap(int&x, int&y)
{
int temp;

temp = x;
x = y;
y = temp;
}
Sample run: Enter two numbers: 10 20
Before calling the function: a = 10 and b = 20
After calling the function: a = 20 and b = 10

307
User Defined Functions

13.12 Passing arrays to functions


Usually, constants and arguments are passed to the function as arguments. But, it is not possible to
pass an array to a function as an argument. Since, an array is a block of memory containing the collection
of elements and all the elements are stored in contiguous memory locations. The name of the array is the
address of the first element.
To pass an array to a function, we just pass the name of the array to the function. i.e., we are referring
the address of the first element of the array. Using this address, the function can access all the elements of
the array.
When the array address is passed to the function by giving the name of the array, the function assign
the same address to another name declared as formal argument in the called function. Any change made
to the array in the called function is also reflected in the array of the calling function.
C++ compiler converts the array declaration of the formal argument of the function into the array
pointer. The size of the array is not necessary.

308
User Defined Functions

Program 13.12: To concatenate two strings


eÁw
#include<iostream.h>
#include<conio.h>
#include<string.h>

void concatenate(char st[], char str[]);


void main()
{
char s1[50], s2[50];

clrscr();
cout<<”Enter the first string: “;
cin.getline(s1,50);

cout<<”Enter the second string: “;


cin.getline(s2,50);

concatenate(s1,s2);
cout<<”Concatenated string: “<<s1<<endl;
getch();
}
void concatenate(char st[], char str[])
{
int l1 = strlen(st);
int l2 = strlen(str);

for(int i = 0; i< l2; i++)


st[l1+i] = str[i];
st[l1+l2 ]=’\0’;
}

Sample run: Enter the first string: Computer


Enter the second string: Science
Concatenated string: ComputerScience

309
User Defined Functions

Program 13.13: To sort the elements by bubble sort method

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>

void read(int *);


void sort(int *);
void print(int *);
int n;
void main()
{
int a[50];

clrscr();
cout<<”How many elements? “;
cin>>n;
read(a);
sort(a);
print(a);
getch();
}
void read(int b[])
{
cout<<”Enter the elements: “;
for(int i = 0; i < n; i++)
cin>>b[i];
}
void print(int c[])
{
cout<<”Sorted elements: “;
for(int i = 0; i <n; i++)
cout<<setw(4)<<c[i];
}

310
User Defined Functions

void sort(int d[])


eÁw{
for(int i = 1; i < n; i++)
for(int j = 0; j < n-i; j++)
if( d[j] > d[j+1] )
{
int temp = d[j];
d[j] = d[j+1];
d[j+1] = temp;
}
}

Sample run: How many elements? 5


Enter the elements: 50 30 40 20 10
Sorted elements: 10 20 30 40 50

Passing structures to functions


We can pass structures to functions as we pass other arguments. Structures are passed to functions
in pass-by-value method. i.e., the function works with copy of the structures. The function can also return
a structure after processing it. Whenever we pass the address of the structure to the function, we should
include the address-of (& ) operator.

311
User Defined Functions

Program 13.4: To add two time periods

#include<iostream.h>
#include<conio.h>

struct time
{
int h;
int m;
};

time sum(time t1, time t2);


void show(time t);

void main()
{
time t3;
time t1 = {2, 25};
time t2 = {3, 50};

clrscr();
cout<<”First time: “;
show(t1);
cout<<”Second time: “;
show(t2);
t3 = sum(t1, t2);
cout<<”Sum of two times: “;
show(t3);
getch();
}
time sum(time t1, time t2)
{
time total;
total.h = (t1.h + t2.h) + (t1.m + t2.m)/60;
total.m = (t1.m + t2.m)%60;
return(total);
}

312
User Defined Functions

void show(time t)
{
eÁw
cout<<t.h<<” Hours and “<<t.m<<” minutes”<<endl;
}

Sample run: First time: 2 Hours and 25 minutes


Second time: 3 Hours and 50 minutes
Sum of two times: 6 Hours 15 minutes

313
User Defined Functions

REVIEW QUESTIONS
One marks questions:
1. What is a user-defined function?
2. Explain any one reason why functions are used?
3. Give one reason for using a function?
4. What is a calling function?
5. What is a called function?
6. How is a function invoked?
7. What type of value the main() functions return, by default?
8. Why do we use return statement.
9. What does the return-type-specifier identify?
10. Can a function return an array to another function?
11. What does the keyword void represent?
12. What is the significance of the keyword void in functions?
13. What is the data type of the value return by the return statement?
14. Why are arguments used in functions?
15. What are actual arguments?
16. What are formal arguments?
17. What are global variables?
18. What are local variables?
19. Give the syntax of function call.
20. Give the syntax of return statement.
21. What is the use of return statement in a function?
22. How many expressions can be included in a return statement?
23. What is a function prototype?
24. Give the syntax of function prototype/
25. When do we not use function prototype in a function?
26. What is scope of a variable?
27. What is the name of the operator :: ?
28. What is the use of scope resolution operator?
29. Is it necessary to pass all the arguments to call a function?
30. Give an advantage of default arguments?
31. Can we modify the constant argument passed to the function?
32. When do we pass constant arguments to a function?
33. How do we pass an array to a function?
34. Why is not possible to pass an array to a function?

314
User Defined Functions

35. Name any one method of calling a function.


36. What
eÁw is pass by value?
37. What is pass by reference?
38. How do we pass a structure to a function?

Twp marks questions:


1. Distinguish between library function and user-defined function/
2. What is the need for us to use functions?
3. Give the structure of a function.
4. Why are arguments or parameters used in a function?
5. How do we call a function? Give the syntax of function call statement.
6. Distinguish between actual parameter and formal parameter.
7. Distinguish between local variable and global variable.
8. What is a function prototype? When is a function prototype necessary?
9. Name the different categories of functions.
10. What is scope of a variable?
11. What are the uses of default arguments?
12. Name the methods of calling a function.
13. Give the syntax of functions with no arguments and no return values.
14. Give the syntax of functions with arguments and no return values.
15. Give the syntax of functions with no arguments and with return values.
16. Give the syntax of functions with no arguments and no return values.
17. Give the syntax of functions with arguments and with return values.
18. Briefly explain pass by value
19. Briefly explain pass by reference.
20. Explain in brief the method of passing default arguments.
21. Explain in brief the method of passing constant arguments.
22. Explain in brief the method of passing arrays to a function.
23. Explain in brief the method of passing structures to a function.

Three marks questions:


1. What are the advantages of functions?
2. Explain the structure of function with an example.
3. Write a C++ program to find the greatest of three numbers using function.
4. Write a C++ program to find the cube of a number using function.
5. Illustrate the use of scope of variables with an example.
6. Explain the working of function with no arguments and no return values.
7. Explain the working of function with arguments and no return values.
8. Explain the working of function with no arguments and with return values.

315
User Defined Functions

9. Explain the working of function with arguments and with return values.
10. Explain the method of passing default arguments to a function.
11. Explain the method of passing constant arguments to a function.
12. Explain pass by value method of calling a function.
13. Explain pass by reference method of calling a function
14. Explain the method of passing an array to a function.
15. Explain the method of passing structure to a function.

Five mrks questions:


1. Explain the structure of the function with an illustrative program.
2. Write a C++ program to find the factorial of a number.
3. Write a C++ program to find the GCD of a number.
4. Write a C++ program to find the LCM of a number.
5. Explain the scope of a variable with an example.
6. Explain the working of function with no arguments and no return values with an example.
7. Explain the working of function with no arguments and no return values with an example.
8. Explain the working of function with arguments and no return values with an example.
9. Explain the working of function with no arguments and with return values with an example.
10. Explain the working of function with arguments and with return values with an example.
11. Explain the method of passing default arguments to a function with an example.
12. Explain the method of passing constant arguments to a function with an example.
13. Explain pass by value method of calling a function with an example.
14. Explain pass by reference method of calling a function with an example.
15. Explain the method of passing an array to a function with an example.
16. Explain the method of passing a structure to a function with an example.

316
eÁw

CHAPTER 14
Structures

OBJECTIVES
To Understand the concept of structures
Their need
Types of structures

317
318
Structures

14.1 Introduction
WeeÁw
have seen variables of simple data types, such as float, char, and int. Variables of such types
represent one item of information: a height, an amount, a count, and so on. But just as groceries are
organized into bags, employees into departments and words into sentences, it is often convenient to
organize simple variables into more complex entities. The C++ construction called the structure is one
way to do this.

A structure is a collection of simple variables. The variables in a structure can be of same or different
types: Some can be int, some can be float and so on. The data items in a structure are called the
members of the structure.

For C++ programmers, structures are one of the two important building blocks in the understanding
of objects and classes. The syntax of a structure is almost identical to that of a class. A structure is a
collection of data, while a class is a collection of both data and functions. So by learning about structures,
we will be able to understand classes and objects.

14.2 Defining a structure


The process of defining a structure is equivalent to defining your own datatype. The process of
defining a structure includes giving the structure a name called the tag and telling the compiler the name
and the datatype of each piece of data you want to be included in the structure.

Syntax

struct structure-name
{
datatype member-name-1;
datatype member-name-2;
……………
datatype member-name-n;
};

The keyword struct introduces the structure definition. Next comes the structure name or tag,
which is part. The declarations of the structure members are enclosed in braces. The list of all structure
members is called template. A semicolon follows the closing brace, terminating the entire structure. Note
that this use of the semicolon for structures is unlike the usage for a block of code (called compound
statement). As we’ve seen, blocks of code, which are used in loops, decisions and functions are also
delimited by braces. However, they don’t use a semicolon following the final brace.
The structure definition serves only as a blueprint for the creation of variables. It does not itself
create any structure variables; that is, it does not set aside any space in memory or even name any
variables. This is unlike the definition of a simple variable, which does set aside memory. A structure
definition is merely a specification for how structure variables will look when they are defined.

319
Structures

Example 14.1: A structure definition to hold employee information.


struct employee
{
int idno;
char name[15];
char designation[10];
float salary;
};

This structure is named employee. It contains four members: an integer quantity named idno, a
character array to hold 15 characters for a name, another character array to hold 10 characters for
designation and float quantity named salary. The structure requires an area in memory, which is 31 bytes
long. The figure given below shows the allocation of memory for the individual elements.

idno name designation float


2 bytes 15 bytes 10 bytes 4 bytes

31 bytes
Figure 14.1 Memory allocations for a structure

14.3 Declaring a structure or defining a structure variable


A structure can be declared (or a structure variable can be defined) as we define a basic built-in
datatype.

The general form is


structure-name variable;
Example 14.2 student oldstudent, newstudent;

oldstudent and newstudent are the two structure variables declared as we declare built-in
datatypes. This similarity is not accidental. One of the aims of C++ is to make the syntax and the operation
of user-defined data types as similar as possible to that of built-in data types.

Example 14.3 employee emp1, emp2;

emp1 and emp2 are the two structure variables declared as belong to the user-defined data type
employee.
We can combine the definition of the structure and definition of structure variables.

320
Structures

Example 14.4 struct employee


eÁw
{
int idno;
char name[15];
char designation[10];
float salary;
}emp1, emp2;

manager

idno name designation salary

assistant

idno name designation salary

Figure14.2 Memory allocation of a structure

NOTE:
 The definition of a structure does not allocate memory space. The definition just defines the
blueprint for the creation of variables.
 A semicolon should follow the last brackets of the structure.
 The definition of the structure should come either before the main function or before any other
variables are declared.
 The declaration of the structure always comes after the definition. The declaration of the
structure creates space to store the values for the variables.

14.4 Accessing the elements of a structure


The member of a structure can be accessed using dot operator

After the structure variables are defined, we should know how the member of a structure variable is
accessed. A member of a structure is always part of a structure and it is not possible to refer the member
directly.
The member of a structure can be accessed using dot operator. The syntax of dot operator is
as follows.

structure-variable-name.member-name

The structure member is written in three parts: the name of the structure variable (part1); the dot
operator, which consists of a period(.); and the member name (part3). The real name of the dot operator
is member access operator.
321
Structures

Example 14.5 To access the name of the member emp1 of the tag employee, we write
emp1.name
Example 14.6 To access the salary of the member emp2 of the tag employee, we write
emp2.salary

Program 14.1 To input and display the information of a student

#include<iostream.h>
#include<iomanip.h>
#include<string.h>
void main( )
{
struct student
{
int regno;
char name[15];
char combination[4];
float perc;
}st;

cout<<"Enter the name of the student: ";


cin.getline(st.name, 15);
cout<<"Enter the combination of the student: ";
cin.getline(st.combination, 6);
cout<<"Enter the register number of the student: ";
cin>>st.regno;
cout<<"Enter the percentage of the student: ";
cin>>st.perc;
cout<<endl<<"Register No: "<<st.regno<<endl;
cout<<"Name: "<<st.name<<endl;
cout<<"Combination: "<<st.combination<<endl;
cout<<"Percentage: "<<st.perc<<endl;
getch( );
}

Sample run: Enter the name of the student: NalinaM A


Enter the combination of the student: CEBA
Enter the register number of the student: 1234
Enter the percentage of the student: 90.05

Register No: 1234


Name: Nalina M A
Combination: CEBA
Percentage: 90.05

322
Structures

 The first component of an expression involving the dot operator is the name of the
specific
eÁw structure variable(part1), and not the name of the structure definition;
 Structure members are treated just like other variables.

Example 14.7 Consider the assignments.


std.regno = 12345;
std.name[] = “Empress College”;
std.perc = 79.54;

14.5 Initializing a structure


Like any other data type, it is also possible to initialize the structure members of a structure
variable. Structures members are initialized when they are declared.

Example 14.8: A program may contain the following initialization of the structure.
employee emp1 = {
1234,
“Lakshmi”,
“Manager”,
10500.00
};
This initialization initializes idno field to 1234, the name field to “Lakshmi”, the designation field to
“Manager” and the salary field to 10500.00.

Example 14.9: student std1 = {


12345,
“PremaKumari”,
“SCBA”,
98.5
};
This initialization initializes regno field to 12345, the name field to “PremaKumari”, the combination
field to “SCBA” and the perc field to 98.5.
A structure variable can be assigned to another structure variable.

Example 14.10: std2 = std1;


Here, std1 and std2 are the structure variables of the structure std.

The value of each member of std1 is assigned to the corresponding member of std2. Since a large
structure can have dozens of members, such an assignment statement can require the computer to do a
considerable amount of work. Note that one structure variable can be assigned to another only when they
are of the same structure type. If you try to assign a variable of one structure type to a variable of another
type, the compiler will complain.
323
Structures

Program 14.2 To find the sum of two distances

#include<iostream.h>
#include<iomanip.h>
#include<string.h>
struct distance
{
int feet;
float inches;
};
void main( )
{
distance d1 = { 5, 6.75 };
distance d2, d3;

cout<<”Enter the second distance in feet and inches: ”;


cin>>d2.feet>>d2.inches;

d3.inches = d1.inches + d2.inches;


d3.feet = 0.0;
if(d3.inches >= 12.0)
{
d3.inches -= 12.0;
d3.feet++;
}
d3.feet += d1.feet + d2.feet;
cout<< d1.feet << “\’-” << d1.inches << “\” + “;
cout<< d2.feet << “\’-” << d2.inches << “\” = “;
cout<< d3.feet << “\’-” << d3.inches << “\”\n”;
getch( );
}

Sample run: Enter the second distance in feet and inches: 10 6.85
5' - 6.75" + 10' - 6.85" = 16' - 1.6"

Notice that we can’t add the two distances with a program statement like d3 = d1 + d2;
Why not? Because, there is no routine built into C++ that knows how to add variables of type distance.
The + operator works with built-in types like float, but not with types we define ourselves, like distance.
However, one of the benefits of using classes, as we’ll see in next volume, in the chapter “Operator
Overloading”. Now it is out of scope of this text book.

324
Structures

14.6 Nested structures


A structure
eÁw can be defined as a member of another structure. Such structure where one structure is
embedded within another structure is called as a nested structure.
During the declaration of nested structures, the definition of the embedded structure must appear
before the definition of outer structure.

Example 14.11. Consider the definition of the following structures.


struct distance
{
int feet;
float inches;
};
struct room
{
distance length;
distance breadth;
};

The structure room contains another structure distance as one of its members. Whenever
nested structures are used, the definition of the internal structure should precede the definition of the outer
structure. In the above example, the definition of the structure distance precedes the definition of the
structure room.

A structure can be defined as a member of another structure. Such structure where one
structure is embedded within another structure is called as a nested structure.

Example 14.12 Consider the definition of structure student.


struct date
{
int dayno;
char month[10];
int year;
};
struct student
{
int regno;
date doa, dob;
marks int;
}std;
To access the field regno of the structure std, we write std.regno. To access the day
number of the date of admission of the structure std, we write std.doa.dayno. To access the year of
date of birth of the structure std, we write std.dob.year.
325
Structures

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<string.h>
struct date
{
int dayno;
int month;
int year;
};
void main( )
{
struct student
{
int regno;
char name[15];
datedoa;
}s;

clrscr( );
cout<<"Enter the name of the student: ";
cin.getline(s.name,15);
cout<<"Enter the register number of the student: ";
cin>>s.regno;
cout<<"Enter the date of admission of the student: ";
cin>>s.doa.dayno>>s.doa.month>>s.doa.year;
cout<<endl<<"Student information:"<<endl;
cout<<"Register No: "<<s.regno<<endl;
cout<<"Name: ";
cout<<s.name<<endl;
cout<<"Date of admission: "<<s.doa.dayno<<"-"
<<s.doa.month<<"-"<<s.doa.year<<endl;
getch( );
}

326
Structures

Sample run:
eÁwEnter the name of the student: Namith Jain
Enter the register number of the student: 1234
Enter the date of admission of the student: 20 5 2005

Student information:
Register No: 1234
Name: Namith Jain
Date of admission: 20-5-2005

Program 14.4 To find the area of the room


#include <iostream>
#include<iomanip.h>
#include<string.h>
#include<conio.h>
struct distance
{
int feet;
float inches;
};
struct room
{
distance length;
distance width;
};
void main()
{
room dining;
clrscr();
dining.length.feet = 15;
dining.length.inches = 8.5;
dining.width.feet = 10;
dining.width.inches = 5.3;
//convert length and width into feet
float l = dining.length.feet + dining.length.inches/12;
float w = dining.width.feet + dining.width.inches/12;
//find area and display it
cout<< “Area of Dining room is “ << l*w<< “ square feet\n” ;
getch( );
}

Sample run: Area of Dining room is 164.021 square feet

327
Structures

14.7 Array of structures


A single variable that represents a structure creates memory space to store one set of information. If
we want to create memory space for more instances then we may have to increase the number of
variables or use the facility called arrays. For example, let us consider that there are 100 students studying
in a college. We have defined the structure so that it could maintain information about students of the
college. If we have to store data of 100 students we need to use arrays rather than a single variable. When
create an array of a structure, we are creating an array of the entire template. This can be done as follows.

Example 14.13 struct student


{
int regno;
char name[15];
char combination;
float fees;
}s[100];

In the declaration, s is an array of 100 elements. Each element of the array s is a separate structure
of type student.
The expression s[0].name will access the name of the first student, while
s[99].fees access the fees paid by the last student.

idno name designation salary


s[0]

s[1]

………

s[99]

Figure 14.3 Memory allocations for an array of structures

An array of structures can be assigned initial values just like any other array. Remember that each
element is a structure that must be assigned a corresponding set of initial values. The process of
initialization is illustrated below.

An array of structures is an array in which each element of the array is a structure. Thus it is a collection
of structures put together as an array.

328
Structures

Example 14.14 struct info


eÁw {
int regno;
char name[15];
float perc;
};
info s[] = { 1, “Lavanya”, 5500.00,
2, “Manasa”, 6250.00,
3, “Sajjan”, 6000.00,
4, “Sahana”, 5900.00
};
In this example s is an array of structures whose size is not specified. The initial values will define
the size of the array and amount of memory required for storing the array.

329
Structures

Program 14.5 To illustrate the use of array of structures

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<string.h>
struct info
{
int regno;
char name[15];
float perc;
};
void main()
{
info s[50];
int i, n, l;
clrscr( );
cout<<"Enter the number of the students: ";
cin>>n;
cout<<"Enter the Reg. No., perc and name of the students: "<<endl;
for(i = 0; i < n; i++)
{
cin>>s[i].regno;
cin>>s[i].perc;
cin.getline(s[i].name,15);
}
cout<<endl<<"Student information:"<<endl;
cout<<"Reg. No.\tName\tPerc"<<endl;
for(i = 0; i < n; i++)
{
cout<<s[i].regno<<"\t";
cout<<s[i].name<<"\t";
cout<<s[i].perc<<endl;
}
getch( );
}

330
Structures

Sample run:
Enter
eÁw the number of the students: 2
Enter the Reg. No., perc and name of the studenst:
1234 75.5Harshith H R
1235 81.75Jyothi H R

Student information:
Reg. No. Name Perc
1234 Harshith H R 75.5
1235 Jyothi H R 81.75

331
Structures

Review questions
One mark questions:
1. Define a structure.
2. Give a difference between an array and a structure.
3. Does the definition of a structure create memory space?
4. Create the structure definition that contains the information of a student.
5. Why is the keyword struct used?
6. How are the elements of a structure accessed?
7. What is the use of dot operator?
8. How do we initialize a structure?
9. What distinguishes an array from a structure?
10. Define an array of structures.
11. Why is an array of structures used?
12. Can an structure has the elements of same data type?

Two mrks questions:


1. When do we use structures?
2. How do define a structure?
3. How do we declare a structure? Give an example.
4. Differentiate between structure definition and structure declaration.
5. Declare a structure that contains the data of a student.
6. Declare a structure that contains the data of all the employees.
7. How are the elements of a structure accessed? Give an example.
8. How do we initialize a structure? Give an example.
9. What are nested structures? Give an example.

Three marks questions:


1. Explain the process of creation of a structure within an example.
2. Explain the nesting of structures with an example.
3. Explain the array of structures with an example.

Five marks questions:


1. Write a C++ program to that contains the data of a point. Input the data of two points and find the
distance between two points.
2. Write a C++ program to that contains the data of a complex number. Input the data of complex
numbers and perform the required operation depend on the operator entered.
3. Write a C++ program to that contains the data of an employee. Input the data of 10 employees
and arrange the data in the order of names.

332
Structures

4. Write a C++ program to that contains the data of a customer. Input 10 customers and output the
data
eÁw
of the required customer.
5. Write a C++ program to for matching the names of countries with their corresponding capitals
using structures.
6. Explain the use of arrays within a structure with a programming example.
7. Write a C++ program that creates a structure for a product, which includes product no., product
name and cost. Input and output the data for 10 products.
8. The local police station wants to store the data of all the residents of the area. Identify the structure
declaration to store the data and perform the input and output operation.

333
334
eÁw

CHAPTER 15
Word Processing

OBJECTIVES
To Understand the features
Usage
Importance of word processing

335
336
Word Processing

15 Word Processing Application:


The
eÁwword processor application is general purpose application software, used in creating,
editing, storing, letters, documents, articles, books, reports etc., mainly using the text, numbers, and
special symbol, pictures and clip arts etc., with different fonts, size, style, colour, alignments, tables,
mail merge operations and many more operations with much ease, faster ,printing, with greater accuracy
and colour ful graphical presentations.
Some of the basic features of any Graphics User Interface(GUI) application software will be
WYSIWYG(WHAT YOU SEE IS WHAT YOU GET) which consists of the frame, title bar, File menu
bar, tool bar, Vertical scroll bar, horizontal scroll bar, ruler, desktop(layout) to enter the data .
Frame Title bar File menu bar Tool bar Ruler Horizontal bar Vertical Bar

BASIC WINDOWS FEATURES

Frame : using the frame the resize of the windows are possible.
Title Bar : gives the details of the file saved and name of the application software. By placing the
mouse pointer on the title bar the screen can moved, minimized, maximized, closed.
Menu Bar : Standard operations are to be carried using the Menu bar (activated with Alt+). There
are sub menu and gives the details of the file operations.
Tool bar :Some of the easy method of carrying out the activity by seeing the icons (small pictures)
seen on the tool bar .
Vertical scroll bar : The large text / document which cannot be view in one screen therefore to view
part of the page by page vertical scroll bar is used.
Horizontal scroll bar : The left to right view of the document can be viewed by horizontal
scroll bar.

337
Word Processor

Ruler : The ruler gives the status of the page with the numeric values with the table and right and left
and indents are viewed.
The GUI windows are of two types
First one is the fixed windows (standard menu and multiple windows are operated ) where the
commands can be carried out with the help of keyboard or mouse.
the second type of windows are called popup windows usually used to for only one task at a
given time.
Fixed windows Popup window

Menu is pull down menu from the file The popup window for printing
menu

15.1.1 Creating a document


Creating a documents are used from the file menu of the word processor. The paper size is set from
the default page setup and margins of the page is set with the File->New (Alt+F->N New) .The data or
information is entered and saved. Or
The Open an existing file from the storage medium. The file will contain the file extension .doc
or.docx

338
Word Processor

15.1.2 Parts of the Menu/windows


eÁw
File Menu :
New(Ctrl +N) start a new word processor file. Recent documents viewed up to eight files
open at once.

To create a new document click on the file->new and black document will be seen along with new
blog post (for online office link with account ) and click on create. The new document will be ready to
accept the data/matter to type.

Open(Ctrl +O)

The open command is used to open the existing file (which are already created and present in the
current folder or any other drive.

339
Word Processing

The most recent documents which was used/opened last few will be displayed with details.
Lets you open an existing document. It opens to the drive and folder set as the default in the shortcut.
To change to a different drive or folder, click on the triangle next to the box labeled Look In: . The button
lets you create a new folder... very handy! The next two buttons show the contents either as a simple list
or with details (file size, modification date, etc). The button moves you up one level in the folder-tree...
also very handy. The File of Type field, near the bottom is very useful, if you want to use Works to open).
If you can’t find your file, choose All Files (*.*).
Close: the file must be saved before closing. Closes a single document, but not the program.
Save/Save As(Ctrl +U). The first time you save, these two menus give you the same thing... a
dialogue box almost identical to the Open one... after that, clicking on Save no longer gives you a dialogue
box— it just saves, with the same options already chosen. Save As, however, always shows the dialogue
box... handy if you want to save under a new name or in a different location— a quick and make another
copy of a file, or to create a backup version.
Save : Be aware of the File of Type option... it lets you save in Word Processor format to work on
your document on another computer (at home, for instance), if you don’t have Works available. File type
text is a lowest common denominator— every computer can read it, but font and formatting
information is lost.RTF (Rich Text Format) is almost as universal, and includes fonts, graphics, etc. — File
Names can be up to 255 characters long in Works 4, and can includes spaces— but not a few characters
such as question marks or colons that have special meanings to the operating system. If you are using
Works 2 or 3, you are limited to 8-character file names. In either case, do not end your file names with a
period, or add a customized three letter extension— either will confuse Windows when you try to open
your file again. The Template button lets you save a document that you will often re-use, with changes...
customized letterhead, report card form, etc. When you save a template, you open it by using the File/
New/TaskWizards item, and scroll down the list to User Defined Templates:

340
Word Processing

Save command can be carried out using ctrl S, or Alt F S or click on floppy icon on the title/ toolbar.
Save
eÁwcommand is used to save with the updated data to the new or existing document file.

Save as command will create a copy of the file with a different name.
Note : The beginners commit mistake will saving the existing file name, over writing with the blank
name. Then the existing file will be over written with the blank file. Care must be taken while using save
and save as command.
Page Setup :The page size is the first step to be checked along with the margin, and lets you set the
margins (note— in the units you set in the Options). The Source, Size, and Orientation lets you set the
paper size and whether you want your document to be vertical (portrait) or horizontal (landscape).You
may need to set your printer to match these settings.
Print Preview shows you a miniature view of how your document will look when it’s printed. You’ll
save lots of paper if you routinely use this before printing!

Select the paper Size Select the margin

Paper size : letter,A4,A3,a5,a6 custom size The binding/ header/footer space must be
thought during this stage.

Print(Ctrl +P) lets you control pages printed, number of copies, target printer, etc. If you have
multiple printers, choose the target printer using the drop-down triangle next to the Printers box. (You set
the default) printer with the Start Menu’s Settings/Printers item—right-click on the desired printer, and
choose Set as Default. To print just page 3, you need to set it to print from Page 3 to Page 3.
The default printer will be setup as one, if more than one printer is used the printer must be selected
under the printer name so that the Operating system will transfer the printing information to that printer.

341
Word Processing

Selected paragraph Printing document can be sent to OneNote

Only selected paragraph will be printed Printing format can be seen.

While printing by default the current page will be printed.


One can give the page number from to, to printer.
Only one paragraph to be printed, can be highlighted and in the printer popup window the selection
radio button is selected, so that only that paragraph is printed.

Printing All the pages Printing based on choice

All the pages from first to last page of the Printing from first to fifteen page.
document.

Note : The some of the


Exit: Works(Alt +F4) closes the program. You will be prompted to save any unsaved work.
On the bottom of the File menu, you’ll see the last four documents opened... this is handy way to
quickly get back to your most recent work.

342
Word Processing

eÁw

Edit Menu
These items are very useful. Be sure to memorize the keyboard shortcuts!
Edit Menu items involve working with selections— telling the computer that you want to do
something to part of your document. To select some text, you can do one of the following techniques:
Click at the beginning of the desired selection, hold the left mouse button down, and drag over what you
want to select. It can often be hard to be precise this way. Alternatively: Click at the beginning, hold the
shift key down, and click at the end of the desired selection. Or: Click at the beginning, hold the shift-key
while using some combination of the arrow keys (left, right, up, or down), Page Up, Page Down, Home,
End, Ctrl+Home, or Ctrl+End to extend the selection. Selection is also useful with the Format menu
items. Here are the contents of the Edit menu:
Undo Editing(Ctrl +Z) can be a lifesaver— if you try it immediately when you make a mistake. If it
(and any menu) is greyed-out it is unavailable at this time.
Cut(Ctrl +X) and Copy (Ctrl +C) are only available if something is selected. If so, they both copy
the selection into the Clipboard for use later. (The Clipboard is a metaphor— not a real, physical part of
the computer. It means the selected item is being stored in memory. The Clipboard only holds one thing at
a time... when you Cut/Copy something else, the previous contents disappear). When you Cuta selection,
it vanishes from the page... when you Copy it, it remains on the page.
Paste(Ctrl + V) places whatever is in the Clipboard where ever the cursor is. Note that when you
paste, the selection is not removed from the Clipboard... you can paste the same item multiple times.
Paste Special is a techie option that you’ll never use. Trust me.
Clear(Del) erases a selection, without sending it to the Clipboard.
Select All(Ctrl +A) selects the whole document... useful for making global changes like changing the
font and size, or double-spacing everything.
Find(Ctrl + F) lets you search a document for desired text... similar but probably more useful is the

343
Word Processing

next item:
Replace(Ctrl +U — they ran out of letters? Why not Ctrl + R?)lets you find text and automatically
(or manually) replace it with something different: cat with dog, for example.
The Find Next option moves to the next instance of the Find text, giving you the choice to replace it
or not... Replace All automatically replaces all instances, and reports on the number replaced.
Note that if some text is selected, this only searches in the selectionf irst reason why this might not
work as expected. The two buttons in the centre, let you add a Tab and a new Paragraph to the desired
text to search or replace. Note the two options: Find Whole Words Only, if selected, would replace ‘cat’
but not ‘Dog’... if that was not selected, Dog, probably not what you intended. would become Match
Case, if selected, would only replace the word if capitalization is exactly what you typed in the Find What
box... i.e.‘Cat’ would not be replaced.
Goto(Ctrl+G) is only useful if you’ve created Bookmarks if so, it lets you jump to a bookmark.
Useful if the created document is very long documents... like chapters in a book.
Easy Text lets you save and insert something you’re often going to use... your return address, for
example. To create Easy Text, high light desired text, and choose this menu item. Choose New, and type
a name for it. (You apply Easy Text from the Insert menu)
Bookmark lets one to add or delete bookmarks, to use with the Go to menu.
Links and Object are two other menus you’ll never use.

344
Word Processing

View Menu
A bunch
eÁw of options about what you see on screen... note that these don’t change the actual contents—
just how they’ll be showed to you.
Normal shows text and graphics, but not margins, headers, or footers... it you find that can’t see all
the way across the page, try changing to this view. It’s also faster on an older computer.
Page Layout shows more like what your page will look like when printed... You have to choose one
or the other of those views.
Toolbar... click on this if the toolbar has disappeared!
Ruler to display a ruler on the top, in the units set in the Options. All Characters shows the hidden
characters— spaces, Enter, tabs, paragraph, etc
Header and Footer jump you to the top or bottom of the page (respectively). Headers and Footers
are for text that you want to appear on every page— titles, page numbers, date, etc. In normal view, these
are shown as a single line labeled H or F at the beginning of the document. In Page Layout view, these are
shown as approx 1 cm. wide areas at the top (or bottom) of every page. Don’t try to type the main body
of your text in these areas!
Header Footer

Header to be printed in the margin space Footer to be printed in the margin space
Can have title, page number, alignment. Can have title, page number, alignment.

The tab key moves you from the left, to the center, to the right of the Header/Footer area, so you can
have three items in each. One can set the font/size separately from the main text. You can use the Insert
menu items to insert (for example), page numbers, or date into the Header or Footer. So to have a Footer
that reads “Page 23” (or whatever the correct number is), go to the Footer and type the word Page
followed by a space, then click on the Insert menu, and choose Page Number. All Footer will read ‘Page
*page*’, but when you print (or print preview), the correct page number will appear.
Headers/Footers on all pages except the first (for a title page, for example), go to File/Page Setup/
Other Options.
Get in the habit of using Headers and Footers, they will make your work look much more professional!

345
Word Processing

Foot notes shows you the footnotes that you created with the Insert/Foot note menu item... these
are at the bottom of the page unless you chose to put them at the end, using File/Page Setup/Other
Options.
Zoom changes the size your page is displayed at... not the size it will print at. Useful if you need to
get up close, or if you can’t see a full page-width on screen at once.

Insert Menu
These items add something special where the cursor is...

Page Break(Ctrl + Enter) starts a new page. Handy if you want to have each section start on its
own page, or to change the automatically pagination— In normal view, you’ll see a dotted line across the
page wherever you’ve inserted a page break— to remove one, click on the dotted line, and press Delete.
Page Number: see the discussion of Headers/Footers
Document Name inserts the saved filename, but shows up as ‘*filename*’until you print. (Should
you care?)
Date and Time gives you a choice of different formats (some showing only the date or the time,
some showing both). There’s an option that will automatically update it whenever you print the document.
Nice for Footers, or letterhead templates.
Special Characters doesn’t let you insert all those hard-to-type French characters (etc), and is
limited to specialized hyphens and spaces (i.e. if you want a phrase (‘Girl Guide’) to be treated as a single
word, and not broken over two lines, insert anon-breaking space between the two words.
Database Field is very useful for form letters, etc... we’ll look at this in detail in the Database

346
Word Processing

workshop. Stay tuned!


Easy
eÁwText lets you save and insert something you’re often going to use... your return address, for
example. Save Easy Text with the Edit menu item, inserting it from this menu item.
Foot note lets you insert a footnote (duh!) either at the bottom of a page or at the end of the
document (if chosen in Page Setup). It automatically adds the proper number as a superscript in the body
of your document... and if you add or delete a footnote, it automatically resets the number.
Tables are useful not only for traditional rows and columns of text or numbers, but also if you
want a more complex page layout than Works will normally give you— for instance, if you want
three columns of text in part of your document, make a table with three columns and one row, and
type away. (Remember— columns go up and down, rows go across!)You have the option to pick
one of a bunch of colour schemes for your table. Unfortunately, you can’t insert clipart into a table, making
it less useful for fancy layout. To change the number of rows/columns in a table, right-click on it, and make
your choice from the popup menu. If you want more power— for instance, to alphabetize data in a table,
use a spreadsheet, then copy and paste into your word processor. To remove a table, click after it and
press Backspace.
Inserting table with rows and columns Inserting rows or columns inside the table

Required number of rows and columns can The inserting, deleting, splitting, merging,
be inserted in the form of table, either by width or height, with alignment, direction
given insert table or selecting no of boxes vertical or horizontal with a columns/rows
rows and columns. soon and much more can be carried out.

Chart/Spreadsheet gives you the option to choose from an existing file or to create a new one...
you can also simply Copy/Paste from your spreadsheet.
Charts can be imported from the spreadsheets or to the value the graph can be generated.

347
Word Processing

Clipart opens the Clipart Gallery, showing thumbnails of a bunch of pictures, sorted by category.
When you pick one, it appears much larger and clearer than the thumbnail picture.
Note that there are lots of extra clipart available from www.microsoft.com/clipgallerylive (or clicking
on the globe icon on the Clip Gallery page).

Word Art lets you perform fancy effects on words/letters... upside down writing, words on an angle
or a curve, etc. You get a box to type the desired text, and a new toolbar with various special effects. Play
around with it!

Drawing(may not be installed) opens word processor Draw— a vector drawing program. These
sorts of graphics programs work differently from more common paint programs, and may be harder to get
used to— but a better for drawing with smooth lines... they don’t get blocky when printed or enlarged.
Object lets you insert any other type of saved work... a KidsPix picture, for instance (though you could
also Copy/Paste from the other program).

348
Word Processing

Format Menu
If you
eÁw choose items in this menu when text is selected, it only applies to the selection... a way to
change what you’ve written. If nothing is selected, the formatting applies to new text typed after the
cursor. Font and Style lets you change font, size, style, and colour of text.

Note that font size is measured in points: 72 to an inch. But because it measures from the lowest part
on a‘y’ to the highest part of the tallest capital letter, two fonts at the same point size may not look the same
height.
Super scripts like in math exponents: X2. Subscript is like in chemical equations: H20. If you click
the Set Default button, those settings will be used as default in future word processor documents... which
can be an unpleasant surprise

349
Word Processing

Paragraph lets set default alignment (more easily set from the Toolbar), and indentation. The Spac-
ing Line Spacing selection.page lets you set double/single spacing... to double space, type ‘2’in the
space, for example. Tabs lets you customize the tab stops. Leaders are characters that appear when you
press tab........... for example.
Borders and Shading let’s add a border around a selection, or change the colour of the paper
within a selection. Borders created on the Border page sometimes have a bad habit of extending over two
pages if your text moves...On the Shading tab, you can set a shading pattern for the background. Note
that the foreground and Page tab lets you create a border for an entire page... nice for title pages.
Bullets are small graphics used at the beginning of list items. You can choose from a wide variety of
characters.

Once you start making a bulleted list, you need to open this menu item and click the Remove button
to stop! (Or click on the Bullets toolbar icon).
Columns lets you create a document with multiple columns, optionally with a line dividing the col-
umns:

As it notes, the columns formats applies to the entire document. If you don’t want this you have a
couple of workaround: headline running across a multi-columned page, use the Header for this purpose

350
Word Processing

.multiple columns is only a small part of a document, . More different pages with different columns set-
ups, caneÁw
be saved each as a separate document. These are much more flexibility, use a page-layout
program like other word processors or other packages. Note that columns in Works (and Word) don’t
let you easily fill, for example, the top 1/2 of each column.... text runs down the first column, then starts to
run down the second. Easy Formats gives instant, pre-set formatting to a selection... Headings, etc. This
is called Styles in some other programs, and they can be customized. Very powerful, unfortunately, too
rarely used way to produce professional-looking, consistent documents. Very good if producing some-
thing like a class newspaper.
Text Wrap/Picture These only apply if you have inserted clipart or a graphic, and have selected the
picture. Absolute text wrap lets you position multiple lines of text around a picture, Inline text wrap lets
you only have a single line of text beside your graphic (lined up with the bottom).

The Picture item lets you set the exact size of your graphic— either in units or as a percentage of the
original. (Note that manually resize a graphic by selecting it, then stretching or shrinking by pulling on the
‘handles’ — the little squares in the corners. Holding shift down while you do this resizes it proportionally,
so don’t get skinny or far pictures).
Tools Menu
Address Book— only works if you’ve created one with the Database.

351
Word Processing

Spelling(F7) spell checks a selection, or the entire document. Of course, it doesn’t recognize
incorrect homonyms: “Eye right reel good, write?”

Note the Change All or Ignore All buttons... very handy since students often make the same
mistake many times.
You m ay want to use the Add button to add your name and address to the Custom dictionary, so
they don’t always come up as mistakes. Get students into the habit of using the spell check, but to use it
critically... in some cases, none of the suggestions will be correct, if the spelling is too far off. As well,
some students start pressing the Ignore button for all their mistakes... or even worse, press the Add

352
Word Processing

button, which adds their mistakes to the dictionary.


(This
eÁwcan be repaired with the Edit Custom Dictionary option. Or delete the C:\Program Files\Common
Files\word processor Shared\Proof\Custom.dic file and start all over again... this might be faster if you
have to redo a bunch of computers!)
New generation word processors, including later include an option to check spelling in real time-
indicating miss-spelled words with a colored underline. Right-click on the underlined word and a list of
alternatives will pop up, along with an option to ignore the spelling.
Thesaurus gives synonyms for the word where the cursor is. Double click on related words in the
Meanings box to get more meanings, with synonyms for each. Like paper thesauri (?), students often have
difficulty using this, as they tend to be unaware of the nuance of words.
Hyphenation only works for a selected word... showing where the word can be hyphenated.
Word Count counts the words in the entire document or a selection.

Lookup Reference is only available if another Microsoft product (Encarta, Bookshelf, etc) is in-
stalled... in which case, it will look up a selected word.
Envelopes/Labels/Form Letters open wizards that walk you through the steps for creating these
special projects.
Paginate Now makes sure that the program hasn’t gotten confused as you move text around.
Customize Toolbar lets you drag icons on or off the toolbar. I threw away the Printer icon, since too
often students clicked it multiple times, while waiting for their page to print— the File/Print option requires
more thought. Options: a bunch of ways to setup the program. Some things you might want to know:
Editing: Smart Quotes are those “curly” ones, rather than the ugly’ and “ characters that are prop-
erly used as abbreviations for feet and inches. When Over type is turned on, if your cursor is in the middle

353
Word Processing

of a word and you type, it replaces the next characters... if it’s off, it inserts letters in the middle of the
word. If this is happening the way you don’t want, you can press the Insert key to switch its behavior. This
is sometimes referred to as Insert/Overtype mode (and if you press Insert, you’ll see letters OVR appear
or disappear in the lower-right corner of the window). When Typing Replaces Select icons (the default),
if you select something, and type, it replaces the selection (duh)... this can cause problems— imagine
selecting the entire document, then pressing Enter... the invisible Enter character replaces Everything!!!(Click
on Undo I to get it back). General[x] Enable Drag and Drop Editing (the default), lets you move text by
selecting it, then pulling it with the mouse to a new location. If this causes problems, turn it off! Proofing
Tools: You may be able to choose between American and British spell checks... but no Canadian

Window Menu
When you have multiple programs open, you can switch between them using the Windows Taskbar,
at the bottom of the screen, or by pressing Alt+Tab, and repeatedly clicking Tab until the desired program’s
icon and name are selected.

Menu item lets you split a single document, so you can view two parts of it at once, with an indepen-
dent scroll bar on the right of each. You can do the same using the little teeny rectangle at the very top of
the vertical scroll bar— pull it down, to get two windows on the same document... when you’re done, pull
it back up to the top.

Toolbar
The Toolbar is across the top, under the Menu bar... if it isn’t visible, click on View/
Toolbar.
You can customize which commands are shown, using the Tools/Customize Toolbar
command, dragging icons from the dialogue box to the Toolbar (or vice versa). To see what command an
icon in the dialogue box represents, click on it. For instance, I added single-space and double-space
icons.

354
Word Processing

eÁw

When [x] Enable ToolTips is selected, letting your mouse point to a Toolbar icon will bring up a brief
description.

15.1.3 Copy & Move


COPY and Paste : Copying data of the documents/paragraph , the initial step will be to select the text
and go the edit menu copy command or press ctrl c, then the cursor is placed at the point where the text
need to be copied this is carried out by the edit menu paste command which makes the another copy of
the same data ctrl v is the command.
The Cut and move : Moving data of the documents/paragraph , the initial step will be to select the
text and go the edit menu cut command or press ctrl x, then the cursor is placed at the point where the text
need to be moved this is carried out by the edit menu paste command which makes the text available the
ctrl v is the command.
Copy Move

The paragraph is move to different


position on the screen

The same matter is copied once again at different The paragraph is only, ie there is no
position. copy of the same only the position is
changed.

355
Word Processing

15.1.4 Formatting features


Formatting a document. : Follow the steps below to create the style of document. By selecting the
type of document/paragraph g/text page from file – page setup with the margin alignment, typing your
title, click the center button and the Bold B button on the formatting toolbar. On the formatting tool
bar, select the font, size and color for your title, or, on the format menu, click font to make your changes.
Making your font selections, select the text (click hold and drag across the text) and then make your
changes while the text is selected. Press Enter twice to move the insertion point (your cursor) below the
title. Click the down-arrow in the style box, then select Normal to return to the default font style. To create
a bulleted or numbered list:press Enter to move a new line. Click either the Numbering button or the
Bullets button on the formatting tool bar. Begin typing your first item. Press enter to create the next bullet
or number. To create a subset bulleted list, press the Tab key at the beginning of the line that you want to
indent. To turn off Numbering or Bullets, press Enter twice or click the Numbering or Bullet button
again. Printing a document can be done by using file-print and OK. All the Menu commands can be
drawn by using Alt-F for file (respectively Underlined letter). Word Art to add emphasis to your docu-
ments, add word art to your titles or special comments. If the Drawing Toolbar is not displayed, on the
View menu, point to Toolbars, and then click Drawing. The Drawing Toolbar, click the Insert Word Art
button. The tool bar is usually located at the bottom of your screen. Select a Word Art style, then click
OK. Type your text, and then select the font style and size. Click ok. Size the WordArt as you would any
graphic. When you click the WordArt object, it will have eight handles around it, and the WordArt
Toolbar appears so that you can change its format. If you want to edit the text of the WordArt, double-
click the WordArt object. Save your document.

15.1.5 Spelling check


Checking your document for Spelling and Grammar Errors
Word automatically checks your spelling and grammar as you type, unless you turn the feature off.
Whenever you see a red, wavy line under a word, it means that the word in not in the program’s dictio-
nary. Whenever you see a green, wavy line under a word, phrase or sentence, it means that Word has a
grammar suggestion. This feature can support students in their editing and writing process.
Note: The red and green wavy lines will not be visible in the printed document.

To change or check spelling or grammar as you go: Right click a word or anywhere on the phrase
that has a red or green wavy line under it. If the word is spelled incorrectly ( or is not in the Microsoft
office dictionary), several suggestions may appear in the shortcut menu. If you want to accept one of the
suggestions, click it. If it is a grammatical error (or suggestion), the correct ways to write the sentence
appear in the shortcut menu. If you want to accept a suggestion, click the suggestion. To change or check

356
Word Processing

Spelling check
eÁw

Checking your document for Spelling and Grammar Errors


Red : for the spelling mistakes
Green : grammar suggestion

spelling or grammar when you are finished typing: On the Tools menu, click spelling and Grammar. The
top box shows the location of the potential spelling or grammatical error. The bottom box shows sugges-
tions to correct the perceived error. click ignore if you do not agree with the perceived error. If you want
to accept one of the suggestions, click the correct word, phrase or sentence, and then click change. Or
click change all if you want all of those same words to be corrected automatically throughout the whole
document. Save your document.

15.1.6 Print
Changing page settings from the default
You can make changes to the margin settings, paper size and layout, styles and so forth, using the
page setup dialog box. On the File menu, click page setup. On the Margins tab, make desired changes to
the margin settings. Click the Paper size tab to make changes to the paper size and or the orientation of the
paper. Click the paper source tab to make changes to the sources. Click the Layout tab to add a page
border, have different formatting for odd and even pages, change the vertical alignment of your document
or add numbers to each line of your document. Click Ok.

357
Word Processing

15.1.7 Creation of tables

Inserting a Table The easiest way to add a table is to use the Insert Table button on the Standard
toolbar. In your document, click where you want to create the table. Click the Insert Table button on the
Standard toolbar and drag your mouse to select the number of rows and columns you want to make.
Click when the correct number of rows and columns are selected. If you want more than four rows or five
columns (a 4*5 table), on the Table menu, point to Insert, then click Table. Enter the desired number of
rows and columns by entering the numbers directly or by clicking the up and down arrows. Formatting a
Table To change the format of your table, display the Tables and Borders toolbar: On the View
menu, point to Toolbars, and then click Tables and Borders. The Tables and Borders toolbar will appear.
Select the rows and columns you want to format. Use the buttons on the Tables and Borders toolbar to
change the line style and weight, border color and type, shading color, and so forth. Move your mouse
pointer over a button on the tables and Borders toolbar; wait for a moment, and a description of the
button’s function ( a Tool Tip appears). Save your document.
Creating a Graph from your Table To create a graph from your table, complete the following steps
:Click inside the table you just created.On the Table menu, point to Select, then click Table. On the Insert
menu, point to picture, then click Chart. To return to word and exit chart edition, click anywhere on the
word document outside of the chart. Creating a Graph without a Table If you want to create a graph,
but do not want to show the table in your document, complete the following steps: On the Insert menu,
point to picture, and then click Chart. A template for you to follow appears, as well as menu and toolbars
appropriate for creating a chart. In the data sheet, replace the text and numbers with your own. To delete
a column or row:A, Click the corresponding gray area either above or to the left of the column or row you
wish to delete. Once you click the gray area (identified as A,B,C, D or 1,2,3,4,) the whole column or row
will be selected. On the Edit menu, click Delete. To add new rows or columns for additional text and
numbers, simply enter the data in the empty rows at the bottom or the empty columns at the right.

358
Word Processing

15.1.8 Other basic operations


Adding
eÁw Headers and Footers :On the View menu. Click Header and footer. The Header and
footer toolbar appears. Press the Tab key twice to move to the right margin of the header area. Type your
name, your class name, or any other information that you want to appear on every page of this document
( e.g., Mr. PARAM /English 1) To change font style and size select the text and, on the Format menu,
click Font and make any desired changes. Click the Switch between Header and footer button. To enter
the name of the file so that it automatically appears on the bottom left of every page, click Insert Auto Text
then click Filename. To automatically insert the correct page number on the bottom center of every page,
press the Tab key to move to the center, then click Insert page number. To automatically insert the last
date this file was opened or changed, press the Tab key to move to the right margin, then click Insert Date.
Click close.
Creating an Organizational chart : Organizational charts are used to show relative importance
and /or relationships of objects or people to each other. A superior object is on a higher level than its
subordinates. Co-workers are on the same level as each other. Organizational charts can be used as a
tool for synthesizing, and supporting ideas. On the Insert menu, click object. click the Create New tab,
scroll down and click MS Organization chart 2.0.Click OK. The organization chart window will appear.
To add text to a shape, click once on the Type name here inside the desired box and type your own
text.To add a shape:Click the shape that you want a new shape to fall under or to be an assistant to.Click
the desired shape button on the organization chart toolbar, and then click one or more of the
following.Subordinate: to place the new shape below and connect it to the selected shape coworker: to
place the shape next to the selected shape and connect it to the same superior shape. Assistant: to
place the new shape below the selected shape with an elbow connector. If you want to add a
pre-set design scheme, click Boxes on the organization chart menu bar, and select a shadow or
border style from the submenu. To change the layout of the organization chart, click the style button and
select a desired layout. If you want your text to interact differently with your organization chart (wrap
around it, etc,) click on the rectangular border of the organization chart to select the full chart. On the
picture tool bar, click the Text wrapping button and choose your text-wrapping style. To move the
chart, move your cursor over the rectangular border of the organization chart. When the cursor turns into
four arrows, click, hold, and drag the object to the desired location.. To delete a chart, click on the
rectangular border on the outer edge of the organization chart, then press the Delete or Backspace key.
Save your file.
Creating Shapes, patterns, and Manipulative
Create a variety of shapes, patterns and manipulative that your students can view and use to help
them to understand complex or abstract ideas. Applications for use of these shapes can be flash-cards.
Algebra or fraction tiles, color, word, picture identification/matching. Shapes, patterns, and manipulative
can be added to any Office file.

359
Word Processing

Drawing objects : Locate the Drawing toolbar, if it is not visible, on the view menu, point to
Toolbars and click Drawing.

It usually is positioned at the bottom of your screen above the task bar. Click the Autoshapes button
and point to a category in the menu that appears. Click one of the shapes. Your cursor will turn into
crosshairs.Click or drag in your document where you want to insert the Autoshape.To move the object,
move the cursor to the edge of the text box until a four-sided arrow appears. Click hold and drag the
Autoshape to the desired location. If you want to add text to your Autoshape without having to add an
extra text box: Right-click on the Autoshape. Click Add Text. A blinking insertion point (cursor) will
appear in your Autoshape. Type the desired text. If you want your text to interact differently with your
Autoshape, change the text wrapping. Right-click the Auto shape.Click format Autoshape. Click the
Layout tab. Select the desired text-wrapping style. To be able to move the shape freely, without pushing
text or other objects around, choose In front of text. Click OK To rotate Autoshape: Click once on the
Autoshape to select it. Locate the green circle, called the rotate handle, somewhere on or very near your
Autoshape.Move your cursor over the total handle ( the green circle). your cursor will change to a
circular arrow. Click, hold, and drag your mouse and the Auto shape will rotate. Release the mouse
button when you reach the desired location. To create a shadow on your shape, or to make it three-
dimensional, click the Shadow button or the 3-D button on the Drawing tool bar and click to choose a
style in the dialog box that appears Save your file.

360
Word Processing

eÁw
Mathematical Equation
Creating Mathematical Equations In Word
Step 1: Open Microsoft Word.
Step 2: Click on the Insert menu and select Object...

Step 3: Select Microsoft Equation 3.0 from the list and click OK.
Step 4: The Equation Tool bar will appear on the screen. From this toolbar we can insert
equations at the cursor.
Step 5: For example, if you wanted to insert a division problem: Click on the Division icon and select
the long division option.
Step 6: A division sign will now appear at the cursor. Type the desired numbers into the boxes. Click
outside the equation box to stop editing the equation.

361
Mail merge
Mail merge is used to type the letters only once. This letter can now be combined with a list of
addresses and sent to all the address on the list.
The wizard will guide to creating the mail merge documents.(Step 1 to Step 3/6)
Preparing a merged document involves the merging of two documents the main document which
contains the text to be sent to all the addresses, and the data sources which contain the list of name and
addresses to whom these letters are to be sent, Once can merge the main document with the appropriate
information from the data source.
Creating a Merged documents
Step 1
From the tools menu in the select the Mail merge
In the Mail Merge create button and choose Form Letter.
Select New Main document, word will take to the word active window/ Change document type
option can be selected, where one can type the letter or document to be sent.

Step 2
Choose Create source

The field names commonly used are displayed in the header Row box
To delete filed names, click on the name and click remove field button
To add a new name field type in the new field name and click on add field Name.
Word shows Save data source box, type a name for the data source and save.
Click on Edit data source button to type the variable data.

362
Word Processing

eÁw

In the ass data Box, enter data for each field, click on Add new to enter more records and on OK
to finish entry.
Step 3
In the main document documents click at the position where you want the merged field to appear.
Now click on the Insert Merge field button on the Mail merge toolbar.
Choose the field wanted to insert. The fields will be inserted at that position in the main documents.
The merged documents can be view merge data button on the mail merge toolbar. The first
document with the first set of variable data will be displayed. Use the record navigator buttons to
view the remaining merged data.
Converting PDF files to Word , Word to PDF
Present day the internet files are in the .pdf format where can be converted into the word format
with the extension .doc

363
Word Processing

Review Questions
One mark questions:
1. What is word processor?
2. Name any two popularly used word processors.
3. Give one important activity that is performed by a word processor.
4. What does the tile bar contain?
5. What information is present on the ruler bar?
6. What is a menu.
7. What is the extension of the word processor file?
8. What happens when the left button of the mouse is clicked twice on a word?
9. How do we convert data to bold using formatting toolbar?
10. Which are the standard alignments used in word processor?
11. What is the use of the font dialog box?
12. What are bullets?
13. What is a header?
14. What is footer?
15. How to insert page numbers?
Two marks questions :
1. Give any two advantages of word processors ?
2. Give the steps involved to state word processor?
3. Explain the usage of scroll bar and status bar?
4. Explain the way menus are displayed in word processor?
5. Give the steps for opening a new file in word processor.
6. Write the difference between save as and save ?
7. Give the steps for opening an existing document.
8. Explain the different methods of selecting text with the mouse.
9. Explain any two options of the formatting toolbar in detail?
10. Explain the option of copy in detail.
11. Explain the option of copy and paste?
12. How do we perform the undo operation?
13. Give the commands for copy and paste?
14. How to select the complete text ?
15. What are tables in word processors?
Three marks questions :
1. Explain GUI windows screen in detail?
2. Write the advantages of GUI?
3. What are the advantages of word processor over a manual system?
4. Explain the screen layout in detail that a word processor can perform?
5. Explain the screen layout in detail with suitable illustrations?
6. Give the steps involved in creating a new word processor document?
7. Explain the contents of the formatting toolbar?

364
Word Processing

8. Explain the process of setting the paragraph attributes?


9. How
eÁw do we include bullets and numbers of different types in a document?
10. Explain the process of setting the page margins in details.
11. Explain the spelling and grammatical mistakes in a document?
12. Give the steps involved and the options in finding af=nd replacing text.
13. Explain the steps involved in inserting the images.
14. How to implement page border’s in a word processor
15. Explain the Mail merge operations.

Five marks questions :


1. Explain with an example the creating the document on about you and your family.
2. Create your class time table using the word processor?
3. Create mail merge documents for inviting your friends to your home.
4. Insert an image and document about a page.
5. Create a document using superscript and subscript and mathematical equations.
15.2 Activities
STEP 1. Open a New document. Set the page as A4 and Set the right margin to 6.5 “& type in the
following.
Office is a group of the most popular and widely used Windows application. Included in Office are word-
a Word processing application; ESS- an electronic spreadsheet; Word processors a word processing
application.
The Insertion point is located in the document window where the next character you type will appear.
The horizontal & vertical ruler appears in Page Layout view. Use the rules to change the margins; to
change the indentations of the current paragraphs & to change the tab stops in the current paragraph.
The Status Bar displays the page & section number of the currently displayed page in the document, the
position of the insertion point on the page & the system time.
Drag the scroll box on the vertical scroll bar to scroll up or down in a document or click on the Next page
button or Pervious page button to scroll one page up (or) down. Drag the scroll box on the horizontal
scroll bar to move the portion of the document that is displayed to the left or right.
Changing the view:
Click on the Normal View button on the horizontal scrollbar or choose view-> Normal. In Normal view,
the formatting applied to text appears on the screen, but the layout of a page doesn’t.
Click on the Page Layout View button on the horizontal scrollbar or choose View-> Page Layout to
display a document just as it will appear when printed.
To control how much of the document is displayed, click on the Outline View button on the horizontal
scroll bar or choose View-> Outline, in Outline view, you can easily change the arrangement of text in the
document or the structure of the document.
To display more of the document on the screen, choose View-> Full Screen. All toolbars, menus, scroll
bars, Rules & the status bar is removed, Press Esc to redisplay the screen items (or if this doesn’t work
Press ALT+V & click on Full Screen option).
By default, the Standard & the formatting tool bar appears in the application window. For activating other
toolbars choose View-> Toolbars & select or deselect the other toolbars.

365
Word Processing

STEP 2. Save this document by giving a relevant name.


STEP 3. Close this file.
STEP 4. Find the file using the FIND FILE option & open the file when it is located.
STEP 5. Duplicate this file by giving another name.
STEP 6. Go to the Print Preview & see how it looks when printed.
STEP 7. Give the Summary Info as follows:
Title WORD PROCESSING
Subject WORD
Author (Your Name)
STEP 8. Try selecting a line in your document (by clicking in the Selection bar area).
ry selecting a sentence (through the Control key).
Select a whole paragraph in the document (by double clicking in the Selection bar area).
STEP 9. Using the mouse & control key copy the first paragraph to another location.
Undo this action by clicking on the Undo toolbar.
Now copy a paragraph using the Copy & Paste it to another location.
STEP 10. Using the mouse Move a sentence to another location.
Undo this action.
Now move a sentence using the Cut Option & Paste it to another location.
STEP 11. Select all the text & using the toolbars change the format as:
FONT ARIAL
SIZE 10
Give the Justification for the text.
Change the Format of the last paragraph as: Font Algerian
STEP 12. Make all the headings to appear4 in Bold; Italic; Underlined & centered.
STEP 13. Select a particular paragraph. Copy it. Open a new document & make some changes in
that paragraph. Save it. And check whether the changes made have been affected in the
other document or not.
STEP 14. Find for the word in your document.
STEP 15. Find for the word & replace it with Microsoft.
STEP 16. Find for the Format; Algerian.
STEP 17. Using the Format Painter toolbar copy the format of the last paragraph to the First para-
graph.

366
eÁw

CHAPTER 16
Spreadsheets

OBJECTIVES
To be able to Understand the features
Usage and importance of Spreadsheets
To implement the concepts of spreadsheets to basic accounting concepts

367
368
Spreadsheets

16. Spreadsheet:
AneÁw
electronic spreadsheet is a computer application program that can also hold formulas in a cell that
serve as a calculator. These formulas allow the electronic spreadsheet to perform calculations much faster
and more accurately that spreadsheets created with pencil, paper, and calculator.
The ESS document is a worksheet. Several worksheets can be saved together as a workbook.
The files with the extension .xls or .xlsx. When you start ESS, a blank worksheet opens. A grid of
rows and columns containing numbers and text that allows the user to manage, predict, and present
information.

Fig 16.0 Worksheet

16. 1.1 Spreadsheets applications


 The ESS is the best tools for all the text and calculations involved applications.
 The accounting balance sheet generation for the auditing.
 The area where the graphical presentation is required like statistical details presentations
 In the schools and educational instructions for the presentations of the graphs and
charts.
 Multiple accounting is involved in the file of budgeting for industry or company or IT
firms.

16. 1.2 Basics concepts of Spreadsheets


The rows are represented by numbers from 1 to 1048576 (old versions 65535). The columns are
represented by alphabetic from A to XFD (old versions up to IV) .

369
Spreadsheets

The intersection of row and column are called cell. Each cell has a cell address represented by an
alphabet and the number.
The text is left aligned by default. The numbers are aligned to the right of the cell by default, calcu-
lations can be calculated.
Create formulas. Calculate results from the data by applying formulas to cell. Formulas can be up to
1,024 characters and can contain operators, cell references, values, text, and functions.
Navigate To change the active cell, use the arrow and page up/page down keys, or use the mouse
to click a new cell or drag the scroll bars.
Select cells Click a cell and drag the mouse to select a range of cells. To select nonadjacent cells,
hold down the CTRL key and then click the cells you want to select.
Add a new worksheet to form a work book Click Insert, and then click worksheet. Or, right-click
the tab of the active worksheet to open the context menu, click Insert, and then click worksheet.
Rename the worksheet. Double-click the name tab; when the default name is highlighted, type the
new name.
Format the worksheet. Change or apply font styles, colors, patterns, borders, and cell alignment to
make your worksheets more attractive and easier to read.
Embed charts and pictures. From Analyzing Data, Educator Tutorial series.

16. 1.3 Entering text


Setting Up Rows and columns for entering and calculating Data. Information is entered into cells.
Cells are addresses for information.
 Click in any cell and begin typing text or numbers.
 Type a title for your worksheet in row 1.
 To type data in several columns, you may want to begin typing in column B to leave column A
available for row descriptions.
 You can move from cell to cell by pressing the Tab key or enter Key, or by clicking with your
mouse in the desired cell. Press the Tab key to move to a cell to the right. Press the Enter key
to move to the row below. Type only one description or number in each cell.
 If the text cannot fit in the cell, it will be hidden. There are two main ways to make text fit into a
cell( so multiple lines of text will shown in one cell). To widen a column, move your cursor over
the line on the right side of the column heading. When the cursor turns into a double arrow, click,
hold, and drag to the right or left until the column is the width you want. To wrap the text Click
the cell that you want to wrap, or click the column or row selection button to select the entire
column or row(your cursor will turn into a down-or right-pointing arrow when it is over the
selection button)
 On the format menu click cells.
 Select the Alignment tab.
 Under Text control, click Wrap text.
 Click OK.
370
Spreadsheets

Note: your row will automatically widen to accommodate the word-wrapped text. However, you
can manually
eÁw
widen or reduce the width of a row: move your cursor over the line underneath the row you
want to modify. When the cursor turns into a double arrow, click, hold, and drag up or down until the row
is the width you want.

16. 1.4 Menus


Menus help in navigating the commands and operating the commands.

Fig 16.1 File Menu

File Menu :
New(Ctrl +N) start a new work sheet file. Recent work sheets viewed up to eight files open at once.
Open(Ctrl +O) lets you open an existing document. It opens to the drive and folder set as the default
in the shortcut. To change to a different drive or folder, click on the triangle next to the box labeled Look
In: . The button lets you create a new folder... very handy! The next two buttons show the contents
either as a simple list or with details (file size, modification date, etc). The button moves you up one
level in the folder-tree... also very handy. The File of Type field, near the bottom is very useful, if you want
to use Works to open). If you can’t find your file, choose All Files (*.*).
Close: Closes a single document, but not the program.
Save/Save As(Ctrl +U). The first time you save, these two menus give you the same thing... a
dialogue box almost identical to the Open one... after that, clicking on Save no longer gives you a dialogue
box— it just saves, with the same options already chosen. Save As, however, always shows the dialogue
box... handy if you want to save under a new name or in a different location— a quick and make another
copy of a file, or to create a backup version.

371
Spreadsheets

Save : Be aware of the File of Type option... it lets you save in Word Processor format to work on
your document on another computer (at home, for instance), if you don’t have Works available. File type
text is a lowest common denominator— every computer can read it, but font and formatting information
is lost.RTF (Rich Text Format) is almost as universal, and includes fonts, graphics, etc. — File Names can
be up to 255 characters long in Works 4, and can includes spaces— but not a few characters such as
question marks or colons that have special meanings to the operating system. If you are using Works 2 or
3, you are limited to 8-character file names. In either case, do not end your file names with a period, or
add a customized three letter extension— either will confuse Windows when you try to open your file
again. The Template button lets you save a document that you will often re-use, with changes..........
customized letterhead, report card form, etc. When you save a template, you open it by using the File/
New/TaskWizards item, and scroll down the list to User Defined Templates:
Page Setup: Lets you set the margins (note— in the units you set in the Options). The Source, Size
and Orientation lets you set the paper size and whether you want your document to be vertical (portrait)
or horizontal (landscape).You may need to set your printer to match these settings.
Print Preview shows you a miniature view of how your document will look when it’s printed. You’ll
save lots of paper if you routinely use this before printing!
Print(Ctrl +P) lets you control pages printed, number of copies, target printer, etc. If you have
multiple printers, choose the target printer using the drop-down triangle next to the Printers box. (You set
the default) printer with the Start Menu’s Settings/Printers item— right-click on the desired printer, and
choose Set as Default. To print just page 3, you need to set it to print from Page 3 to Page 3.
Exit: Works(Alt +F4) closes the program. You will be prompted to save any unsaved work.
On the bottom of the File menu, you’ll see the last four documents opened... this is handy way to
quickly get back to your most recent work.

Edit Menu
These items are very useful. Be sure to memorize the keyboard shortcuts!!
Fig 16.2 Edit Menu

372
Spreadsheets

Edit Menu items involve working with selections— telling the computer that you want to do some-
thing toeÁw
part of your document. To select some text, you can do one of the following techniques: Click at
the beginning of the desired selection, hold the left mouse button down, and drag over what you want to
select. It can often be hard to be precise this way. Alternatively: Click at the beginning, hold the shift key
down, and click at the end of the desired selection. Or: Click at the beginning, hold the shift-key while
using some combination of the arrow keys (left, right, up, or down), Page Up, Page Down, Home, End,
Ctrl+Home, or Ctrl+End to extend the selection. Selection is also useful with the Format menu items.
Here are the contents of the Edit menu:
Undo Editing(Ctrl +Z) can be a life saver— if you try it immediately when you make a mistake. If it
(and any menu) is greyed-out it is unavailable at this time.
Cut(Ctrl +X) and Copy (Ctrl +C) are only available if something is selected. If so, they both copy
the selection into the Clipboard for use later. (The Clipboard is a metaphor— not a real, physical part of
the computer. It means the selected item is being stored in memory. The Clipboard only holds one thing at
a time... when you Cut/Copy something else, the previous contents disappear). When you Cuta selection,
it vanishes from the page... when you Copy it, it remains on the page.
Paste(Ctrl + V) places whatever is in the Clipboard where ever the cursor is. Note that when you
paste, the selection is not removed from the Clipboard... you can paste the same item multiple times.
Paste Special is a techie option that you’ll never use. Trust me.
Clear(Del) erases a selection, without sending it to the Clipboard.
Select All(Ctrl +A) selects the whole document... useful for making global changes like changing the
font and size, or double-spacing everything.
Find(Ctrl + F) lets you search a document for desired text... similar but probably more useful is the
next item:
Replace(Ctrl +U — they ran out of letters? Why not Ctrl + R?)lets you find text and automatically
(or manually) replace it with something different: Pete with Mary, for example.
The Find Next option moves to the next instance of the Find text, giving you the choice to replace it
or not... Replace All automatically replaces all instances, and reports on the number replaced.
Note that if some text is selected, this only searches in the selection first reason why this might not
work as expected. The two buttons in the center let you add a Tab and a new Paragraph to the desired
text to search or replace. Note the two options:
Easy Text lets you save and insert something you’re often going to use... your return address, for
example. To create Easy Text, high light desired text, and choose this menu item. Choose New, and type
a name for it. (You apply Easy Text from the Insert menu)
Bookmark lets one to add or delete bookmarks, to use with the Go to menu.
Linksand Object are two other menus you’ll never use.

373
Spreadsheets

View Menu
A bunch of options what you see on screen... note that these don’t change the actual contents— just
how they’ll be showed to .

Fig 16.3 View Menu

Normal shows text and graphics, but not margins, headers, or footers... it you find that can’t see all
the way across the page, try changing to this view. It’s also faster on an older computer.
Page Layout shows more like what your page will look like when printed... You have to choose one
or the other of those views. Toolbar... click on this if the toolbar has disappeared!
Ruler to display a ruler on the top, in the units set in the Options. All Characters shows the hidden
characters— spaces, Enter, tabs, paragraph, etc.
Header and Footer jump you to the top or bottom of the page (respectively). Headers and Footers
are for text that you want to appear on every page— titles, page numbers, date, etc. In normal view, these
are shown as a single line labeled H or F at the beginning of the document. In Page Layout view, these are
shown as approx 1 cm. wide areas at the top (or bottom) of every page.
The tab key moves you from the left, to the center, to the right of the Header/Footer area, so you can
have three items in each. One can set the font/size separately from the main text. You can use the Insert
menu items to insert (for example), page numbers, or date into the Header or Footer. So to have a Footer
that reads “Page 23” (or whatever the correct number is), go to the Footer and type the word Page
followed by a space, then click on the Insert menu, and choose Page Number. All Footer will read ‘Page
*page*’, but when you print (or print preview), the correct page number will appear.
Headers/Footers on all pages except the first (for a title page, for example), go to File/Page Setup/
Other Options.
Foot notes shows you the footnotes that you created with the Insert/Foot note menu item... these are
at the bottom of the page unless you chose to put them at the end, using File/Page

374
Spreadsheets

Setup/ Other Options.


Zoom
eÁw changes the size your page is displayed at... not the size it will print at. Useful if you need to get
up close, or if you can’t see a full page-width on screen at once.

Hiding Cell Gridlines


Sometimes the gridlines get in the way of what you intend to present in your worksheet. The default
gridlines that you see on the screen will not print(unless you change the default settings), but they are
viewable on the screen. To view a worksheet without gridlines:
1. On the tools menu, click options.
2. click the view tab.

Insert Menu
Insert Pictures, Logos or Diagrams
Insert pictures or logos Insert > Picture Insert a diagram Insert > Diagram Draw lines on the spread-
sheet or add shapes Use the Drawing Toolbar. Make sure this is visible by selecting
View > Toolbars > Drawing, then select the relevant lines or shapes and draw them onto the
worksheet

Fig 16.3 Insert Menu

Adding Drawing objects to your worksheet

Adding a drawing object in ESS is very similar to the procedure used in any other word processor Office
program. On the Drawing toolbar click Auto shapes, point to a category, and then click the shape you
want. Or, choose the rectangle or oval shape on the drawing toolbar. The cursor will turn into crosshairs.
Click, hold, and drag to create your shape. To add fill color: Click on the object to select it. Click the
down-arrow next to the fill color button (paint bucket) on the drawing toolbar. Choose a color or fill
option. To color additional objects with that color, simply select that objects, then click the fill color
button. The drawing toolbar is usually located at the bottom of your screen. If the Drawing toolbar is not
visible, on the view menu, point to Toolbars, and then click Drawing.

375
Spreadsheets

Format Commands

A format, quite simply, is the way in which something is arranged or presented. ESS contains a number of
formatting options and tools that you can use to improve the presentation of your spreadsheets. By using
lines, colours and spacing you can draw attention to or from text or data and make the information you
present easier to understand. This note helps you find Ess’s most commonly used formatting commands
on your PC.

Fig 16.5 Format Menu


TOOLS MENU
A click on the “Tools” tab in the Menu bar or pressing “Alt + T” keys will open the Tools menu. By default
Ess opens the menu with commonly used commands only. (All commands available under the menu can
be viewed by a click on the double downward arrow circular tab at the bottom of the menu.) A small
triangle against a command name indicates a sub-menu for the command. The commands listed under File
Menu can be executed or the sub-menu can be opened by a click on its icon / tab or by pressing key for
the underlined letter after opening the menu (or by pressing the keys listed on the right side of the com-
mand name).

Fig 16.6 Tools Menu

376
Spreadsheets

Checks errors in formulas on the worksheet and if an error is found suggestions are given.
Spelling
eÁw Checks spelling of text in the currently open worksheet.

Research Enables search for typed text on web.


Error checking
Formula Auditing Formula Auditing can be used to find and correct errors in formulas. to know
about Finding and Correcting Errors in Formulas
Checks errors in formulas on the worksheet and if an error is found suggestions are given.
Goal Seek Goal Seek
Macros : A macro is a series of instructions which can be issued using a single command. The
macro can be invoked in various different ways - from the keyboard (using a Control key combination),
from a special icon on a toolbar or through the menu system. Ideally, you need to know a programming
language (Microsoft Visual Basic) to create really useful macros; the examples below give you an intro-
duction to macro writing.

Data Menu
You can create tables some of the simple features for sorting and performing calculations with numeric
data in tables. However, ESS provides many more powerful features for handling numeric data. How to
use Autofill to fill in a series and the Function Wizard to calculate a statistical function.

Fig 16.7 Data Menu

377
Spreadsheets

You can create tables some of the simple features for sorting and performing calculations with
numeric data in tables. However, ESS provides many more powerful features for handling numeric data.
how to use Autofill to fill in a series and the Function Wizard to calculate a statistical function.

Sort data
The sorting will arrange the data in ascending or descending order. When the range of value re given.
Either the rows or columns. Both numeric and alphabetic sorting is possible.
Filter data
Filtering data by selecting a value seems like a nice feature. You select a region, click a button, and
Ess displays. Ess does support selection filtering, but looking for it because it’s not available by default on
the ribbon or tool bar once the option is added, selection filtering is just two clicks away.
Create a pivot table
First, our data that we want to use to populate the pivot table resides on Sheet1.
Under the Data menu, select “PivotTable and PivotChart Report”.

Manipulate a time series


Resources for time-series data manipulation. time-series statistical analysis (e.g. Sales details, Fore-
casting, etc). To extract a portion of data based on a time segment. Problem with statistical analysis with
TS and TS data manipulation in Reverse. Examples only on time-series data manipulation All kind of
manipulation. Once I can extract required data in time-series format statistical analysis.
data<-ts(data[,1],start=1956,freq=12)

Windows Menu
Suppose you have created a workbook with a a numbers of sheets, typically a number working data
sheets and maybe a summary sheet. In order to monitor the cells on the summary sheet whilst still working
on one of your other sheets in the same workbook.
In Ess this task is possible by clicking the New Window on the View Tab. To view both windows on
your screen Hit View> Arrange All>- select any option but not CascadeIn my example below I have
selected Horizontal. Ess has assigned a new name to the new workbook window, and in addition it has
changed the original.

378
Spreadsheets

eÁw

Fig 16.8 Window Menu

Fig 16.9 Two windows can be seen

In my example it has renamed the windows Widget Sales Summary:2 and Widget Sales Summary:1.
Two Views of the same workbook- how neat is that?. Sales Summary 1 is the summary sheet and Sales
Summary2 is my data sheet.

Help Menu
Press F1 to get the help on the topics /contents.

379
Spreadsheets

Fig 16.10 Help Menu

16. 1.5 Commands


The commands of the ESS can be carried using Keyboard and using Mouse.
Using Keyboard
The desired menu can be opted using Alt key and the desired option. For example if the File menu
bar option Press ALT and F keys together to display its pull down menu.
Inside the pull-down menu also, each of the commands has an underlined letter. Here again you have
to press only the underlined letter. For example to select the Print option for the File pull-down menu,
press the Alt and F keys together and then press the letter P from the keyboard
Using Mouse
The second method is simply moving the mouse pointer over the menu bar option and then clicking
the left button. For example for selecting the File menu bar option, move the move-pointer over this
option, and then click the left mouse-button. A pull-down menu gets displayed.
Inside the pull-down menu consisting of a list of commands, move the mouse-pointer over the de-
sired commands and click the left ,mouse-button for example to select the over Print option, move the
mouse-pointer over this option and click the left mouse-button.

16.1.6 Column width


To widen a column, move your cursor over the line on the right side of the column heading. When the
cursor turns into a double arrow, click, hold, and drag to the right or left until the column is the width you
want. To wrap the text Click the cell that you want to wrap, or click the column or row selection button
to select the entire column or row(your cursor will turn into a down-or right-pointing arrow when it is over
the selection button) On the format menu click cells. Select the Alignment tab. Under Text control,

380
Spreadsheets

click Wrap text. Click OK.


eÁw
16.1.6 Copy
Copying Data or Formulas
You can quickly copy and paste text, numbers, or formulas. When you copy a formula, ESS
automatically adjusts the cell references so that they correspond to the new formula location. For ex-
ample, if you are adding the numbers in column A and you copy the formula to column B, ESS automati-
cally adjusts the formulas so that it is adding up the numbers in column B, not column A
 Click the cell or select the cells that you want to copy.
 On the Edit menu, click copy or press Ctrl-c moving dotted lines will appear around the cells
that you are copying.
 Click in the cell to which you want the data or formula to be copied.
Hint – To copy the formula to multiple cells, in click in the cell with the formula , click, hold, and drag
to select all of the cells in which you want the formula to appear.

16.1.7 Paste
You can quickly copy and paste text, numbers, or formulas. When you copy a formula, ESS
automatically adjusts the cell references so that they correspond to the new formula location. For ex-
ample, if you are adding the numbers in column A and you copy the formula to column B, ESS automati-
cally adjusts the formulas so that it is adding up the numbers in column B, not column A
 Click the cell or select the cells that you want to copy.
 On the Edit menu, click copy or press Ctrl-c moving dotted lines will appear around the cells
that you are copying.
 Click in the cell to which you want the data or formula to be copied.
 On the Edit menu, click, pasted or press Ctrl-v.
Hint – To copy the formula to multiple cells, in click in the cell with the formula, click, hold, and drag
to select all of the cells in which you want the formula to appear.
Note: the number of rows and no of columns copied must match with the numbers of row and no of
columns in the paste sheet/ paste to the cell.

16.1 8 Insert rows /columns


Adding Rows or Columns
 To add a row or a column, click the row or column selection button at the far left of the row or
the top of the column.
 on the Insert menu, click either Rows or Columns to add a row above your selected row or a
column to the left of the selected column.
 Deleting Rows or Columns
 To delete a row or a column, click, the row or column selection button on the far left of the row
or the top off the column.
 To delete the entire row/column and its contents, on the Edit menu, click Delete.
381
Spreadsheets

 Note; To delete only the contents of the row/column, on the edit menu, point to Clear, then click
All.

16.1.9 Formatting
Formatting cells can change the way the cells look or change how the content is represented by
formatting the cells.

Fig 16.11 Cell format

Format Text Perform basic text formatting functions. The formatting toolbar Perform more com-
plex text formatting functions Format > Cells > Font tab Align Text Wrap text Format > Cells > Alignment
tab >check the Wrap Text box Align text to the left or right of a cell or column Use the formatting toolbar
or Format > Cells > Alignment tab and select the Horizontal and/or Vertical text alignment options as
appropriate Indent text . Use the formatting toolbar or Format > Cells > Alignment tab and increase the
number in the Indent box as appropriate Change the text direction Format > Cells > Alignment tab and
slide the indicator in the Orientation area to the appropriate direction
Merge Cells Merge cells Highlight the cells, then Format > Cells > Alignment tab and check the
Merge Cells box or Highlight the cells, then use the merge and center button on the toolbar Split merged
cells Highlight the cells, then Format > Cells > Alignment tab and uncheck the Merge Cells box

Format Rows and Columns


Insert rows or columns Insert > Rows or Insert > Columns Hide rows or columns Select the row or
column to hide, then Format > Row > Hide or Format > Column > Hide Change the column width ·
Double click the column border to auto fit the width to the longest entry in the column or · Drag the column
border to your chosen width or · Format > Column > Width and enter the specific width Change the row
height · Drag the row border or · Format > Column > Row and enter the specific height

Format Numbers
Change numerical values to percentages (e.g. from 0.04 to 4%) The formatting toolbar or Format >
Cells > Number tab Increase or decrease the number of decimal places (e.g. from 12400 to 12400.0)

382
Spreadsheets

The formatting toolbar or Format > Cells > Number tab


Change a plain number to comma style (e.g. from 12400 to 12,400)
eÁw
The formatting toolbar or Format > Cells > Number tab
Change a plain number to currency style (e.g. from 12400 to £12,400)
The formatting toolbar or Format > Cells > Number tab
Choose a date format : Format > Cells > Number tab > Date and select options as appropriate
Align currency symbols and decimal points Format > Cells > Number tab > Accounting and select
options as appropriate Show text exactly as it is entered Format > Cells > Number tab > Text Create my
own format code Format > Cells > Number tab > Custom Insert today’s date into a cell Press CTRL and
; (semicolon) at the same time.

Add Borders and Shading


Apply borders to cells · Use the Borders palette on the formatting toolbar to draw borders directly onto
the worksheet or · Format > Cells >Border tab and select options as appropriate Apply shading (colours)
and patterns to cells · Use the Fill Colour palette on the formatting toolbar to select from preset options or
draw borders directly onto the worksheet or · Format > Cells >Patterns tab and select options as
Appropriate Highlight cells or text when a specific condition is met (e.g. highlighting all salaries over
£25,000 in a column of different salaries) Note : Rupees symbol can be inserted.
Select data range and use Format > Conditional Formatting, then specify your criteria and your
format

Use Automatic Formatting


Apply automatic formatting to my table of data Highlight the whole table then Format > AutoFormat
and select the style you require Copy formats from one area of my worksheet to another Select a cell
containing the formatting to be copied, click on the Format Painter button on the standard toolbar then
select the cells to which you wish to apply the formatting

Format Description Sample Format Text Example

"#,###.0" will show:


Changes the data 0.0
display for a cell, such
as decimal places. mm/dd/yyyy
Cell This is the same as #,##0_);
Formatting the "Format Cells - "dddd, mmmm dd, yyyy"
Number" command
[Red](#,##0) will show:
inside of Ess (see
screenshot below)
@ (for text)

Bold Changes font to bold 1=Bold, 0=Not Bold

383
Spreadsheets

Italic Changes font to italic 1=Italic, 0=Not Italic

Changes font to 1=Underlined, 0=Not


Underline
underlined Underlined

Same as Font selection


Changes the font
Font Name in Ess, such as
typeface
"Verdana"

Same as point size in


Changes font point
Font Size Font selection, such as
size
"18"
Changes font color. #FF0000 = red
Font Color Use standard HTML
colors (RGB) #808080 = gray
Changes cell color. #f8f800 = red
Background
Use standard HTML
Color #f0f0f0 = light gray
colors (RGB)

Horizontal Placement of text


Alignment inside a cell
left, center, right

Vertical Placement of text


Alignment inside a cell
top, middle, bottom

Column Number of pixels for


Size of a column
Width new width

Row Height Height of a row Number of pixels

Changes border none, thin, medium,


Border
around cell thick

Fig 16.12 Different Formats

16.1.10 Formul a Creating simple calculations


Formulas are equations that perform calculations in a worksheet. In ESS, you create a formula
every time you want to add, subtract, multiply divide, or make any other mathematical computation.
To add numbers in various cells

384
Spreadsheets

 Click a cell in which you want the calculation to appear.


 Type the equal sing: =
eÁw
 Click the first cell that you want to add. ESS will automatically enter the cell name(e.g., B3) into
the formula
 To add the data from additional cells, type the plus sign;+
 Click the next cell you want to add.
 Continue alternating the plus sign and clicking a cell you want to add.
To subtract numbers in various cells:
 Click a cell in which you want the calculation to be placed.
 Type the equal sign: =
 Click the first cell from which you want to subtract. ESS will automatically enter the cell
name(e.g.,B3) into the formula.
 Type the minus sign:-
 Click the cell that you want to subtract from the first cell.
 Continue alternating the minus sign and clicking a cell you want to subtract.
 When finished, press Enter.

To multiply two numbers.


 Click a cell in which you want the calculation to be placed .
 Type the equal sign; =
 Click the first cell that you want to multiply, they type the asterisk; *
 click the cell you want to multiply.
 Press Enter.

To divide two numbers:


 Click a cell in which you want the calculation to be placed.
 Type the equal sign; =
 Click the cell that you want to divide into ( the numerator), they type the slash:/
 Click the cell you want to divide by (the denominator)
 Press Enter.

Using the Built-in Formulas in ESS


ESS contains pre-defined formulas that will automatically add numbers, find out an average, calcu-
late a payment on a loan, etc. formulas always include the function’s name (such as Sum. Average,
If,etc.,) the cells you want to calculate, and any other information(called arguments) that are needed to
complete the formula.
Using Autosum.
If you have a consecutive list of numbers that you want to add, use the sum formula.
a sum formula results in the same answer as if you typed =D3+E3+F3+G3+H3+I3, but instead it
lists the range of cells that you want to add. The formula=sum(d3:I3) adds the numbers in cells d3, i3, and
all cells in between them. The Autosum tabulation tool is the tool to use to quickly add numbers in
consecutive cells.

385
Spreadsheets

=D3+E3+F3+G3+H3+I3 =SUM(D3:i3)

 Click a cell in which you want the calculation to be placed.


 On the standard toolbar, click the Autosum button.
 It will automatically create a formula does not contain the correct set of numbers, click,. Hold,
and drag across the cells that you want to add together.
 When the range of cells you want to add together is surrounded by a box, press Enter.
 Additional automatic formulas are available. By click the down-arrow next to the Auto sum
button, you can select a variety of formulas that will be automatically entered to make quick and
easy calculations. Follow the same directions as above except instead of clicking the Auto sum
button, click, the down-arrow next to it and select a different function Average, count(how many
entries) Max(Maximum number in the list) or Min (Minimum number in the list) additional functions
are available if you click More functions.
Creating a More complex or Unusual formula
Sometimes you may need a more complex or unusual formula than just adding, averaging, counting,
etc. when you create a formula that contains a function ( a pre-defined formula), THE Insert Function
dialog box helps you enter your formula data.
 To start the formula with a function, click the Insert Function FX button on the Formula Bar.
 The Insert function dialog box will open. In search for a function box, you can enter a question
that describes what you want to do ( for example, searching for “Roman numbers” results in the
function Roman, which converts regular numbers into Roman numerals; “loan payment” results in
the function PMT, which calculates the payments of a loan with interest) or in the or select a
category box, you can browse from the categories.
 Once you select a function name from the Select a function list, click Ok.

Note: when you click a function name, a brief explanation of the selected function appears.
 When you select a function, the Functions Argument dialog box will open. Enter the needed
information. All argument boxes may not need to have data. You can get help on what kind of
data to enter by clicking in the data box where you need help, then clicking Help on this function.
You want directly click or select a series of cells to enter into the argument fields while the function
Arguments dialog box is open. Whatever you click or select will automatically be entered into the
formula data. If the functions arguments dialog box is in the way, click, hold and drag the box to
386
Spreadsheets

a new location. As an example, data for the function, If, is shown below. The results of the If
function is a formula that makes a logic or condition test. In the example below, the test compares
eÁw
a number we designated to the number in a specific cell. The number in cell E5 must be larger than
30 to display the comments, “we made our goal!”
 Once you have entered your data, click Ok. The formula makes its logic test an then displays the
appropriate answer in the cell in which the formula is located.

16.1.11 Print: Printing a worksheet


 On the file menu, click print preview. This view shows you how the document will print with the
current settings. If the preview is what you want, click the print button in the preview window and
continue printing window. If it is not what you want, click setup and continue with step .
 If you clicked setup, the page setup dialog box appears.
o If your data is going off the page, you have several options:
o In the page setup dialog box, change your paper layout so that they fit on a page, in the
page setup dialog boss, select the fit to option. If it is acceptable to print on a second
page for the length, but you want the width of your information to appear on one page,
you can select a higher page number than 1 for how many pages “tall’ you want your
worksheet to print, while keeping the width at 1 page wide

Fig 16.14 Printing Popup window

o The other option is to move things around on your page so that they all fit into the print
range. Click cancel in the page setup dialog box and close print preview. The print range
will now be marked on your worksheet as a dashed line. Move your content or adjust
the width of your columns or rows so that the content falls within the dashed lines, and
repeat from the beginning.
o When you have completed your changes, click OK.

387
Spreadsheets

o Return to back to the beginning to preview your worksheet. If the preview is acceptable,
continue to go printing window.
 In the print preview window, click print, or, if, you are in the Normal view of your worksheet and
not in print preview, on the file menu, click print.
o The print dialog box will appear.
o Check to be sure that the default printer is correct. If it is not, click the down-arrow next
to the printer name and select the correct printer.
o The default is to print only the worksheet you are currently viewing,. If you have several
sheets, and you want to print all of them, click Entire workbook.
o To change the settings for your printer, such as print quality, color, paper type, etc., click
properties…. Make your changes, then click OK to return to the print dialog box.
o When ready, click Ok to print your worksheet.

16.1.12 SORT
The sorting will arrange the data in ascending or descending order. When the range of value are
given. Either the rows or columns. Both numeric and alphabetic sorting is possible.
The sort feature in Ess allows you to look at the same data in different ways depending
upon what information you are after. Ess allows you to sort by date, sort by text or numbers,
sort by multiple columns, or by color. And, if you like, you can even color code your data. These
tutorials include step by step examples and cover the main sort options available in Ess.
Sort the data based on the date : Select the range and click on sort. The data will be sorted.

Fig 16.15Date is sorted based on year

16.1.13 Filter
Filtering data by selecting a value seems like a nice feature. You select a region, click a button, and
Ess displays. Ess does support selection filtering, but looking for it because it’s not available by default on
the ribbon or tool bar once the option is added , selection filtering is just two clicks away.
Set up the database: The first row (A1:D1) has headings. Subsequent rows contain data. There
are no blank rows within the database. There is a blank row at the end of the database, and a blank
column at the right.

388
Spreadsheets

Set up the databaseThe first row (A1:D1) has headings. Subsequent rows contain data. There are
no blank rows within the database. There is a blank row at the end of the database, and a blank column
eÁw
at the right.

Fig 16.16 Data filter on total


Set up the Criteria Range (optional)
In the criteria range for an Ess advanced filter, you can set the rules for the data that should remain
visible after the filter is applied. You can use one criterion, or several.
In this example, cells F1:F2 are the criteria range. The heading in F1 exactly matches a heading (D1)
in the database. Cell F2 contains the criterion. The > (greater than) operator is used, with the number 500
(no $ sign is included).
After the Ess advanced filter is applied, orders with a total greater than $500 will remain visible.

Other operators include:


< less than
<= less than or equal to
>= greater than or equal to
<> not equal to
Set up the Extract Range (optional) If you plan to copy the data to another location, you can
specify the columns that you want to extract. If you want to extract ALL columns, you can leave the
extract range empty for the Ess advanced filter. Select the cell at the top left of the range for the extracted
data. Type the headings for the columns that you want to extract. These must be an exact match for the
column headings, in spelling and punctuation. The column order can be different, and any or all of columns
can be included.

389
Spreadsheets

Apply the Ess Advanced Filter Select a cell in the database. On the Ess Ribbon’s Data tab, click
Advanced, to open the Advanced Filter dialog box You can choose to filter the list in place, or copy the
results to another location. Ess should automatically detect the list range. If not, you can select the cells on
the worksheet. Select the criteria range on the worksheet If you are copying to a new location, select a
starting cell for the copy
Note: If you copy to another location, all cells below the extract range will be cleared when the
Advanced Filter is applied. Click OK
Fig 16.17 Data form filter on t-shirt

That’s it. In just two clicks, you filtered your data! You can use the AutoFilter option with any column
or any value in your data set. You can further hone your records by moving to a second column, choosing
a value, and clicking AutoFilter. As you can see below, the filtered recordset now shows Medium T-Shirt
records, not just all Medium records.

Click anywhere inside the data range. Click the Data tab. Choose Filter from the Data menu, select
AutoFilter, Click Filter in the Sort & Filter group. Doing so displays the filtering arrows in the header
cells. Click the Item column’s filtering arrow and uncheck Select All (the default). Check one column , and
click OK. (Ess filter is a bit easier to use - just select the value). To clear the filter, click Clear in the Sort
& Filtering group. choose Filter from the Data menu and then Show All. It’s a tedious process if you do it
often.Now, let’s reduce the previous process to just two clicks by enabling the filter by selection option
(AutoFilter), as follows (in the latest version of ESS) :
1. Click the File tab and then choose Options (under Help).
2. In the left pane, choose Customize ribbon.
3. Choose All Commands from the Choose Commands From dropdown.
4. Select AutoFilter in the resulting list.
5. To the right, click the Data tab and then click New Group.
6. Click Move Up to position the new group right after the Sort & Filter group.
7. With the new group selected, click Add.
8. Click OK and Ess adds a custom group with the AutoFilter option.

390
Spreadsheets

eÁw

Fig 16.18 data forms auto filter using customize Ribbon

In Ess 2007, add this option to the Quick Access Toolbar (QAT), as follows: From the QAT dropdown,
choose More Commands.
If you’re still using Ess 2003, customize the toolbar as follows: Choose Customize from the Tools
menu. From the Categories list, select Data. In the Commands list, find AutoFilter and drag it to the
toolbar. Show All.Click Close.
Now, you’re ready to use the new filtering option, as follows:
First, select a cell that contains the value you want to sort by. For instance, select Medium in column
C.Next, click AutoFilter (the new option in the custom group you just added). In Ess 2007, you’ll find it
on the QAT. In Ess 2003, you’ll be using the button you just added to the toolbar.

16.1.14 Other basic operations


Relative Cell Reference: A cell reference that adjusts to a new location when copied or moved.
Absolute Cell Reference: A cell reference that does not adjust to the new cell location when copied or
moved.
Mixed Cell Reference: A cell reference containing both relative and absolute references

16.2. Different types of graph -(some advanced features such as graphs)


Using Appropriate charts and Graphs
Charts are visually appealing and make it easy for users to see comparisons, patterns, and trends in
data. For instance, rather than having to analyze several columns or worksheet numbers, you can see at
a glance whether the data is falling or rising over a particular period. Different charts are used for different
purposes. Consult the summary below to determine what type of chart you should use:

391
Spreadsheets

Step 1 select the range of values


Step 2 : Insert the chart and type of chart and style.
Step 3: View the graph.

Fig 16.19 Different types of graph

Column: column charts are used to show how values change over time to compare data or show
trends. They are typically used for a limited time series( e.g., just a few years, quarters, months, etc.)
arrange your data in columns:
Bar: A horizontal bar chart is very similar to a column chart in that it shows individual figures at a
specific time or makes comparisons, but it places less emphasis on time flow. It resembles a column chart
that has been rotated 90 degrees. If you have a large number of data values that you need to show, a bar
chart is typically a better choice than a column chart if you plan to print the chart. A column or line chart
would be more beneficial if you want to evaluate change over time. Arrange your data in columns or in
rows.
Line: Line charts are best for showing changes in a group of values over longer periods of time,
especially if you are trying to emphasize time flow and rates of change, rather than amount of change.
They are also recommended if you are displaying several groups of data simultaneously. Arrange your
data in columns or in rows.
Pie: pie charts are often the best way to portray the contributing of parts to a whole or showing
proportions and ratios. They are used to show a “snapshot” at a specific time. A pie chart works best if
you do not have more than six or seven different values. Pie charts have only one series of data, so you
should use only one column of data:
XY Scatter: The XY or scatter chart is commonly used to plot scientific data, but it can be used for
any chart where you want to see the relationship between two different numerical variables and compare
392
Spreadsheets

trends across uneven time periods. Scatter charts can reveal trends or patterns in data and can be used
for determining
eÁw
whether variables are dependent upon or affect one another. Arrange your data in
columns, with x values in the first column are corresponding y values in adjacent columns:
Doughnut: At first glance, a doughnut chart appears to just be a pie chart with a hole in the middle.
This is basically true if you are plotting on data series. Unlike the pie chart, however, a doughnut chart can
be used to show more than one data series. When you create a doughnut chart with multiple data series,
the first data series is placed in the center of the doughnut, each successive series forms a ring on the
doughnut.
Adding charts and Graphs ESS has a very easy chart wizard to help you create a chart or graph of
your data by leading you through four steps

Fig 16.20 Different types of graph


1. On the Insert menu, click charts.
2. In the chart wizard dialog box, click a chart type on the left, then click a chart sub-type to
choose the style.
3. click Next.
4. On your worksheet, click, hold, and drag your cursor to select the cells that you want to appear
in your chart. If the chart wizard dialog box is in the way click, hold, and drag it to another
location.
5. When your cells are selected, click Next.
6. If desires, enter a title for your chart and titles for the X- axis (horizontal) and the Y-axis(vertical)
7. You can click on any of the other tabs to make changes to the way the Axes, Gridlines, Legend,
data labels, or Data Table is formatted.
8. Click Next.
9. If you want the chart to appear on the same worksheet as your data’s, keep the default setting
shown in the As object in box. If you want the chart to appear on a separate worksheet
remember a Standard ESS file has three worksheet), select one of the other sheets listed in the
As Object in drop down list, or select As New sheet and keep the default or type a name for the
new worksheet.
393
Spreadsheets

10. Click Finish.


11. Your new chart will appear on your worksheet. Click, hold and drag the white area of the chart
to move it to the desired location in your worksheet.
12. If you change any of the existing data in the worksheet, it will automatically update your chart.
However, if you add a row or column, you will need to repeat the steps above.
13. You can copy and paste the chart into any other application:
a. Click once on the chart to select it.
b. On the Edit menu, click copy ( or press ctrl-c)
c. Open the file where you want to paste the chart.
d. On the edit menu, click paste( or press Ctrl-V)

16.2.1 Library functions


(Arithmetic, date and time, Financial, Logical, text and statistical) with emphasis on commerce re-
lated applications and data forms with applications to simple problems.
Creating a More complex or Unusual formula
Sometimes you may need a more complex or unusual formula than just adding, averaging, counting,
etc. when you create a formula that contains a function ( a pre-defined formula), THE Insert Function
dialog box helps you enter your formula data.
To start the formula with a function, click the Insert Function FX button on the Formula Bar.
Example =sum(d3:i3) sum of range d3to i3 to calculate the total

The SUM Function The AVERAGE Function

To add a column or a row of numbers follow the To average a column or a row of numbers
steps below: follow the steps below:

394
Spreadsheets

eÁw
The SUM Function The AVERAGE Function

To add a column or a row of numbers follow To average a column or a row of numbers


the steps below: follow the steps below:

1. Click on an empty cell. In the above 1. Click on an empty cell. In the above
example, we chose cell F1 in which to example, we chose cell F1 in which to
enter our formula. enter our formula.
2. With your keyboard type the equal 2. With your keyboard type the equal sign
sign (=) (=)
3. Begin the function by typing SUM( 3. Begin the function by typing
* Don't forget to open the AVERAGE(
parentheses! * Don't forget to open the parentheses!
4. Either type A1:E1 or use your mouse 4. Either type A1:E1 or use your mouse to
to highlight cells A1, B1, C1, D1 and highlight cells A1, B1, C1, D1 and E1
E1 5. Complete the function with a closing
5. Complete the function with a closing parentheses by typing )
parentheses by typing ) 6. Press the <ENTER> key
6. Press the <ENTER> key
Note the average of the numbers is displayed in
Note the sum of the numbers is displayed in cell F1 and the formula can be found in the
cell F1 and the formula can be found in the formula bar.
formula bar.

The SQRT (SQuare RooT) Function

To find the square root of a number located within a worksheet cell follow the steps below:

1. Click on an empty cell. In the above example,


we chose cell B2 in which to enter our
formula.
2. With your keyboard type the equal sign (=)
3. Begin the function by typing SQRT(
* Don't forget to open the parentheses!
4. Either type B1 or use your mouse to click on
cell B1
5. Complete the function with a closing parentheses by typing )
6. Press the <ENTER> key

Fig 16.22 Different built in arithmetic functions

A formula is an equation that performs operations on worksheet data. Formulas can perform
mathematical operations, such as addition and multiplication, or they can compare worksheet values.
Formulas can refer to constants, or other cells on the same worksheet. While using Ess in conjunction with
the physics labs, you will create your own formulas as well as use predefined formulas that are built-in to
the Ess program.

395
Spreadsheets

Fig 16.23 working of average calculations

Each formula is entered and edited on the formula bar, located near the top of the spread sheet. The
above image shows the formula bar encircled. As an example, the equation in the formula bar adds 25 to
the value in cell B4 and then divides the result by the sum of the values in cells D5, E5, and F5.
You can also use constants in your formulas. These constants can be numbers (2, 365 or 3.14159),
predefined constants (PI( ) or EXP(1)), or references to a constant defined within worksheet.
Ess contains many predefined, or built-in, formulas, which are known as functions. Functions can
be used to perform simple or complex calculations. The most frequently used function is the SUM func-
tion, which is used to add the numbers in a range of cells.
Ess to determine the thickness of one sheet of paper. Say we know that a ream of paper contains
500 sheets and is 4.895 cm thick. The thickness of a single sheet can be determined by dividing the total
thickness by the total number of sheets in the ream. Let’s utilize the spread sheet program by first record-
ing our known values, i.e., the total number of sheets and the total thickness. These are entered into
columns A and B, respectively, in the example below. The formula (=B2/A2) can then be entered in cell
C2. The worksheet example is shown below.

Fig 16.24 Display of decimals

Note that the cell containing the formula is highlighted and the equation is also printed and highlighted.
With any worksheet that you turn in to be graded, it is important that you highlight and print
your formulas so your TA can follow your steps and correct your mistakes.
Let’s say that we wish to know the distance traveled if you run around a football field six times. It is
given that the length of the field is 109.80 meters and its width is 48.80 meters. The distance traveled is
simply the field’s perimeter multiplied by the number of laps. The perimeter, of course, is the sum of the
distances of each side of the field, or Perimeter = (2 x Length) + (2 x Width). Therefore your worksheet
may look like the following:

396
Spreadsheets

eÁw

Fig 16.25 Display of multiplications

We can use the work in the above example to determine the number of miles which was run. The
conversion factor between meters and miles is 1 mile = 1609.3 meters. Therefore using this conversion
and the result from cell D2 in the above example, we can find the distance traveled in miles. The screen
shot below shows the formula used:

Fig 16.26 Display of multiplications

To determine the distance traveled if you ran, say, 12.5 laps, all you need to do is change the contents
of cell A2 from 6 to 12.5 and the distance is automatically recalculated for you! There is no need to alter
any of your formulas!
The general quadratic equation is given by ax2 + bx + c = 0. Its solution is, of course, the quadratic
formula, or

Say we are given the quadratic equation, , and we wish to find both of its solu-
tions. We can use Ess to help us do this and the screen shot below shows how that is done. (The spaces
within the formula were added to make the formula easier to read.)

Fig 16.27 Display of multiplications with sqrt()

397
Spreadsheets

Of course, to solve another quadratic equation, all one needs to do is change the values of the
constants a, b and c in cells A1, B1 and C1. There is no need to alter the formula and the new result is
given immediately after the new values are entered!
4 We will close this tutorial with one last example with which all should be familiar. You should know
that the volume of a sphere is given by the formula , where r is the sphere’s radius and ? =
3.14159. In this example, we are told that the volume of a basketball is 7200 cm3. Use Ess to determine
the radius of the ball. First, the equation must be rewritten as . The screen shot below shows
one way to use Ess to solve for the radius:

Fig 16.28 Display of multiplications and division

In the above example, we used the number 3.14159 to represent the constant ?. Ess has a built-in
constant, PI( ), which returns the value for ? when used in an Ess formula. Therefore, the equation for the
radius in the above example can be rewritten as shown below:

Fig 16.29 Display of pi()

Either method is fine to use. Some prefer to use the numerical value and some prefer to use the built-
in constant. The choice is yours.
Finally, let’s say, that we know the volumes of four other spheres and we would like to determine the
radii of these spheres. We could simply change the value of cell A2 in the above examples and determine
the radius of each sphere one at a time. Or we could type new formulas for each sphere. However the
best (and fastest) way to determine the radii of the remaining spheres is to use the copy and paste
functions that

FUNCTION DESCRIPTION EXAMPLE RETURN


VALUE()
DATE Returns the serial number of a particular =DATE(2013,3,29) 3/29/2013
date

DATEVALUE Converts a date in the form of text to =DATEVALUE(“2013/3/29”) 41362


a serial number

398
Spreadsheets

DAY Converts a serial number to a day of the =day(2013/03/29) 23


eÁw month
DAYS360 Calculates the number of days between =DAYS360(14,29,) 15
two dates based on a 360-day year
EDATE Returns the serial number of the date that =EDATE(29,3) 120
is the indicated number of months
before or after the start date

EOMONTH Returns the serial number of the last day =EOMONTH(29,3) 121
of the month before or after a specified
number of months

NOW Returns the serial number of the current =Now() 3/30/2013 8:37
date and time
TODAY Returns the serial number of today’s date 3/30/2013

YEAR Converts a serial number to a year =year(2013) 1905

Fig 16.29 Date and time functions

The Insert function dialog box will open. In search for a function box, you can enter a question that
describes what you want to do ( for example, searching for “Roman numbers” results in the function
Roman, which converts regular numbers into Roman numerals;
Financial functions :
“Loan payment” results in the function PMT, which calculates the payments of a loan with
interest) or in the or select a category box, you can browse from the categories.
The RATE Function
The RATE function returns the interest rate for an annuity.
Syntax
The syntax for the RATE function is:
RATE( number_payments, payment, PV, [FV], [Type], [Estimate] )
number_payments is the number of payments for the annuity.
payment is the amount of the payment made each period.
PV is the present value.
FV is optional. It is the future value. If this parameter is omitted, the RATE function assumes a FV
value of 0.
Payments are due at the beginning of the period.If the Type parameter is omitted, the RATE function
assumes a Type value of 0.
Payments are due at the beginning of the period.If the Type parameter is omitted, the RATE function
assumes a Type value of 0.
Type is optional. It indicates when the payments are due. Type can be one of the following values:

399
Spreadsheets

Value Explanation 0
Payments are due at the end of the period. (default) 1

Payments are due at the beginning of the period.If the Type parameter is omitted, the RATE function

A Descriptions

1 48 Number of periods (years, months, weeks..etc) 48

2 $550 Periodic payment $550

3 $24,000 Total amount of loan $24,000

4 0 The balance left to pay at the end of the period. If 0


you omit this argument Ess uses “0”.

5 0 Payment made at the beginning of the period (1) or 0


at the end of the period (0). If you omit this argu-
ment Ess uses “0” saying that the payment is made
at the end of each period which is usually the reality
when you borrow money.

6 5.00% The result with the formula using the RATE $4.75
function. =RATE(A1,-
Note: the format of this cell must be “Percent- A2,A3)*12*100
age” with any number of decimals. In this ex-

Fig 16.29 calculating Rate() function

Notes on the formula: The payment argument is negative (-A2); If you use months as periods
and you want an annual rate you multiply by 12, if you use a years as periods and you want an annual
rate you don’t multiply......; If you don’t use the “Percentage” format in cell A6 the result of this example
will be 0.05; The formula could also be =RATE(A1,-A2,A3)*12 the arguments in A4 and A5 being
optional
The PMT Function
The PMT function returns the payment amount for a loan based on an interest rate and a constant
payment schedule.
Syntax
The syntax for the PMT function is: PMT( interest_rate, number_payments, PV, [FV], [Type] )
interest_rate is the interest rate for the loan.
number_payments is the number of payments for the loan.
PV is the present value or principal of the loan.

400
eÁw A Descriptions

1 5.00% The annual interest rate.Note: the format of this 5.00%


cell must be “Percentage” with any number of
decimals. In this example the number of
decimals is 2
2 48 Number of periodic payments (years, months, 48
weeks)
3 24,000 Total amount of loan 24,000

4 0 The balance left to pay at the end of the period. If 0


you omit this argument Ess uses “0”.
5 0 Payment made at the beginning of the period (1) or 0
at the end of the period (0). If you omit this argu-
ment Ess uses “0” saying that the payment is made
at the end of each period which is usually the reality
when you borrow money.
6 -$550.41 The result with the formula using the PMT ($550.41)
function.

Fig 16.30 Calculating PMT() function

Here is the formula in cell A6:=PMT(A1/12,A2,A3,A4,A5)


Notes on the formula: If you don’t use the “Percentage” format in cell A1 enter 0.05; If you use months
as periods the rate must be divided by 12 (A1/12), if you use weeks then you divide by 52 (A1/52), if
there are 4 payments per year you will divide the rate by 4 (A1/4)and if the payment is annual you don’t
divide the rate argument (A1) ; The formula could also be =PMT(A1/12,A2,A3) the arguments in A4
and A5 being optional; If you want the payment to show as a positive value add a minus sign before the
equal sign (=-PMT(A1/12,A2,A3,A4,A5))

The FV Function (Future value)


The FV function returns the future value of an investment based on an interest rate and a constant
payment schedule.
Syntax
The syntax for the FV function is:
FV( interest_rate, number_payments, payment, [PV], [Type] )
interest_rate is the interest rate for the investment.
number_payments is the number of payments for the annuity.
payment is the amount of the payment made each period.

401
Spreadsheets

FV is optional. It is the future value or the loan amount outstanding after all payments have been made. If
this parameter is omitted, the PMT function assumes a FV value of 0.
Type is optional. It indicates when the payments are due. Type can be one of the following values:
Value Explanation 0
Payments are due at the end of the period. (default) 1

Explanation 0
Payments are due at the end of the period. (default) 1
Payments are due at the beginning of the period.
If the Type parameter is omitted, the FV function assumes a Type value of 0.
The question to which FV brings an answer to is:
- If I put a certain amount of money in the bank each month how much money will I have saved at
the end of a certain period of time?
Here is the formula in cell A6:=FV(A1/12,A2,A3,A4,A5)
Notes on the formula: If you don’t use the “Percentage” format in cell A1 enter 0.05; If
you use months as periods the rate must be divided by 12 (A1/12), if you use weeks then you divide
by 52 (A1/52), if there are 4 payments per year you will divide the rate by 4 (A1/4)and if the payment
is annual you don’t divide the rate argument (A1) ; The formula could also be =FV(A1/12,A2,A3) the
arguments in A4 and A5 being optional; If you want the RESULT to show as a positive value add a
minus sign before the equal sign (=-FV(A1/12,A2,A3,A4,A5))

The NPER Function

The NPER function returns the number of periods for an investment based on an interest rate and
a constant payment schedule.
Syntax
The syntax for the NPER function is:
NPER( interest_rate, payment, PV, [FV], [Type] )
interest_rate is the interest rate for the investment.
payment is the amount of the payment for each period. This should be entered as a negative value.
PV is the present value of the payments.
FV is optional. It is the future value that you'd like the investment to be after all payments have
been made. If this parameter is omitted, the NPER function will assume a FV of 0.
Type is optional. It indicates when the payments are due. Type can be one of the following values:
Value Explanation 0
Payments are due at the end of the period. (default) 1
Payments are due at the beginning of the period.
If the Type parameter is omitted, the NPER function assumes a Type value of 0.

402
Spreadsheets

PV is optional. It is the present value of the payments. If this parameter is omitted, the FV function
assumeseÁw
PV to be 0.
Type is optional. It indicates when the payments are due. Type can be one of the following values:
A Descriptions Value

1 5.0% The annual interest rate.Note: the format of this 5.0%


cell must be “Percentage” with any number of
decimals. In this example the number of deci-
mals is 2

2 $550 Periodic payment $550

3 $24,000 Total amount of loan $24,000

4 0 The balance left to pay at the end of the period. If 0


you omit this argument Ess uses “0”.
5 0 Payment made at the beginning of the period (1) or 0
at the end (0). If you omit this argument Ess uses
“0”.

6 48.26 The result with the formula using the NPER 48.26123273
function. =NPER(A1/12,-
a2,a3,a4,a5)

Fig 16.31 Calculating NPER() function

The question to which NPER brings an answer to is:


- How many months would it take me to repay a certain loan at a certain interest rate if I pay a certain
amount each month?
Here is the formula in cell A6:=NPER(D1/12,-D2,D3,D4,D5)
Notes on the formula: If you don’t use the “Percentage” format in cell A1 enter 0.05;
The second argument MUST BE NEGATIVE; If you use months as periods the rate must be
divided by 12 (A1/12), if you use weeks then you divide by 52 (A1/52), if there are 4 payments
per year you will divide the rate by 4 (A1/4)and if the payment is annual you don’t divide the rate
argument (A1) ; The formula could also be =NPER(A1/12,A2,A3) the arguments in A4 and A5 being
optional;

403
Spreadsheets

Logical Functions

Functions What it Does Function


AND Returns TRUE if all its arguments are TRUE =IF(AND(A1=1,A1<> 2),9,8)

IF Specifies a logical test to perform =IF(A1=1,9,8)

NOT Reverses the logic of its argument =IF(A1<> 100,9,8).

OR Returns TRUE if any argument is TRUE

Fig 16.32 List Logical function

You cannot use an IF formula to change the color of the font or of the cell’s background based on a
value (criteria). To do so you will use “ Conditional Formatting” .
When you develop a condition for an IF formula it is not case sensitive.
The basic IF formula looks like this =IF(condition,value if condition is True,value if condition is
False). So =IF(A1=1,9,8) in plain English means if the value of cell A1 is 1 the value in which this
formulas resides is 9 otherwise it is 8.
Remember that you cannot nest more than 7 IFs within the same formula. Nested IFs are IFs within
IFs like in =IF(A1> =90,”A” ,IF(A1> =80,”B” ,”C”). In other words if a condition is true you want to
test another condition in such cases we are talking about nested IFs. In plain English this formula says: if
the value of cell A1 is equal or higher than 90 the result in the cell where this formula resides is the capital
letter “A” , if the value in cell A1 is 80 or greater then the result is “B” else the result is “C” . Below you will
see a way to go around this limit.

IF, MOD, TRUNC and &


How many dozens are there in 106 units?
With the number of units in cell A1 the formulas in B1:
=TRUNC(A1/12,0) will return the number of complete dozens
this formula in C1:
=MOD(A1,12) will return the number of units left when the total number is divided by 12.

If you want to present the result as “ 8 dozens and 10 units” in a single cell you will use the following
formula combining math & Trig functions and the ampersand (& ) sign:
=TRUNC(A1/12) & “ dozens and “ & MOD(A1,12) & “ units”
But what if there are 96 units and you don’t want the result to show as “8 dozens and 0 units” but as
“8 dozens” . You will then use this formula:
=IF(MOD(A1,12)=0,TRUNC(A1/12) & “ dozens” ,TRUNC(A1/12) & “ dozens and “ &
MOD(A1 12) & “ units” )

404
Spreadsheets

IF, MOD, TRUNC and &


How manyeÁw dozens are there in 106 units?
With the number of units in cell A1 the formulas in B1:
=TRUNC(A1/12,0) will return the number of complete dozens
this formula in C1:
=MOD(A1,12) will return the number of units left when the total number is divided by 12.

If you want to present the result as “8 dozens and 10 units” in a single cell you will use the following
formula combining math & Trig functions and the ampersand (& ) sign:
=TRUNC(A1/12) & “ dozens and “ & MOD(A1,12) & “ units”
But what if there are 96 units and you don’t want the result to show as “ 8 dozens and 0 units” but as “
8 dozens” . You will then use this formula:
=IF(MOD(A1,12)=0,TRUNC(A1/12) & “ dozens” ,TRUNC(A1/12) & “ dozens and “ &
MOD(A1 12) & “ units” )

Statistical Functions

ESS functions in the “Statistical” MIN, MAX, SMALL, LARGE functionsCOUNTIFS,


AVERAGEIF and AVERAGEIFS.
Functions What it Does

AVERAGE Returns the average of its arguments

COUNT Counts how many numbers are in the list of arguments

AVERAGEA Returns the average of its arguments, including numbers, text, and logical values

COUNTA Counts how many values are in the list of arguments)

RANK Returns the rank of a number in a list of numbers

LARGE Returns the k-th largest value in a data set

SMALL Returns the k-th smallest value in a data set

New Functions in Ess 2007

405
Spreadsheets

AVERAGEIF Calculates the average within a range that meet a given criteria
(SUMPRODUCT does better)

AVERAGEIFS Calculates the average within a range that meet one or many
given criteria (SUMPRODUCT does better)

COUNTIFS Counts the number of nonblank cells within a range that meet the
given criteria (SUMPRODUCT does better)

LARGE, SMALL
And what if you want the second or third largest value or the second smallest value. Use LARGE and
SMALL like this:
=LARGE(A1:A5,2), =LARGE(A1:A5,3), =SMALL(A1:A5,2)
You can use these functions with dates.

As a matter of facts you can forget about MIN and MAX with:
=LARGE(A1:A5,1), =SMALL(A1:A5,1)

COUNT and COUNTA

If you want to count the number of cells that are not blank COUNT and COUNTA will return a
different result if in one of the cells there is a text. OR A SPACE
=COUNT(A1:A5) will return 5 is only numbers OR DATES are present in cells A1 to A5 and 4 if
there is a letter, an empty cell OR A SPACE in one of the cells. The SPACE thing is important to
remember when you are importing data from an external source.
=COUNTA(A1:A5) will return 5 unless one of the cells is empty. If all the cells contain numbers,
letters OR SPACES the result will be 5.

AVERAGE and AVERAGEA


Watch for dates! If you want the average of a range and there is a date within there is a problem
because dates are numbers. If all the cells are dates, indeed you can calculate the average date of.... The
difference between AVERAGE and AVERAGEA becomes evident when one of the cells contains a text
OR A SPACE and don’t forget the SPACE. A cell containing a space is NOT empty.

406
Spreadsheets

Fig 16.33 Difference calculating Rate() function

ToeÁw
Concatenate: To assemble strings of text. When you concatenate the result is always in text
format even if your are concatenating numbers.
For example: if you have 1 in cell A1 and 2 in cell A2 the formula =A1+A2 will return 3. If instead of
the plus sign (+) you use the ampersand (& ) the formula =A1 & A2 will return 13 because concatenating
is not adding it is creating a chain of characters with the content of many cells. The result 13 is not even a
number with which you could execute calculations it is a text just like Peter.
The TEXT functions in Ess are great “Time Saving” tools. When you have data that you receive from
colleagues, clients or suppliers, when you download data from a database or the Internet and the format
is not right for you, you need to RE-ENTER the data manually and this task is time consuming, error
prone and very frustrating. The TEXT functions will allow you to do the reformatting automatically.
I have developed hundreds of spreadsheets to convert data and make them usable within Ess. I have
also developed spreadsheets to convert large quantities of Ess data into a format uploadable in large
databases (Oracle, Sybase, SQL Server...) or ERP systems (JDEdwards, SAP, PeopleSoft, SmartStream...)
as batch files.
Ess is a great translator to move data from one system to the other. You download data from system
A, convert and either use it in Ess or upload in system B.

Basic Ess Formulas using TEXT Functions

CONCATENATE and the ampersand (& )


If you have “Karnataka “ in cell A1 and “State” in cell B1 the following formula in cell C1 will return
“Karnataka State” :
=CONCATENATE(A1,” “ ,B1)
With this formula you are telling Ess to assemble the content of cell A1, a space (between quotes) and
the content of cell C1.
a simpler way to get the same result:
=A1 & “ “ & B1
The ampersand (& ) is the sign used to tell Ess to concatenate strings of text. Most users prefer the
ampersand to the CONCATENATE function.

FIND or SEARCH
With “Karnataka State” in cell A1 the formula =FIND(“ “ ,A1) will return 9 because the space is the
ninth character from the left. This function is very useful to remove parts of a string of characters when
there is a constant within it. FIND and SEARCH perform the same task but FIND is case sensitive and
SEARCH is not.

LEFT, RIGHT, MID


If you have Karnataka State in cell A1 these formulas in cell B1 to B3:
=RIGHT(A1,2) will return “te”
=RIGHT(A1,5) will return “ State”
407
Spreadsheets

=LEFT(A1,2) will return “Ka”


=LEFT(A1,5) will return “Karna”
=MID(A1,10,3) will return “Sta” because you are asking Ess to extract 3 characters starting with the
seventh from the left.

LEN
The function LEN returns the number of characters in a string. Like many functions of the TEXT
category LEN is a function that is rarely used by itself The basic LEN formula looks like this:
=LEN(A1)
If cell A1 contains “Karnataka State” the answer will be 9, with “Karnataka State” the answer is 15
because the space is a character

REPT
The REPT function is indispensable when you want to upload a series a values that are in different
columns in Ess to an old database or to an A/S400 database. These databases and certain other
accounting programs have fixed width fields. For example the “ amount” field can be 10 characters
wide so even if the amount that you have is 3.35 (In cell A1) you need to upload 0000000335
=REPT(0,8) & A1 will return 0000000335

TEXT
=TEXT(A4,”@”) will return 3567 and you know that it works because the string although looking
like a number is aligned to the left of the cell. This function is particularly important when working with
numerical part numbers or account numbers specially with SUMPRODUCT and INDEX/
MATCH.

TRIM
=TRIM(A1) will return the same result “Peter Clark” with no space at the beginning or the end and a
single space in between. The TRIM function only removes what Ess considers as useless spaces.

VALUE
Sometimes when you download data from certain databases the numbers are in text format and you
cannot use them in calculations. You will use the following formula to resolve this
problem:=VALUE(A1)
assumes a Type value of 0.

The question to which RATE brings an answer to is:-


What is the real interest rate if they ask me for a certain amount each period to pay a loan?
Here is the formula in cell A6: =RATE(A1,-A2,A3,A4,A5)*12
Notes on the formula: The payment argument is negative (-A2); If you use months as
periods and you want an annual rate you multiply by 12, if you use a years as periods and you
want an annual rate you don’t multiply......; If you don’t use the “Percentage” format in cell A6 the result

408
Spreadsheets

Functions What it Does


eÁw
LEFT Returns the leftmost characters from a text value

LEN Returns the number of characters in a text string

MID Returns a specific number of characters from a text string starting at


the position you specify

RIGHT Returns the rightmost characters from a text value

TRIM Removes spaces from text

FIND Finds one text value within another (case-sensitive)

REPT Repeats text a given number of times

TEXT Formats a number and converts it to text

VALUE Converts a text argument to a number

Fig 16.32 List of TEXT function

DATA FORM
Data Form : Interaction of Data Base with ESS
Step 1: The data base which is existing in the data base / New database must be created using access.
Step 2: go to ESS -> data -> from access -> the fields will be inserted in the form of table
Step 3: Each columns will be the fields
Step 4: Each row will be the record –the records can be entered ie data entry
Step 5 :The fields can be data filtered.
Step 6: The table tools can be seen on top of the title Bar.

409
Spreadsheets

410
Spreadsheets

eÁw

The sorting, Data filters can be carried out using


the data from.
Any Database files can be accessed and the
reports can be obtained.
The Charts for the data field can be inserted.
Data validation is possible.
Data filed can be grouped.
Advanced features of locating of data, based on
criteria with the range can be generated.

Practical question
Step 1: Start -> program -> ESS
Step 2: Alt +F -> New
Step 3 : Enter the format of the sales for the month of three product under the columns, with the total
Step 4: Enter the details of amount and total is calculated by giving the formula=sum(c3:e3) rows
Step 5 : The individually product amount is calculated.=sum(c3:c10) columns.

The Graph can be generated by selecting the range/ wizard to help in navigation step by step.

411
Spreadsheets

Review Question
One mark questions :
1. Expand ESS?
2. What is a spread sheet?
3. What is a work sheet?
4. How many rows and columns are present in a worksheet?
5. What is cell?
6. What is cell address?
7. What is cell pointer?
8. What is the use of formula?
9. Give the formats of entering dates in a worksheet by default?
10. Why is the auto format option used?
11. How so we include a formula in a worksheet?
12. What is a chart ?
13. What is the advantage of using a chart wizard?

Two marks questions :


1. What is the purpose of using ESS?
2. How is ESS used in the Give any two features of spread sheet.
3. Explain the terms cell, cell address with suitable example.
4. What are the steps to activate ESS?
5. What are the types of data used in ESS?
6. Explain the steps used to add rows and columns to a worksheet.
7. What is the range of numbers possible in a worksheet with version?
8. Explain the steps used to change the size of rows and columns in a worksheet.
9. Explain the steps of using the auto format option.
10. Explain the use of any two mathematical functions with suitable examples.
11. Explain the use of any two statistical functions with suitable examples.
12. Explain the use of any two financial functions with suitable examples.
13. Explain the use of any two text functions with suitable examples.
14. Classify the types of graph ?
15. What is data Form ?

Three marks questions :


1. Give the area ESS is used in detail .
2. Give the features of a spreadsheets?
3. Explain the screen layout of a worksheet in detail .
4. Explain the options of the standard toolbar in detail.
5. Explain in detail the types of data and the range of values that can be used in a worksheet.
412
Spreadsheets

6. Explain the various options of the formatting toolbar.


7. Explain
eÁw the use of the various statistical functions with suitable example.
8. Explain the use of financial functions with suitable examples
9. Explain the steps involved in drawing a chart.
10. How can data form the other packages imported in ESS?

Five marks questions :


1. Explain the default alignments text and numerical with examples.
2. Illustrate with the an example to draw a line graph for five Indian cricket players runes in five test
matches?
3. Explain the sales of the iphones with the brand name and model number for this year
4. Classify various types of built in functions in ESS.
5. Explain the method of using built in functions in detail.
6. Explain with help of importing Data from database for the pollution in your city?

413
414
eÁw

CHAPTER 17
Web Designing

OBJECTIVES
To Understand the concepts of internet
To develop simple web applications

415
416
Web Designing

17.1 Introduction
In early
eÁw days we had only standalone computers. This confined the users to a single user environment
and when two people wanted to exchange information, they had to physically carry the data from place to
place. This actually gave a new scope to the programmers to make two computers to communicate with
each other to form computer network.
A computer network is an interconnection of autonomous computers for the purpose of
communication and data sharing. Two computers are said to be interconnected if they can exchange
information. The connection can be through copper wires, lasers, satellite communication, etc. irrespective
of the distance where these computers are located.

Figure 17.1 Internet

Therefore, internet is a collection of computer networks all over the world. Here hundreds of thousands
of computers are connected across hundreds of countries via telephone lines, fibre optic cables, satellites
and so on.

 A global computer network providing a variety of information and communication facilities,


consisting of interconnected networks using standardized communication protocols.
 According to ICT (Information and Communication Technology) the internet is world-wide
system of computer networks i.e. “network of networks” that consists of millions of smaller
domestic, academic, business, government networks, which together carry various information
and services, such as email, online chat, file transfer, search for information, e-Commerce,
online payment etc.

Every computer in the network is called a host .each host in the network can be identified uniquely by
what is called as an IP( Internet Protocol) address. The IP address is mapped on to Domain Name
System which is represented as www.google.com .The DNS is used instead of the IP address since it is
difficult to remember numbers but the DNS is any logical address which can be easily remembered. The
DNS is entered in the address bar of any browser.

417
Web Designing

A web browser is a software application that enables a user to display and interact with the images,
videos, music and other information typically located on a Web page at a website on the World Wide
Web (www) or a local area network. Some of the web browsers are internet explorer, Netscape Navi-
gator, Mozilla Firefox, etc. It is important to note that internet is not www (World Wide Web) and it is only
a part of the internet.

17.2 Services on the internet


In this world of information technology, there is no field which does not use the internet. In the field of
Science and technology, Military, Engineering, Banking, Multimedia, Medicine, Aviation, Education, Busi-
ness, Entertainment are some of the services to name a few. Here are some important services on the
internet listed below:
1. The world wide web:

Figure 17.2 world wide web

This is also called web or www or 3w. The collection of all web pages in all web sites on Internet is
called www. These web pages provide us information in the form of text, pictures, audio and video
formats etc.
2. E-mail:

Figure 17.3 E-mail

418
Web Designing

E-mail was one of the first uses of the Internet, and quickly became a popular feature because it lets
users exchange
eÁw
messages from anywhere in the world. Further, e-mail is less expensive than using the
telephone because there is no charges for using it other than the regular fees we pay to ISP (Internet
Service Provider). E-mail is also a faster way to communicate than postal mail because e-mail messages
typically reach their destination in seconds rather than days.
E-mail stands for electronic mail. It is the most popular, cheap, easy and fastest mailing service. We
can send and receive messages on internet with- in seconds or minutes. Let us understand more about this
in detail.
The only Internet service that is more frequently used than the Web is electronic mail. Electronic
mail, or e-mail, is a system for exchanging messages through a computer network. People most com-
monly use e-mail to send and receive text messages, but depending on the software we use, we may be
able to exchange audio or video messages with someone else.
There are numerous benefits of using an email service. The different advantages of email are as fol-
lows:
1. Easy to use: Sending an email frees us from the tedious task of managing data for daily use. It
helps us manage our contacts, send mails quickly, maintain our mail history, store the required information,
etc.
2. Speed: An email is delivered instantly and anywhere across the globe. No other service matches
the email in terms of speed. We can send the same message/mail to multiple users simultaneously; thus, a
lot of time is saved.
3. Easy to prioritize: Since emails come with a subject line, it is easy to prioritize them and ignore the
ones that are unwanted.
4. Reliable and secure: Constant efforts are taken to improve the security in electronic mails. It
makes the email one of the secured ways of communication.
5. Informal and conversational: The language used in emails is generally simple and thus, makes the
process of communication informal. Sending and receiving emails takes less time, so it can be used as a
tool for interaction.
6. Easier for reference: It is possible to reply to a mail by attaching previous mails as references. It
helps refresh the recipient’s know-how on what he/she is reading.
7. Automated emails: It is possible to send automated emails using special programs like the auto
responders. The auto responders reply only to those messages with a generalized, pre-written text.
8. Environment friendly: Postal mails use paper as a medium to send letters. Electronic mail there-
fore, prevents a large number of trees from getting axed. It also saves the fuel needed for transportation.
9. Use of graphics: Colorful greeting cards and interesting pictures can be sent through emails. It
adds value to the email service.
10. Advertising tool: Nowadays, many individuals and companies are using the email service to
advertise their products, services, etc.

419
Web Designing

11. Cheap Service: The expenses incurred in using an email service are less. However, it also
depends on whether you have an Internet connection at home.
12. Data Storage: The providers of email service offer enough space for data storage. Also, the
process of sorting and arranging mails as per the subject, date, etc. is made quite easy for users.
13. Provision of Attachments: The feature of attachments allows users to send huge chunks of
data in the same mail. Also, sending attachments doesn’t raise the cost as in the postal service.
The advantages of internet are unlimited and even beyond the scope of author’s thinking capability.
Every concept will have both advantages and disadvantages. But it is important to adopt that if the advan-
tages are more compared to disadvantages.

Disadvantages of Email:
The email service, though beneficial in our day-to-day life, has its own drawbacks that are off late
coming to the fore.
1. Viruses: These are computer programs which have the potential to harm a computer
system. Viruses copy themselves and further infect the computer. Recipients need to scan the
mails since; viruses are transmitted through them(mail) and have the potential to harm computer
systems.
2. Spam: Emails when used to send unsolicited messages and unwanted advertisements create
nuisance and are termed as spam. Checking and deleting the unwanted mails can unnecessarily
consume a lot of time. It has therefore, become necessary to block or filter unwanted emails by
means of spam filters. Spamming is practiced by sending hoax emails. Email spoofing .It is
another common practice, used for spamming. The act of spoofing involves deceiving the recipi-
ent by altering email headers or addresses from which the mail is sent.
3. Hacking: The act of breaking into computer security is termed as hacking. In this form of
security breach, emails are intercepted by hackers. An email, before it is delivered to the
recipient, “bounces” between servers located in different parts of the world; hence, it can be
hacked by a professional hacker.

3. Email discussion group:


These are used to discuss different topics with other people by email.

420
Web Designing

4. Newsgroups:
eÁw

Figure 17.4 Newsgroups

Newsgroups are discussion groups on internet. They are used for free exchange of information. A
user sends a message to the news group site. Other users read this message from this site and reply.
Newsgroups are provided by special computers called news servers.

5. Ecommerce:

Figure 17.5 Ecommerce


It stands for Electronic Commerce. E-commerce means to carry out business dealings by internet.
Examples of Ecommerce include: Online Banking, Online shopping and online education etc.

6. FTP:
FTP stands for file transfer protocol. It is used to transfer files on internet easily and quickly. Audio,
video, graphics and data files can be uploaded and downloaded using FTP.

421
Web Designing

7. Telnet or remote login:

Figure 17.6 Telnet

This program is used to access a remote computer on internet as shown in the figure 17. . You can
access data and files from connected computer by Telnet. Telnet may also provide you a user interface on
screen. You will give commands to remote computer by this user interface.

8. Chat:

Figure 17.7 chat

It is the most popular services by which two or more users can live chat with each other. We can chat
by text or audio or video. Voice chat is just like talking on telephone. Messenger software like chat for
google is as shown figure 17.7. Yahoo messenger or MSN messenger is used for chatting.

9. Gopher:

Figure 17.8 Gopher

422
Web Designing

A gopher on the Internet is a system for users to search for files via menus or directory structures. It
uses plain
eÁw
English names and is text based only.

17.3 Some terms related to web

1. World Wide web (www or 3w)


In September 1994, Berners-Lee founded the World Wide Web Consortium (W3C) at the Massa-
chusetts Institute of Technology with support from the Defense Advanced Research Projects Agency
(DARPA) and the European Commission. It comprised various companies that were willing to create
standards and recommendations to improve the quality of the Web. Berners-Lee made the Web available
freely, with no patent and no royalties due. The W3C decided that its standards must be based on royalty-
free technology, so they can be easily adopted by anyone.
By the end of 1994, while the total number of websites was still minute compared to present stan-
dards, quite a number of notable websites were already active, many of which are the precursors or
inspiring examples of today’s most popular services.
The World Wide Web (“WWW” or simply the “Web”) is a global information medium which users
can read and write via computers connected to the internet.
Or
The term WWW refers to the World Wide Web or simply the Web. The World Wide Web consists
of all the public Web sites connected to the Internet worldwide, including the client devices (such as
computers and cell phones) that access Web content. The WWW is just one of many applications of the
Internet and computer networks.
The term is often mistakenly used as a synonym for the internet itself, but the Web is a service
that operates over the Internet, just as e-mail also does. The history of the internet dates back significantly
further than of the World Wide Web.

2. Web Page
A web page is a web document or other web resource that is suitable for the World Wide Web and
can be accessed through a web browser and displayed on a monitor or mobile device. This information is
usually in HTML or XHTML format, and may provide navigation to other web pages via hypertext links.
Web pages frequently subsume other resources such as style sheets, scripts and images into their final
presentation.
Web pages may be retrieved from a local computer or from a remote web server. The web server
may restrict access only to a private network, e.g. a corporate intranet, or it may publish pages on the
World Wide Web. Web pages are requested and served from web servers using Hypertext Transfer
Protocol (HTTP).
Web pages may consist of files of static text and other web content stored within the web server’s file
system (static web pages), or may be constructed by server-side software when they are requested
(dynamic web pages). Client-side scripting can make web pages more responsive to user input once on
the client browser.
423
Web Designing

Web pages usually include information as to the colours of text and backgrounds and very often also
contain links to images and sometimes other types of media to be included in the final view.
A webpage is a document, typically written in plain text interspersed with formatting instructions of
Hypertext Markup Language (HTML, XHTML). A webpage may incorporate elements from other
websites with suitable markup anchors.
Web pages are accessed and transported with the Hypertext Transfer Protocol (HTTP), which may
optionally employ encryption (HTTP Secure, HTTPS) to provide security and privacy for the user of the
webpage content. The user’s application, often a web browser, renders the page content according to its
HTML markup instructions onto a display terminal.

3. Website
A website is a collection of web pages (documents that are accessed through the Internet. A web
page is what we see on the screen when we type in a web address, click on a link, or put a query in a
search engine. A web page can contain any type of information, and can include text, color, graphics,
animation and sound.
A website is a set of related web pages served from a single web domain. A website is hosted on at
least one web server, accessible via a network such as the Internet or a private local area network through
an Internet address known as a Uniform Resource Locator. All publicly accessible websites collectively
constitute the World Wide Web.
The pages of a website can usually be accessed from a simple Uniform Resource Locator (URL)
called the web address. The URLs of the pages organize them into a hierarchy, although hyper linking
between them conveys the reader’s perceived site structure and guides the reader’s navigation of the site
which generally includes a home page with most of the links to the site’s web content, and a supplemen-
tary about, contact and link page.

4. Web browser

Figure 17.9 Web browser

424
Web Designing

The first web browser was invented in 1990 by Sir Tim Berners-Lee. It was called Worldwide Web
(no spaces)
eÁw
and was later renamed Nexus.
A web browser (commonly referred to as a browser) is a software application for retrieving, pre-
setting and traversing information resources on the World Wide Web. An information resource is identi-
fied by a Uniform Resource Identifier (URI) and may be a web page, image, video or other piece of
content. Hyperlinks present in resources enable users easily to navigate their browsers to related re-
sources. A web browser can also be defined as an application software or program designed to enable
users to access, retrieve and view documents and other resources on the Internet.

5. http

Figure 17.10 http

The term Hyper Text was coined by Ted Nelson. Berners-Lee and his team are credited with
inventing the original HTTP along with HTML and the associated technology for a web server and a text-
based web browser.
The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collabora-
tive, hypermedia information systems. HTTP is the foundation of data communication for the World Wide
Web. It is a multi-linear set of objects, building a network by using logical links (the so-called hyperlinks)
between the nodes (e.g. text or words). HTTP is the protocol to exchange or transfer hypertext.

6. Domain name system


The Domain Name System (DNS) is a hierarchical distributed naming system for computers,
services, or any resource connected to the Internet or a private network. It associates various information
with domain names assigned to each of the participating entities. Most prominently, it translates easily
memorized domain names to the numerical IP addresses needed for the purpose of locating computer
services and devices worldwide and hence provides a worldwide, distributed keyword-based redirection
service
425
Web Designing

The Domain Name System can be visualized as a phone book for the Internet by translating human-
friendly computer host names into IP addresses. For example, the domain name www.example.com
translates to the addresses 192.0.43.10 (IPv4). Unlike a phone book, the DNS can be quickly updated,
allowing a service’s location on the network to change without affecting the end users, who continue to
use the same host name. Users take advantage of this when they use meaningful Uniform Resource
Locators (URLs) and e-mail addresses without having to know how the computer actually locates the
services.

7. Uniform resource Locator (URL)


It is also known as web address, is a specific character string that constitutes a reference to a
resource. In most web browsers, the URL of a web page is displayed on top inside an address bar. An
example of a typical URL would be “http://www.example.org/bharath/Main_Page.html”. A URL is tech-
nically a type of uniform resource identifier (URI), but in many technical documents and verbal discus-
sions, URL is often used as a synonym for URI.

8. Search Engines
Aweb search engine is software code that is designed to search for information on the World Wide
Web. The search results are generally presented in a line of results often referred to as Search Engine
Results Pages (SERPs). The information may be a specialist in web pages, images, information and other
types of files. Some search engines also mine data available in databases or open directories. Unlike web
directories, which are maintained only by human editors, search engines also maintain real-time informa-
tion by running an algorithm on a web crawler. Some of the most commonly used search engines include
ask, aol, yahoo, google, Baidu, Bing, yandesk, ASK, AOL.

9. Surfing on the Internet


It means to move from place to place on the internet searching for topics of interest. Web surfing has
become a favorite pastime for many internet users. The links on each page enable you to start virtually
anywhere on the Web and eventually find interesting pages.
The term surfing is generally used to describe an unidirectional type of web browsing in which the
user jumps from page to page rather whimsically, as opposed to specifically searching for specific infor-
mation.

17.4 Introduction to HTML


HTML is a language for describing web pages. It stands for Hyper Text Markup Language. A
markup language is a set of markup tags. The tags describe document content and these documents
contain tags and plain text. The HTML documents are also called web pages.
HTML markup tags are usually called HTML tags. These tags are keywords (tag names) surrounded
by angle brackets like <html>. They normally come in pairs like <b> and </b>. The first pair of tags is the
start tag and the second tag is the end tag and end tag contains a forward slash before the tag name. Start
and end tags are also called opening tags and closing tags. The HTML tags are also called as the
HTML elements. The general form is as shown below.

426
Web Designing

<tagname> content </tagname>


Now
eÁwlet us understand about the general HTML Page Structure. Below figure17.11 gives a visual-
ization of an HTML page structure:

<html>
<body>

<h1>This a heading block</h1>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

Figure 17.11 Structure of a HTML page

<!DOCTYPE html> Defines the document type


<html> Describes the web page
<body> Is the visible page content

<h1>My First Heading</h1> Is displayed as a heading


<p>My first paragraph.</p> Is displayed as a paragraph
<p>This is another paragraph.</p> Is displayed as another
paragraph

</body>
</html> Figure 17.12 Example of HTML page

Figure 17.12 explains about example and generally these html tags are edited in a any text editor or
notepad. It is important to save these HTML pages by giving the extension as “.html”. To open the
notepad the following steps has to be followed. Select
Start  All programs  Accessories  Notepad
The next step is to open this file in any browser in order to have the resultant view of the final web
page. The figure 17.13 describes the content of the web page. To view the web page, Start your web
browser and open your html file from the File, Open menu, or just browse the folder and double-click
your HTML file.

427
Web Designing

Figure 17.13 Web Page

17.5 Basic Tags


<html>: This element defines the whole HTML document. The element has a start tag <html> and
an end tag </html>.The element content is another HTML element (the body element).
<body> : This element defines the body of the HTML document. This element has a start tag
<body> and an end tag </body>.The element content is another HTML element (a p element).
<p>: This element defines a paragraph in the HTML document. The element has a start tag <p> and
an end tag </p>.The element content is: This is my first paragraph.
<head>: This element is displayed in title bar of the browser as a part of the browser’s window.
<title>: The title appears in the title bar on top of the browser’s window. .This element also has a
start tag <title> and an end tag </title>. This contains the document title explains the content of the web
page on the whole.
<headings>: There are six levels of headings starting from h1 through h6. This tag makes the font
size of the text to appear larger and bolder at different levels. These tags can be used as headings,
subheadings, sections and sub sections as shown in web program1 below.

428
Web Designing

Web Program 1: Design a web page to demonstrate the headings.


eÁw
<!DOCTYPE html>

<html>

<body>

<h1>My First Heading</h1>

<h2>My Second Heading</h2>

<h3>My Third Heading</h3>

The resultant web page after opening this in the web browser appears as shown in figure 7.14.

Figure 17.14 Demonstration of Headings

17.6 Formatting tags


1. <b>: Defines bold text. It makes the data to appear as thicker and darker.
Example 17.1
<b> VIRTUAL MEMORY </b>
displays
VIRTUAL MEMORY
2. <i>: Defines italicized text. It makes the data to appear as italic.

Example 17.2:
<i> VIRTUAL MEMORY </i>
displays
VIRTUAL MEMORY
429
Web Designing

3. <u>: Defines underlined word. It makes the data to be underlined.

Example 17.3:
<u> VIRTUAL MEMORY </u>
displays
VIRTUAL MEMORY
4. <br>: Defines a single line break. Use the <br> tag to enter line breaks, not to separate
paragraphs.<br> tag is useful for writing addresses or poems.
Example 17.4:
HTML <br> XHTML<br>DHTML<br>
displays
HTML
XHTML
DHTML
5. <a>: This tag defines a hyperlink, which is used to link from one page to another. The most
important attribute of the <a> element is the href attribute, which indicates the link’s destination. By
default, links will appear as follows in all browsers:
 An unvisited link is underlined and blue
 A visited link is underlined and purple
 An active link is underlined and red
 Example 17.4:
<a href= “path”> link </a>
displays
this respective website
6. <img>: The <img> tag defines an image in an HTML page. The <img> tag has two required
attributes: src(Specifies the URL of an image) and alt(Specifies an alternate text for an image).
Note that images are not technically inserted into an HTML page, images are linked to HTML pages.
The <img> tag creates a holding space for the referenced image.
To link an image to another document, simply nest the <img> tag inside <a> tags but, <img> has no
end tag.

17.7 Lists in HTML


The <li> tag defines a list item. They are of three types and they are:
The <li> tag is used in ordered lists (<ol>)
The (<ul> ) tag is used in unordered lists (<ul>)
The (<dl>) tag is used in ordered lists (<dl>)

430
Web Designing

17.8 Some additional tags and simple programs


eÁw
<ol>

<li>Coffee</li>

<li>Tea</li>

<li>Milk</li>

</ol>

<ol start="5">
The resultant web page after opening this in the web browser appears as shown in figure 7.15.

Figure 17.15 List web page

431
Web Designing

The resultant web page after opening this in the web browser appears as shown in figure 7.16.

<!DOCTYPE html>

<html>

<body>

<ul>
<li> CHARLES BABBAGE
<li> LADY ADA LOVE LACE
<li> HERMAN HOLLERITH
</ul>
</body>
</html>

Figure 17.16 unordered list

432
Web Designing

<!DOCTYPE html>
<html>
eÁw
<head>
<title>P U DEPARTMENT</title></head>
<body>
<h1><center> MY COLLEGE</h1></center>
<p><h3><center> Most prestigious institutions in KARNATAKA.<bR>
Has been a pioneer in the field of education, for many years, excellency <br> in imparting quality
knowledge.</center><br></p>

<p><center> Courses offered here includes <BR>


science,<Br> commerce,<br> arts courses. </center><br></h3></p>

</body>
<marquee direction="right"> Admission for the Eligilble STUDENTS </marquee>

</html>

The resultant web page after opening this in the web browser appears as shown in figure 7.17.

Fig- ure
7.17 Web page of your college using minimum five tags

433
Web Designing

<!DOCTYPE html>

<html>

<head>

<title> To display an image</title></head>

<body>

<h1><center><imgsrc="C:\Users\Public\Pictures\Sample
Pictures\Penguins.jpg" align="top"><br> IMAGE DEMONSTRATION</h1></center>

<p><h3><center> The image can be placed anywhere in the screen according to our
convenience. </center><br></p>

The resultant web page after opening this in the web browser appears as shown in figure 7.18.

Figure 7.18 Image on the web page

434
Web Designing

The following table 17.1are the list of tags supported by HTML5.


eÁw
Tag Description

<!—...—> Defines a comment


<!DOCTYPE> Defines the document type
<a> Defines a hyperlink
<abbr> Defines an abbreviation
<address> Defines contact information for the author/owner ofa document
<audio> New Defines sound content
<b> Defines bold text
<bdi> New Isolates a part of text that might be formatted in a different
direction from other text outside it
<body> Defines the document’s body
<br> Defines a single line break
<button> Defines a clickable button
<caption> Defines a table caption
<center> Not supported in HTML5. Deprecated in HTML 4.01.
Defines centered text
col> Specifies column properties for each column within a <colgroup> element
<datalist>New Specifies a list of pre-defined options for input controls
<dd> Defines a description of an item in a definition list
<dialog>New Defines a dialog box or window
<div> Defines a section in a document
<dl> Defines a definition list
<dt> Defines a term (an item) in a definition list
<em> Defines emphasized text
<figure> New Specifies self-contained content
<font> Not supported in HTML5. Deprecated in HTML
4.01. Defines font, color, and size for text
<footer>New Defines a footer for a document or section
<form> Defines an HTML form for user input
<frame> Not supported in HTML5. Defines a window (a frame) in a frameset
<h1> to <h6> Defines HTML headings
<head> Defines information about the document
<header> ew Defines a header for a document or section
<hgroup> New Groups heading (<h1> to <h6>) elements'
<hr> Defines a thematic change in the content

435
Web Designing

Tag Description

<html> Defines the root of an HTML document


<i> Defines a part of text in an alternate voice or mood
<img> Defines an image
<input> Defines an input control
<label> Defines a label for an <input> element
<li> Defines a list item
<link> Defines the relationship between a document and an external resource
(most used to link to style sheets)
<map> Defines a client-side image-map
<mark> New Defines marked/highlighted text
<menu> Defines a list/menu of commands
<object> Defines an embedded object
<ol> Defines an ordered list
<p> Defines a paragraph
<pre> Defines preformatted text
<q> Defines a short quotation
<s> Defines text that is no longer correct
<script> Defines a client-side script
<section> New Defines a section in a document
<select> Defines a drop-down list
<small> Defines smaller text
<source> New Defines multiple media resources for media elements (<video> and <audio>)
<span> Defines a section in a document
<style> Defines style information for a document
<sub> Defines subscripted text
<table> Defines a table
<tbody> Groups the body content in a table
<td> Defines a cell in a table
<th> Defines a header cell in a table
<time> New Defines a date/time
<title> Defines a title for the document
<tr> Defines a row in a table
<track>New Defines text tracks for media elements (<video> and <audio>)
<u> Defines text that should be stylistically different from normal text
<ul> Defines an unordered list
<video> New Defines a video or movie
Table 17.1 HTML tags list

436
Web Designing

Review questions
eÁw
One mark questions :
1. Define internet.
2. Define browser.
3. Mention any two services of the internet.
4. What is world wide web?
5. What is e-mail?
6. Mention any one advantage of e-mail.
7. Mention any one disadvantage of e-mail.
8. What is virus?
9. What is spam?
10. What is hacking?
11. What are newsgroup?
12. What is e-commerce?
13. What is chatting?
14. What is a gopher?
15. What is telnet?
16. Expand FTP.
17. What is FTP?
18. What is a webpage?
19. What is a website?
20. What is http?
21. Expand http.
22. What is DNS?
23. Expand DNS.
24. What is URL?
25. Expand URL.
26. What are search engines?
27. What is surfing of net?
28. Expand HTML.
29. Mention any two tags in HTML.
30. Which tag is used to display a list?

Two marks questions:


1. Briefly explain internet.
2. Mention any four services of internet.
3. Explain www and email.

437
Web Designing

4. Mention any two advantages of e-mail.


5. Mention any one disadvantages of e-mail.
6. Briefly explain FTP and Telnet.
7. Briefly explain chatting and gopher.
8. Briefly explain www
9. Briefly explain webpage.
10. Briefly explain web browser.
11. Briefly explain http.
12. Briefly explain DNS.
13. Briefly explain URL.
14. Briefly explain search engine.
15. Briefly explain surfing.
16. Briefly explain HTML.
17. Explain any two tags in HTML.
18. Explain any two formatting tags in HTML.
19. Explain lists in HTML.
20. Which tag is used for hyperlink?

Three marks questions:


1. Explain any four services of internet.
2. Explain any four benefits of email.
3. Explain the disadvantages of email.
4. Explain www and webpage in detail.
5. Explain website and web browser.
6. Explain http and DNS.
7. Explain URL and search engines.
8. Explain the structure of a HTML tag page.
9. Explain the basic tags in HTML .
10. Explain the formatting tags in HTML.

Five marks questions :


1. Explain in detail the services of internet.
2. Explain the various benefits of email.
3. Explain some important terms in web technology.
4. Explain the structure of a HTML tag page with and example.
5. Explain the basic tags in HTML .
6. Explain the formatting tags in HTML.
7. Design a web page to demonstrate the ordered lists.
8. Design a web page to display your details on a web page.

438
MODEL QUESTION PAPER
eÁw
FIRST PUC - COMPUTER SCIENCE

Time: 3 Hours 15 minutes Max. marks: 70

PART –A

Note: Answer all the following questions:

Each question carries ONE mark. 1x10=10

1. Which is the earliest computing machine?


2. Who is called the father of computers?
3. What are the steps involved in problem solving?
4. Mention the rules for drawing flowcharts.
5. What is OOP?
6. Define bottom-up approach.
7. What is inheritance?
8. Mention any two unary operators.
9. Define an array.
10. How to convert data to bold using formatting tool bar.
PART –B
Note:Answer any five of following questions:
Each question carries TWO marks. 2x5=10

11 Mention any two features of EDVAC.


12 Compare the differences between static and dynamic RAM.
13 Write a note on testing and debugging.
14 Mention the advantages of OOPs?
15 Explain the input operator in C++.
16 Give the structure of a function.
17 Mention any two advantages of Email.
18 What are headers and footers in word processor?
PART –C
Note: Answer any five of following questions:
Each question carries three marks. 5x3=15
19. Explain the generations of computers.
20. Subtract 36 from 83 using 2’s compliment method.
21. Explain the question concept of structured programming.
22. Explain any four characteristics of C++.
23. Write a C++ program to find the sum of n natural numbers.
24. Give the creation of structure with an example.

439
25. How do you initialize one dimensional array?
26. Declare a structure that contains the data of a student?
PART –D
Note: Answer any seven of following questions:
Each question carries FIVE marks. 7x5=35
27. Explain the storage medium.
28. Evaluate BEAD16 to Octal, binary and decimal.
29. Illustrate divide and conquer method with an example
30. Explain the difference between while and do-while structures. Give example.
31. What are the advantages and disadvantages of OOPs?
32. Explain the various tokens of C++.
33. Write a C++ program to convert the temperature from Fahrenheit to Celsius.
34. Write a C++ program to find product of two compatible matrices.
35. Explain any five functions of the header string.h.
36. Define mail-merge. Explain mail-merge steps to invite four of your friends on the eve of your
birthday.
37. Design a web page to display your details using HTML tags?

*****

440
FIRST PUC ANNUAL EXAMINATION
FEBRUARY – 2014 Bangalore (North )
eÁw COMPUTER SCIENCE
TIME: 3 Hours 15 minutes Max.marks: 70

PART - A
Note: Answer all the questions:
Each question carries one mark. 10 x 1 = 10
1. Which is the earliest computing machine?
2. Give an example for non-impact printer.
3. What is syntax error?
4. Define keyword.
5. What is the extraction operator in C++.
6. What is the purpose of break statement?
7. Name the data types of the array subscript.
8. Define actual arguments.
9. Name any two word processors.
10. What is a worksheet?

PART - B
Note: Answer any five questions:
Each question carries two marks. 5 x 2 = 10
11. How are computers important in communication?
12. Compare static RAM and dynamic RAM.
13. Define the terms multiprogramming and multitasking.
14. Mention any two advantages of flowchart.
15. Write any two characteristics of OOP.
16. What are variables? Give its declaration syntax.
17. Explain any two character based functions.
18. What headers and footers in word processor?

PART - C
Note: Answer any five questions:
Each question carries three marks. 5 x 3 = 15
19. Give the application of OCR, OMR, MICR devices.
20. Explain the features of UNIX operating system.
21. Define a. testing b. Debugging c. Top-down analysis
22. Write an algorithm to find largest of three numbers.
23. Explain the different relational operators with examples.
24. What is cascading of input and output operators? Explain with suitable examples.
25. What is syntax and examples of initialization of two dimensions array?
26. How is structure defined? Write syntax and examples.

PART - C
Note: Answer any five questions:
Each question carries three marks. 5 x 3 = 15
27. Explain the characteristics of computers in detail
28. Solve: FEAD (16) = ?(10) = (?)2 = (?)8
29. What is structured programming? Mention its advantages.
30. Draw a flowchart to find the factorial of a number.
31. Explain the structure of C++ program with an example.
32. Write a C++ program to find the position of a given number in an array.
33. Explain the working of switch statement with an example.
34. Explain the working of for statement with a programming example.
35. What is recursive function? Explain with a programming example.
36. Mention the features of spreadsheets.
37. Explain any five tags of HTML.
******

441
Appendix I

ASCII Excess
Decimal Binary SYMBOL Octal Hex BCD EBCDIC 3 code
0 0 NUL 0 0 0000 11110000 0011
1 1 SOH 1 1 0001 11110001 0100
2 10 STX 2 2 0010 11110010 0101
3 11 ETX 3 3 0011 11110011 0110
4 100 EOT 4 4 0100 11110100 0111
5 101 ENQ 5 5 0101 11110101 1000
6 110 ACK 6 6 0110 11110110 1001
7 111 BEL 7 7 0111 11110111 1010
8 1000 BS 10 8 1000 11111000 1011
9 1001 HT 11 9 1001 11111001 1100
10 1010 LF 12 00A
11 1011 VT 13 00B
12 1100 FF 14 00C
13 1101 CR 15 00D
14 1110 SO 16 00E
15 1111 SI 17 00F
16 10000 DLE 20 10
17 10001 DC1 21 11
18 10010 DC2 22 12
19 10011 DC3 23 13
20 10100 DC4 24 14
21 10101 NAK 25 15
22 10110 SYN 26 16
23 10111 ETB 27 17
24 11000 CAN 30 18
25 11001 EM 31 19
26 11010 SUB 32 01A
27 11011 ESC 33 01B
28 11100 FS 34 01C
29 11101 GS 35 01D
30 11110 RS 36 01E
31 11111 US 37 01F
32 100000 SP 40 20
33 100001 ! 41 21
34 100010 " 42 22
35 100011 # 43 23
36 100100 $ 44 24
37 100101 % 45 25

442
38 100110 & 46 26
eÁw
39 100111 ' 47 27
40 101000 ( 50 28
41 101001 ) 51 29
42 101010 * 52 02A
43 101011 + 53 02B
44 101100 , 54 02C
45 101101 - 55 02D
46 101110 . 56 02E
47 101111 / 57 02F
48 110000 0 60 30
49 110001 1 61 31
50 110010 2 62 32
51 110011 3 63 33
52 110100 4 64 34
53 110101 5 65 35
54 110110 6 66 36
55 110111 7 67 37
56 111000 8 70 38
57 111001 9 71 39
58 111010 : 72 03A
59 111011 ; 73 03B
60 111100 < 74 03C
61 111101 = 75 03D
62 111110 > 76 03E
63 111111 ? 77 03F
64 1000000 @ 100 40
65 1000001 A 101 41
66 1000010 B 102 42
67 1000011 C 103 43
68 1000100 D 104 44
69 1000101 E 105 45
70 1000110 F 106 46
71 1000111 G 107 47
72 1001000 H 110 48
73 1001001 I 111 49
74 1001010 J 112 04A
75 1001011 K 113 04B
76 1001100 L 114 04C
77 1001101 M 115 04D
78 1001110 N 116 04E
79 1001111 O 117 04F

443
80 1010000 P 120 50
81 1010001 Q 121 51
82 1010010 R 122 52
83 1010011 S 123 53
84 1010100 T 124 54
85 1010101 U 125 55
86 1010110 V 126 56
87 1010111 W 127 57
88 1011000 X 130 58
89 1011001 Y 131 59
90 1011010 Z 132 05A
91 1011011 [ 133 05B
92 1011100 \ 134 05C
93 1011101 ] 135 05D
94 1011110 ^ 136 05E
95 1011111 _ 137 05F
96 1100000 ` 140 60
97 1100001 a 141 61
98 1100010 b 142 62
99 1100011 c 143 63
100 1100100 d 144 64
101 1100101 e 145 65
102 1100110 f 146 66
103 1100111 g 147 67
104 1101000 h 150 68
105 1101001 i 151 69
106 1101010 j 152 06A
107 1101011 k 153 06B
108 1101100 l 154 06C
109 1101101 m 155 06D
110 1101110 n 156 06E
111 1101111 o 157 06F
112 1110000 p 160 70
113 1110001 q 161 71
114 1110010 r 162 72
115 1110011 s 163 73
116 1110100 t 164 74
117 1110101 u 165 75
118 1110110 v 166 76
119 1110111 w 167 77
120 1111000 x 170 78
121 1111001 y 171 79

444
122
eÁw 1111010 z 172 07A
123 1111011 { 173 07B
124 1111100 | 174 07C
125 1111101 } 175 07D
126 1111110 ~ 176 07E
127 1111111 DEL 177 07F

445
Practical problem 1.a

Write a C++ program to interchange the values of two variables using a third variable.

1. INPUT a, b
2. temp = a
a=b
b =temp
3. OUTPUT a, b
4. STOP

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
int a, b, temp;
clrscr();
cout<<“Enter two numbers: “;
cin>>a>>b;
cout<<“Before interchanging: a = “<<a<<“\tb= “<<b<<endl;
temp = a;
a = b;
b = temp;
cout<<“After interchanging: a = “<<a<<“\tb= “<<b<<endl;
getch();
}

Sample run: Enter two numbers: 50 100


Before interchanging: a = 50 b= 100
After interchanging: a = 100 b= 50

446
Practical problem 1.b

Write a eÁw
C++ program to interchange the values of two variables without using a third variable.

1. INPUT a, b
2. a=a+b
b=a-b
a=a-b
3. OUTPUT a, b
4. STOP

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
int a, b, temp;
clrscr();
cout<<“Enter two numbers: “;
cin>>a>>b;
cout<<“Before interchanging: a = “<<a<<“\tb = “<<b<<endl;
a = a + b;
b = a - b;
a = a - b;
cout<<“After interchanging: a = “<<a<<“\tb = “<<b<<endl;
getch();
}

Sample run: Enter two numbers: 50 100


Before interchanging: a = 50 b = 100
After interchanging: a = 100 b = 50

447
Practical problem 2

Write a C++ program to find the area and circumference of a circle.

1. INPUT radius
2. area = 3.142 * radius * radius
circum = 2 * 3.142 * radius
3. OUTPUT area, circum
4. STOP

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
float radius, area, circum;
clrscr();
cout<<“Enter the radius: “;
cin>>radius;
area = 3.142 * radius * radius;
circum = 2 * 3.142 * radius;
cout<<“Area = “<<area<<endl;
cout<<“Circumference = “<<circum<<endl;
getch();
}

Sample run: Enter the radius: 5.5


Area = 95.0455
Circumference = 34.562

448
Practical problem 3

Write a eÁw
C++ program to find the area of a triangle given three sides.

1. INPUT s1, s2, s3


2. s = (s1+s2+s3)/2
area = sqrt(s*(s-s1)*(s-s2)*(s-s3))
3. OUTPUT area
4. STOP

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<math.h>
void main()
{
double s1, s2, s3, s, area;
clrscr();
cout<<“Enter the length of 3 sides: “;
cin>>s1>>s2>>s3;
s = (s1+s2+s3)/2;
area = sqrt(s*(s-s1)*(s-s2)*(s-s3));
cout<<“Area = “<<area<<endl;
getch();
}

Sample run: Enter the length of 3 sides: 5 3 6.5


Area = 7.21083

449
Practical problem 4

Write a program to convert days into years, months and days (Hint: Assume all months have 30 days)

1. INPUT totaldays
2. years = totaldays/365
totaldays = totaldays%365
months = totaldays/30
days = totaldays%30
3. OUTPUT days, months, years
4. STOP

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
int totaldays, days, months, years;
clrscr();
cout<<“Enter the total days: “;
cin>>totaldays;
years = totaldays/365;
totaldays = totaldays%365;
months = totaldays/30;
days = totaldays%30;
cout<<“Days = “<<days<<endl;
cout<<“Months = “<<months<<endl;
cout<<“Years = “<<years<<endl;
getch();
}

Sample run: Enter the total days: 1015


Days = 15
Months = 9
Years = 2

450
Practical problem 5

Write a eÁw
program to find the largest, smallest and second

1. INPUT a, b, c
2. largest = a
3. if (b > largest)
b = largest
if end
4. if (c > largest)
c = largest
if end
5. smallest = a
6. if (b < smallest)
b = smallest
if end
7. if (c < smallest)
c = smallest
if end
8. seclargest = (a+b+c) – (largest+smallest)
9. OUTPUT largest, seclargest, smallest
10. STOP

#include<stdio.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a, b, c, largest, seclargest, smallest;
clrscr();
cout<<“Enter three numbers: “;
cin>>a>>b>>c;
largest = a;
if (b>largest)
largest = b;
if (c>largest)
largest = c;
smallest = a;
if (b<smallest)
smallest = b;

451
if (c<smallest)
smallest = c;
seclargest = (a+b+c)-( largest+ smallest);
cout<<“Smallest = “<<smallest<<endl;
cout<<“Second largest = “<<seclargest<<endl;
cout<<“Largest = “<<largest<<endl;
getch();
}

Sample Run: Enter three numbers: 10 50 20


Smallest = 10
Second largest = 20
Largest = 50

Practical problem 6

Write a program to input the total amount in a bill, if the amount is greater than 1000, a discount of 8% is
given. Otherwise, no discount is given. Output the total amount, discount and the final amount. Use if-
statement.

1. INPUT amount
2. discout = 0.0
3. if (amount>=1000)
discout = 8/100
if end
4. netdiscount = amount * discount
netamount = amount – netdiscount
5. OUTPUT netdiscount, netamount
6. STOP

452
#include<stdio.h>
eÁw
#include<conio.h>
#include<iomanip.h>
void main()
{
float amount, discount, netdiscount, netamount;
clrscr();
cout<<“Enter the total purchase: “;
cin>>amount;
discount = 0.0;
if (amount>=1000)
discount = (float)8/100; //Type casting
netdiscount = amount * discount;
netamount = amount - netdiscount;
cout<<“Nett discount = “<<netdiscount<<endl;
cout<<“Nett amount = “<<netamount<<endl;
getch();
}

Sample Run: Enter three total purchase: 3000


Nett discount = 240
Nett amount = 2760

Practical problem 7
Write a program to check whether a given year is a leap year or not, using if-else statement.

1. INPUT year
2. if ( year%4 == 0 && year%100!= 0 || year%400 == 0 )
OUTPUT “It is a leap year”
else
OUTPUT “It is not leap year”
3. STOP

453
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int year;
clrscr( );
cout<< “ Enter the year: “;
cin>> year;
if ( year%4 == 0 && year%100!= 0 || year%400 == 0 )
cout<<“It is a leap year”<<endl;
else
cout<<“It is not leap year”<<endl;
getch( );
}

Sample run: Enter the year: 2012


It is a leap year

Sample run: Enter the year: 1900


It is not leap year

454
Practical problem 8

Write aeÁw
program to accept a character. Determine whether the character is a lower-case or upper-case
letter.

1. INPUT ch
2. if (ch >=’A’ AND ch <= ‘Z’)
PRINT “It is an upper-case alphabet”
else
if (ch >=’a’ AND ch <= ‘b’)
PRINT “It is a lower-case alphabet”
else
PRINT “It is not an alphabet”
3. STOP

455
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
char ch;
clrscr( );
cout<< “ Enter the character: “;
cin>>ch;
if ( ch>=’A’ &&ch<=’Z’)
cout<<“It is an upper-case character”<<endl;
else
if ( ch>=’a’ &&ch<=’z’)
cout<<“ It is a lower-case character”<<endl;
else
cout<<“It is not an alphabet”<<endl;

getch( );
}

Sample Run: Enter the character: J


It is an upper-case character

Sample Run: Enter the character: g


It is a lower-case character

Sample Run: Enter the character: 5


It is not an alphabet

456
Practical program 9
eÁw
Write a program to input the number of units of electricity consumed in a house and calculate the final
amount using nested-if statement. Use the following data for calculation

Units Consumed Cost


< 30 Rs 3.50 / unit
>=30 and <50 Rs 4.25 / unit
>=50 and < 100 Rs 5.25 / unit
>=100 Rs 5.85 /unit

1. INPUT oldread, newread, minamt


2. units = newread – oldread
3. if (units < 30)
amt = units * 3.50
else
if (units < 50)
amt = (29 * 3.50) + (units – 29) * 4.25
else
if (total < 100)
amt = (29 * 3.50) + (20 * 4.25) + (units – 49) * 5.25
else
amt = (29 * 3.50) + (20 * 4.25) + (50 * 5.25) + (units – 99) * 5.85
if end
4. vat = 12.5/100
5. netamt = (amt * vat) + minamt
6. PRINT netamt
7. STOP

457
START

INPUT oldread, newread, minamt

units = newread - oldread

T F

amt = units * 3.50


Is F
T
units < 50
?

Amt=(29*3.50)-(units-29)*4.25
Is F
T
units < 100
?

Amt=(29*3.50)+(20*4.25)+(units-49)*5.25

Amt=(29*3.50)+(20*4.25)+((units-49)*5.25+(50*5.25)+
(units -99)*5.85

Vat = 12.25
netamt = (amt * vat) +minamt

OUTPUT netamt

STOP

458
#include<iostream.h>
eÁw
#include<iomanip.h>
#include<conio.h>
void main()
{
int oldread, newread, units;
float minamt, vat, amt, netamt;
clrscr();
cout<<“Enter the old reading: “;
cin>>oldread;
cout<<“Enter the new reading: “;
cin>>newread;
cout<<“Enter the minimum: “;
cin>>minamt;
units= newread - oldread;
if (units < 30)
amt = units * 3.50;
else
if (units < 50)
amt = (29 * 3.50) + (units - 29) * 4.25;
else
if (units < 100)
amt = (29 * 3.50) + (20 * 4.25) + (units - 49) * 5.25;
else
amt = (29 * 3.50) + (20 * 4.25) + (50 * 5.25) + (units - 99) * 5.85;

vat = 12.5/100;
netamt = (amt * vat) + minamt;
cout<<“Final amount = “<<netamt;
getch();
}

Sample Run: Enter the old reading: 450


Enter the new reading: 600
Enter the minimum: 200
Final amount = 293.419

459
Practical program 10

Write a program to input the marks of four subjects. Calculate the total percentage and output the result
as either “First class” or “Second class” or “Pass class” or “Fails” using switch statement.

Class Range(%)
First Class Between 60 and 100%
Second Class Between 50 and 59%
Pass Class Between 40 and 49%
Fails Less than 40%

1. INPUT m1, m2, m3, m4


2. total = m1+m2+m3+m4
3. percentage = (total/400)*100
4. score = (int)percentage/10
5. switch(score)
6. {
case 10:
case 9:
case 8:
case 7:
case 6: PRINT “First class”
break
case 5: PRINT “Second class”
break
case 4: PRINT “ Pass class”
break
default: PRINT “Fails”
}
7. STOP

#include<iostream.h>
#include<iomanip.h>
void main()
{
int m1, m2, m3, m4, total, choice;
float percentage;
cout<<“Enter the first subject marks: “;
cin>>m1;
cout<<“Enter the second subject marks: “;

460
cin>>m2;
eÁw cout<<“Enter the third subject marks: “;
cin>>m3;
cout<<“Enter the fourth subject marks: “;
cin>>m4;
total = m1 + m2 + m3 + m4;
percentage = total/4.0;
choice = (int)percentage/10;
cout<<“Total marks = “<<total<<endl;
cout<<setprecision(2);
cout<<“Percentage = “<<percentage<<endl;
cout<<“The result of the student is “;
switch(choice)
{
case 10:
case 9:
case 8:
case 7:
case 6: cout<<“First class”<<endl;
break;
case 5: cout<<“Second class”<<endl;
break;
case 4: cout<<“Pass class”<<endl;
break;
case 3:
case 2:
case 1: cout<<“Fail”<<endl;
}
}

Sample Run: Enter the first subject marks: 69


Enter the second subject marks: 75
Enter the third subject marks: 80
Enter the fourth subject marks: 75
Total marks = 299
Percentage = 74.75
The result of the student is First class

461
START

INPUT m1, m2, m3, m4

total = m1+m2+m3+m4
percentage = (total/100)*100
score = int(percentage/10)

Is
score

OUTPUT “First class” OUTPUT “Second class” OUTPUT “Pass class” OUTPUT “Fails”

STOP

Practical problem 11

Write a program to find the sum of al l the digits of a number using while statement.
START

INPUT n

sum = 0
1. INPUT n
2. sum = 0
Is F
3. while (n 0) n‡0
rem = n%10 ?
sum = sum+10 T
n = n/10 rem = n %10
sum = sum / 10
while end
n = n /10
4. PRINT sum
5. STOP
OUTPUT sum

STOP

462
#include<iostream.h>
#include<iomanip.h>
eÁw
#include<conio.h>
void main()
{
int n, m, sum, rem;
clrscr();
cout<<“Enter the number: “;
cin>>n;
m = n;
sum = 0;
while (n != 0)
{
rem = n%10;
sum = sum + rem;
n = n/10;
}
cout<<“Sum of digits in “<<m<<“ is “<<sum<<endl;
getch();
}

Sample Run: Enter the number: 1205


Sum of digits in 1205 is 8

Practical problem 12

Write a program to input principal amount, rate of interest and time period, calculate the compound
interest using while statement.

1. INPUT priamt, rate, time


2. netamt = priamt;
3. year = 1;
4. while ( year <= time )
netamt = netamt*(1+rate/100)
year = year+1
while end
5. ci = netamt - priamt;
6. PRINT “Compound interest = “, ci
7. PRINT “Nett amount = “, netamt
8. STOP

463
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
float priamt, netamt, rate, ci;
int time, year;
clrscr();
cout<< “Enter the principal amount, rate of interest and time: “<<endl;
cin>>priamt>>rate>>time;
netamt = priamt;
year = 1;
while ( year <= time )
{
netamt = netamt*(1+rate/100);
year++;
}
ci = netamt - priamt;
cout<<“Compound interest = “<<ci<<endl;
cout<< “Nett amount = “<<netamt<<endl;
getch();
}

Sample run:

Enter the principal amount, rate of interest and time:


1000 10 5
Compound interest = 610.51
Nett amount = 1610.51

464
Practical Program 13
eÁw
Write a program to check whether a given number is power of 2.
1. INPUT n
2. m=n
status = 1
3. while (n>2)
if (n mod 2 = 1)
status = 0
GOTO 4
else
n = n/2
while end
4. if(status)
PRINT m, “ is power of 2”
else
PRINT m, “ is not power of 2”
5. STOP

465
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, m, status;
clrscr();
cout<<“Enter a number: “;
cin>>n;
m = n;
while (n>2)
if (n%2 == 1)
{
status = 0;
break;
}
else
n = n/2;
if(status)
cout<<m<<“ is power of 2”<<endl;
else
cout<<m<<“ is not power of 2”<<endl;
getch();
}

Sample run: Enter a number: 63


63 is not power of 2

Sample run: Enter a number: 128


128 is power of 2

466
eÁw Practical program 14

Write a program to check whether a given number is an Armstrong number using do-while statement
(Hint: 153 = 13 + 53+ 33).

1. INPUT n
2. temp = n
sum = 0
3. do
rem = temp mod 10
sum = sum + rem*rem*rem
temp = termp/10
while (temp 0)
4. if (sum = n)
PRINT n, “is an Armstrong number”
else
PRINT n, “is not an Armstrong number”
5. STOP

467
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, temp, rem, sum;
clrscr();
cout<<“Enter a number: “;
cin>>n;
temp = n;
sum = 0;
do
{
rem = temp%10;
sum = sum + rem*rem*rem;
temp = temp/10;
} while (temp != 0);
if (sum == n)
cout<< n<<“ is an Armstrong number”<<endl;
else
cout<< n<<“ is not an Armstrong number”<<endl;
getch();
}

Sample run: Enter a number: 370


370 is an Armstrong number

Sample run: Enter a number: 152


152 is not an Armstrong number

Practical program 14

Write a program to find the factorial of a number using for statement.

1. INPUT n
2. fact = 1
3. for i = 1 to n
fact = fact * i
for end
4. PRINT fact
5. STOP

468
eÁw

#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, fact, i ;
clrscr();
cout<<“Enter the number: “;
cin>>n;
fact = 1;
for (i=1; i<=n; i++)
fact = fact * i;
cout<<n<<“! = “<<fact;
getch();
}

Sample Run : Enter the number: 7


7! = 5040

Practical problem 16

Write a program to generate the Fibonacci sequence up to a limit using for statement.

1. INPUT n
2. first = 0
second = 1
3. PRINT first, second
4. third = first+second
5. for ( count=2; third<=n; count++)
PRINT third
first = second
second = third
third = first+second
for end

6. STOP

469
#include <iostream.h>
#include <conio.h>
#include<iomanip.h>
void main( )
{
int n, first, second, count, third ;
clrscr();
cout<<“Enter the limit: “;
cin>>n;
first=0;
second=1;
cout<<first<<setw(4)<<second;
third = first+second;
for (count = 2; third<=n; count++)
{
cout<<setw(4)<<third;
first = second;
second = third;
third = first+second;
}
cout<<endl<<“Total terms = “<<count<<endl;
getch();
}

Sample Run: Enter the limit: 50


0 1 1 2 3 5 8 13 21 34
Total terms = 10

470
Practical problem 17
eÁw
Write a program to find the sum and average of n numbers.

1. INPUT n
2. for i = 0 to n-1
INPUT a[i]
for end
3. sum = 0
4. for i = 0 to n-1
sum = sum + a[i]
for end
5. average = sum/n
6. OUTPUT sum, average
7. STOP

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, n, sum;
float avg;
clrscr( );
cout<<“How many elements? ”;
cin>>n;
cout<<“Enter the elements: “;
for(i=0; i<n; i++)
cin>>a[i];
sum = 0;
for(i=0; i<n ;i++)
sum = sum + a[i];
avg = (float)sum/n;
cout<<“Sum = “<<sum<<endl;
cout<<“Average = “<<avg<<endl;
getch( );
}
Sample run: How many elements? 5
Enter the elements: 10 20 50 40 30
Sum = 150
Average = 30

471
Practical problem 18
Write a program to find the second largest of n numbers.

1. INPUT n
2. for i = 0 to n-1
INPUT a[i]
for end
3. if (a[0] > a[1])
largest = a[0]
seclargest = a[1]
else
largest = a[1]
seclargest = a[0]
4. for i = 2 to n-1
if (a[i] > largest)
seclargest = largest
largest = a[i]
else
if (a[i] > seclargest)
seclargest = a[i]
for end
5. PRINT largest, seclargest
6. STOP

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, n, largest, secondlar;
clrscr( );
cout<<“How many elements?”<<endl;
cin>>n;
cout<<“Enter the elements: “;
for(i=0; i<n; i++)
cin>>a[i];
if(a[0] > a[1])
{
largest = a[0];
secondlar = a[1];
}

472
else
{
eÁw
largest = a[1];
secondlar = a[0];
}
for(i=2; i<n ;i++)
if(a[i] > largest) Sample run: How many elements?
{ 5
secondlar = largest; Enter the elements: 10 20 50 40 30
largest = a[i]; Largest = 50
} Second Largest = 40
else
if(a[i] >secondlar)
secondlar = a[i];
cout<<“Largest = “<<largest<<endl;
cout<<“Second Largest = “<<secondlar<<endl;
getch( );
}
Practical program 19
Write a program to arrange a list of numbers in ascending order.
1. INPUT n
2. for i = 0 to n-1
INPUT a[i]
for end
3. for i = 1 to n-1
for j = 0 to n-1-i
if (a[j] > a[j+1])
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
if end
for end
for end
4. for i = 0 to n-1
OUTPUT a[i]
for end 5. STOP

473
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a[50], i, temp, n, j;
clrscr();
cout<<“Enter the number of elements: “;
cin>>n;
cout<<“Enter the elements: “;
for(i=0; i<n; i++)
cin>>a[i];
for(i=1; i<n; i++)
for(j=0; j<n-i; j++)
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
cout<<“The sorted elements are: “;
for(i=0; i<n ;i++)
cout<<setw(5)<<a[i];
getch( );
}

Sample run: Enter the number of elements: 5


Enter the elements: 30 20 50 40 10
The sorted elements are: 10 20 30 40 50

Practical problem No. 20

Write a program to find the position of a given number in an array.

1. INPUT n, ele
2. for i = 0 to n-1
INPUT a[i]
for end
3. pos = -1

474
4. for i = 0 to n-1
eÁw if (a[i] == ele)
pos = a[i]
GOTO 5
if end
for end
5. if (pos >= 0)
PRINT ele, “ is present at position “, pos
else
PRINT ele, “ is not present”
6. STOP

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, pos, ele, n;
clrscr( );
cout<<“Enter the number of elements: “;
cin>>n;

475
cout<<“Enter the elements: “;
for(i=0; i<n; i++)
cin>>a[i];
cout<<“Enter the search element: “;
cin>>ele;
pos=-1;
for(i=0; i<n ;i++)
if(ele == a[i])
{
pos = i;
break;
}
if(pos>= 0)
cout<<ele<<“ is present at position “<<pos<<endl;
else
cout<<ele<<“ is not present”<<endl;
getch( );
}

Sample run: Enter the number of elements: 5


Enter the elements: 10 20 50 40 30
Enter the search element: 40
40 is present at position 3

Sample run: Enter the number of elements: 5


Enter the elements: 10 20 50 40 30
Enter the search element: 25
25 is not present

476
Practical problem 21
eÁw
Write a program to check whether a given matrix is scalar or not.

1. INPUT m, n
2. for i = 0 to m-1
for i = 0 to m-1
INPUT a[i][j]
for end
for end
3. if ( m=n )
PRINT “It is a square and “
scalar = 1
scalarele = a[0][0]
for i = 0 to m-1
for j = 0 to n-1
if (i = j)
if (a[i][j] ‘“ scalarele)
scalar = 0
GOTO 4
if end
else
if ( a[i][j] ‘“ 0)
scalar = 0
GOTO 4
if end
for end
for end
4. if (scalar)
PRINT “ scalar matrix”
else
PRINT “ not scalar matrix”
else
PRINT “It is a rectangular matrix”
5. STOP

477
478
#include<iostream.h>
#include<conio.h>
eÁw
#include<iomanip.h>
void main( )
{
int a[5][5], m, n, i, j, scalar, scalarele;
clrscr( );
cout<<“Enter the order : “;
cin>>m>>n;
cout<<“Enter the elements of the matrix: “<<endl;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];
if(m == n)
{
cout<<“It is a square and “;
scalar = 1;
scalarele = a[0][0];
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(i == j)
{
if(a[i][j] != scalarele)
{
scalar = 0;
break;
}
}
else
if(a[i][j] != 0)
{
scalar = 0;
break;
}
if(scalar)
cout<<“scalar”<<endl;
else
cout<<“not scalar”<<endl;
}
else
cout<<“It is a rectangular matrix”<<endl; getch(); }

479
Sample run 1: Enter the order: 2 3
Enter the elements
3 0 0
0 3 0
It is a rectangular matrix
Sample run 2: Enter the order: 3 3
Enter the elements
3 0 0
0 3 0
0 0 3
It is a square and scalar
Sample run 3: Enter the order: 3 3
Enter the elements
3 0 0
0 3 0
3 0 3
It is a square and not scalar

Practical problem No. 22


Write a program to sum of all the rows and the sum of all the columns of a matrix separately.
1. INPUT m, n
2. for i = 0 to m
for j = 0 to n
INPUT a[i][j]
for end
for end
3. for i = 0 to m-1
rsum = 0
for j = 0 to n-1
rsum = rsum + a[i][j];
for end
PRINT “Sum of row-no:”, i+1, “ = “, rsum
for end
4. for i = 0 to n-1
csum = 0
for j = 0 to m-1
csum = csum + a[j][i]
for end
PRINT “Sum of column-no:”, i+1, “ = “, csum

for end 5. STOP


480
#include<iostream.h>
#include<conio.h>
eÁw
#include<iomanip.h>
void main( )
{
int a[5][5], m, n, i, j, rsum, csum;
clrscr( );
cout<<“Enter the order of the first matrix: “;
cin>>m>>n;
cout<<“Enter the elements of the matrix: “<<endl;
for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];
for(i=0; i<m; i++)
{
rsum = 0;
for(j=0; j<n; j++)
rsum = rsum + a[i][j];
cout<<“Sum of row-no:”<<i+1<<“ = “<<rsum<<endl;
}
for(i=0; i<n; i++)
{
csum = 0;
for(j=0; j<m; j++)
csum = csum + a[j][i];
cout<<“Sum of column-no:”<<i+1<<“ = “<<csum<<endl;
}
}

Sample run: Enter the order of the first matrix: 2 3


Enter the elements of the matrix:
121
305
Sum of row-no:1 = 4
Sum of row-no:2 = 8
Sum of column-no:1 = 4
Sum of column-no:2 = 2
Sum of column-no:3 = 6

481
Practical problem No. 23

Write a program to find the sum of two compatible matrices.

Compatibility: Two matrices can be added if the two matrices are of same order. i.e., the number of
rows in the first matrix is same as the number of rows in the second matrix and the
number of columns in the first matrix is same as the number of columns in the second
matrix.

1. INPUT m1, n1
2. INPUT m2, n2
3. for i = 0 to m1 -1
for j = 0 to n1 -1
INPUT a[i][j]
for end
for end
4. for i = 0 to m2 -1
for j = 0 to n2 -1
INPUT b[i][j]
for end
for end
5. if (m1=m2 AND n1=n2)
for i = 0 to m1 -1
for j = 0 to n1 -1
s[i][j] = a[i][j] + b[i][j]
for end
for end
6. for i = 0 to m1 -1
for j = 0 to n1 -1
OUTPUT s[i][j]
for end
for end
else
PRINT “The matrices are not compatible”
7. STOP

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[5][5], b[5][5], s[5][5], i, j, m1, n1, m2, n2;
clrscr( );
cout<<“Enter the order of the of the first matrix: “;
cin>>m1>>n1;

482
cout<<“Enter the order of the of the second matrix: “;
eÁw cin>>m2>>n2;
cout<<“Enter the elements of the first matrix: “<<endl;
for(i=0; i<m1; i++)
for(j=0; j<n1; j++)
cin>>a[i][j];
cout<<“Enter the elements of the second matrix: “<<endl;
for(i=0; i<m2; i++)
for(j=0; j<n2; j++)
cin>>b[i][j];
if( (m1==m2) && (n1==n2) )
{
for(i=0; i<m1; i++)
for(j=0; j<n1; j++)
s[i][j] = a[i][j] + b[i][j];
cout<<“The resultant matrix is: “<<endl;
for(i=0; i<m1 ;i++)
{
for(j=0; j<n1; j++)
cout<<setw(5)<<s[i][j];
cout<<endl;
}
}
else
cout<<“Matrices are not compatible … “<<endl;
}

Sample run: Enter the order of the of the first matrix: 2 3


Enter the order of the of the second matrix: 2 3
Enter the elements of the first matrix:
123
456
Enter the elements of the second matrix:
251
211
The resultant matrix is:
3 7 4
6 6 7

483
Sample run: Enter the order of the of the first matrix: 2 3
Enter the order of the of the second matrix: 3 3
Enter the elements of the first matrix:
123
456
Enter the elements of the second matrix:
251
211
413
Matrices are not compatible …

484
Practical problem No. 24
eÁw
Consider an array MARKS[20][5] which stores the marks obtained by 20 students in 5 subjects. Now
write a program to:

a. Find the average marks obtained in each subject.


b. Find the average marks obtained by every student.
c. Find the number of students who have scored below 50 in their average.

1. INPUT n, s //n = No. of students and s=No. of subjects


2. for i = 0 to n-1
for j =0 to s-1
INPUT marks[i][j]
for end
for end
3. for i = 0 to s-1
total = 0
for j = 0 to n-1
total = total + marks[j][i]
for end
average = total/n
PRINT average
for end
4. for i = 0 to n-1
total = 0
for j = 0 to s-1
total = total + marks[i][j]
for end
average = total/s
PRINT average
for end
5. count = 0
6. for i = 0 to n-1
total = 0
for j = 0 to s-1
total = total + marks[i][j]
for end
average = sum/s
if (average < 50)
count = count + 1
if end
for end
7. PRINT count
8. STOP

485
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int marks[20][5], i, j, n, s, total, count = 0;
double average;
clrscr( );
cout<<“Enter the number of students: “;
cin>>n; //n is the number of students
cout<<“Enter the number of subjects: “;
cin>>s; //s is the number of subjects
cout<<“Enter the marks: “<<endl;
for(i=0; i<n; i++)
for(j=0; j<s; j++)
cin>>marks[i][j];
cout<<endl<<“Average of subbjects:\nSub1\tSub2\tSub3\tSub4\tSub5"<<endl;
cout<<setprecision(5);
for(i=0; i<s; i++)
{
total = 0;
for(j=0; j<n; j++)
total = total + marks[j][i];
average = total/n;
cout<<average<<“\t”;
}
cout<<endl<<endl<<“Average of students:\nStudent \tAverage”<<endl;
for(i=0; i<n; i++)
{
total = 0;
for(j=0; j<s; j++)
total = total + marks[i][j];
average = total/s;
if (average < 50)
count++;
cout<<“\t”<<i+1<<“\t”<<average<<endl;
}
cout<<endl<<endl<<“Number of students less than average 50 is “ <<count<<endl;
getch();
}

486
Sample Run: Enter the number of students: 4
eÁw Enter the number of subjects: 5

Enter the marks:


30 50 50 25 40
80 60 80 90 70
45 65 35 40 40
90 80 70 80 70

Average of Subjects:
Sub1 Sub2 Sub3 Sub4 Sub5
61 63 58 58 55

Average of students:
Student Average
1 39
2 76
3 45
4 78
Number of students less than average 50 is 2

Practical problem No. 25


Write a program to check whether a given string is a palindrome or not.

1. INPUT st
2. len = 0

3. while(st[len]
len = len+1
‡ ‘\0’)

while end
4. for i = len–1downto 0
rev[len-i-1] = st[i]
for end
5. for i = 0 to len-1
if (rev[i] = st[i])
flag = 1
else
flag = 0
for end
6. if (flag)
PRINT “ It is a palindrome.”;
else PRINT “ It is not a palindrome.”; 7. STOP

487
#include<iostream.h>
#include <stdio.h>
#include <string.h>
void main()
{
char string[25], reverse[25] = {‘\0’};
int i, len, flag;

clrscr();
cout<<“Enter a string: “;
cin.getline(string, 25);
// Keep going through each character of the string till its end to find length
for (len = 0; string[len] != ‘\0’; len++);
//Reverse the string
for (i = len - 1; i >= 0 ; i—)
reverse[len-i-1] = string[i];

/* Check if the string is a Palindrome */


flag = 1;
for (i = 0; i < len ; i++)
if (reverse[i] != string[i])
{
flag = 0;
break;
}
if (flag)
cout<<“The string \””<<string<<“\””<<“ is a palindrome.”;
else
cout<<“The string \””<<string<<“\””<<“ is not a palindrome.”;
getch();
}

Sample run: Enter a string: MALAYALAM


The string “MALAYALAM” is a palindrome.

Sample run: Enter a string: Madam


The string “Madam” is not a palindrome

488
eÁw

489
Practical problem No. 26

Write a program to count the number of vowels and consonants in a string.

1. INPUT st
2. len = strlen(st)
vow = 0
cons = 0
3. for i = 0 to len-1
if(isalpha(st[i]))
switch(toupper(st[i]))
{
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’: vow = vow +1
break
default: cons = cons + 1
}
if end
for end
4. PRINT vow, cons
5. STOP

490
#include<iostream.h>
#include<conio.h>
eÁw
#include<string.h>
#include<ctype.h>
void main( )
{
char s[100];
int l, i, cons = 0, vow = 0;
clrscr( );
cout<<“Enter the string: “;
cin.getline(s, 100);
l = strlen(s);
for( i = 0; i < l; i++)
if(isalpha(s[i]))
switch(toupper(s[i]))
{

case ‘A’:

case ‘E’:
case ‘I’ :
case ‘O’:
case ‘U’: vow++;
break;
default: cons++;
}
cout<<“Number of vowels: “<<vow<<endl;
cout<<“Number of consonants: “<<cons<<endl;
getch( );
}

Sample run: Enter the string: Dr. A P J Abdul Kalam


Number of vowels: 5
Number of consonants: 10

491
Practical problem No. 27

Write a program to find the GCD and LCM of two numbers using functions.

1. INPUT a, b
2. g = gcd(a, b)
3. lcm = (a*b)/g
4. OUTPUT g, lcm
5. STOP

gcd(m,n):

1. while( n
‡ 0)
rem = m mod n
m=n
n = rem
while end
2. return m

492
#include<iostream.h>
#include<conio.h>
eÁw
#include<string.h>
#include<ctype.h>
void main( )
{
int gcd(int, int);
int a, b, g, lcm;
clrscr();
cout<<“Enter two numbers: “;
cin>>a>>b;
g = gcd(a, b);
lcm = (a*b)/g;
cout<<“GCD of “<<a<<“ and “<<b<<“ is “<<g<<endl;
cout<<“LCM of “<<a<<“ and “<<b<<“ is “<<lcm<<endl;
getch( );
}
int gcd(int m, int n)
{
int rem;
while(n != 0)
{
rem = m%n;
m =n;
n = rem;
}
return(m);
}

Sample run: Enter two numbers: 24 18


GCD of 24 and 18 is 6
LCM of 24 and 18 is 72

493
Practical problem No. 28

Write a program to find XY using functions.

1. INPUT x, y
2. p = expo (x, y)
3. OUTPUT p
4. STOP

expo(a, b):
1. if (a = 0)
return 0
else
. if (b = 0)
return 1
else
. if (b > 0)
return a* expo(a, n-1)
else
return expo(a, n+1)/a

494
#include<iostream.h>
#include<conio.h>
eÁw
void main( )
{
float expo(float, int);
float x, p;
int y;
clrscr();
cout<<“Enter the base: “;
cin>>x;
cout<<“Enter the exponent: “;
cin>>y;
p = expo(x, y);
cout<<x<<“^”<<y<<“ = “<<p<<endl;
getch( );
}

float expo(float a, int n)


{
if(a == 0)
return 0.0;
else
if(n == 0)
return 1.0;
else
if(n > 0)
return(a*expo(a, n-1));
else
return(expo(a, n+1)/a);
}

Sample run: Enter the base: 0 Sample run: Enter the base: 2
Enter the exponent: 2 Enter the exponent: 3
0^2 = 0 2^3 = 8
Sample run: Enter the base: 2
Enter the exponent: 0
2^0 = 1

Sample run: Enter the base: 2


Enter the exponent: -3
2^-3 = 0.125

495
Practical problem No. 29

An industrial organization wants to computerize the allowance calculations. Given the monthly sales for
the salesman, the rules for the calculations are as follows:

i. If the total sales is less than Rs. 10000/- there is no allowance.

ii. If the total sales is between Rs. 10000/- and Rs. 20,000/- then the
allowance is 10% of the sales amount or Rs. 1800/-, whichever is minimum.

iii. If the total sales is greater than or equal to Rs. 20000/- then the
allowance is 20% of the sales amount or Rs.6,000/-, whichever is
minimum.

Write a program using a function to calculate the allowance.

1. INPUT sales
2. allowance = company(sales)
3. PRINT allowance
4. STOP

company(sales):

1. if(sales >=20000)
allowance = sales * 0.2
if( allowance >= 6000)
allowance = 6000
if end
else
if(sales >=10000)
allowance = sales * 0.1
if( allowance >= 1800)
allowance = 1800
if end
else
allowance = 0
2. return allowance

496
eÁw

497
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main( )
{
float company(float);
float sales, allowance;
clrscr();
cout<<“Enter the sales: “;
cin>>sales;
allowance = company(sales);
cout<<“Allowance = “<<allowance<<endl;
getch( );
}
float company(float sales)
{
float allowance;
if(sales < 10000)
allowance = 0.00;
else
if(sales >=10000 && sales < 20000)
{
allowance = sales * 0.1;
if(allowance > 1800)
allowance = 1800.00;
}
else
if(sales >= 20000)
{
allowance = sales * 0.2;
if(allowance > 6000)
allowance = 6000.00;
}
return(allowance);
}
Sample run: Enter the sales: 9950 Sample run: Enter the sales: 19250.25
Allowance = 0 Allowance = 1800
Sample run: Enter the sales: 14550.5 ample run: Enter the sales: 35900
Allowance = 1455.05 Allowance = 6000
Sample run: Enter the sales: 27250.75
Allowance = 5450.15

498
Practical problem No. 30

Write a eÁw
program to input the register number, name and class of all the students in a class into a structure
and output the data in a tabular manner with proper heading.

1. INPUT n
2. struct student
{
int regno
char name[20]
char class9[4]
} s[50]
3. for i = 0 to n-1
INPUT s[i].regno, s[i].name, s[i].section
for end

4. for i = 0 to n-1
OUTPUT s[i].regno, s[i].name, s[i].section
for end

5. STOP
START

Declare structure with members


regno, name and class

Declaration of structure variable

Loop for the all the values

INPUT the student details

Loop for the all the values

OUTPUT the student details

STOP

499
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<string.h>
struct student
{
int regno;
char name[25];
char section[10];
};
void main()
{
student s[50];
int i, j, n;
clrscr();
cout<<“How many students? “;
cin>>n;
for(i = 0; i < n; i++)
{
cout<<“Enter the Reg. No. of the student”<<i+1<<“: “;
cin>>s[i].regno;
cout<<“Enter the name of the student”<<i+1<<“: “;
cin>>s[i].name;
cout<<“Enter the class of the student”<<i+1<<“: “;
cin>>s[i].section;
}
cout<<“\tREG. NO.\tNAME\tCLASS\t”<<endl;endl;
for(i = 0; i < n; i++)
cout<<“\t”<<s[i].regno<<“\t”<<s[i].name<<“\t”<<s[i].section<<endl;
getch();
}

500
Sample eÁw
Run: How many students? 3
Enter the Reg. No. of the student1: 111
Enter the name of the student1: Ayesha
Enter the class of the student1: CEBA
Enter the Reg. No. of the student2: 222
Enter the name of the student2: Harshini
Enter the class of the student2: CEBA
Enter the Reg. No. of the student3: 333
Enter the name of the student3: Divya
Enter the class of the student3: SEBA

REG.NO. NAME CLASS


111 Ayesha CEBA
222 Harshini CEBA
333 Divya SEBA

501
502
eÁw

SECTION B
WORK SHEET
MANUAL

503
Spreadsheet Practical List

1. Eight salesmen sell three products for a week. Using a spreadsheet create a
sales report. The report should include the name of the salesman, Amount of
sales for each product and the salesman’s total sales in the format given
below.

a) Type in all text and numbers in the spreadsheet.


b) Format all numbers as a currency.
c) Center the spreadsheet headings across the spreadsheet.
d) Format all text.
e) Create formulas to display a total for each sales rep.
f) Create formulas to display a total for each product.
g) Create a formula to calculate the total sales for all sales rep’s for the
month.

STEP 1: START -> PROGRAMS-> OFFICE -> EXCEL


STEP 2: Enter the header Sales for the month under c1
STEP 3: Enter Name on A2 and Total products on B2 so on.
STEP 4: Under E3., give the =Sum() formula
STEP5: Move the cursor on the end of the cell you will obtain the + symbol
and drage to all the values
STEP 6: Find the total for the month in the F2 cell give the formula =sum(e3)*4
STEP7: Move the cursor on the end of the cell you will obtain the + symbol
and drage to all the values

504
eÁw

505
STEP 1: START -> PROGRAMS-> OFFICE -> EXCEL
STEP 2: Enter the header Salary for the month under D1
STEP 3: Enter Employee Code under A2 in the columns.
STEP 4: BASIC SALARY IS FIXED BASED ON THE SALES BY THE GOVT.
STEP 5: Under D4 The DA is caluclated ie 50% of Basic THE give
the=SUM(D4*50)/100
STEP 6: Under E4 The HRA is caluclated ie 12% of Basic THE give
=SUM(E4*12)/100
STEP 7: Under G4 The Total Salary is caluclated,The give =SUM(D2:F4)-G4
the loan amount is minused
STEP 8: Under H3 The Tax is caluclated based on the conduction condition ie
=IF(H4>500000,H4*20/100,H4*10/100)

506
eÁw

SALARY FOR THE MONTH OF APRIL


Total
Annual
Employee Code Employee Name Basic Salary DA HRA Loan Monthly Salary Salary Tax
CS-1 Shankaraiah Y J 45000 22500 5400 5000 67900 814800 162960
CS-5 Mahadeva D 50000 25000 6000 5000 76000 912000 182400
CS-2 Mahadevaprabhu 25000 12500 3000 5000 35500 426000 42600
POL-7 Dhananjaya 30000 15000 3600 5000 43600 523200 104640
ELE-6 Shoba 7000 3500 840 5000 6340 76080 7608
MON-3 Jyothishree H R 30000 15000 3600 5000 43600 523200 104640
Mat-8 Ramesha 5622 2811 674.64 5000 4107.64 49291.68 4929.168
SS-7 Ambika 70000 35000 8400 5000 108400 1300800 260160
Eco-8 Anitha 300000 150000 36000 1500 484500 5814000 1162800

=IF(H3>=
As per Any 500000,
the Govt. fixed H3*20%,
Department Name rules =C3*50% =C3*50% value =C3+D3+E3-F3 '=12*G3 H3*10%)

507
3. Enter the following details for 10 Students Register Number , Name,
Subject1 Mar ks, Subject2 Marks, Subject3 Marks, Subject4 Marks, Total
Marks and Percentage.

Test Marks data of a Class


Register Name Subject1 Subject2 Subject3 Subject4 Total Percentage
Number Marks Marks Marks Marks Marks

a) Type the Register Nu mber, Name and marks of four subjects for
10students in the spreadsheet.
b) Format all text and numeric data appropriately.
c) Center the spreadsheet headings across the spreadsheet.
d) Create a formula to compute the Total marks and copy this to all
the cells.
e) Create a formula to compute Percentage and copy this to all the
cells.
f) Create a formula to compute the highest and lowest score using a
library function.
g) Draw a bar graph for Register Number against total marks.
h) Draw Pie chart f or one student showing his marks in different
subject from total score

STEP 1: START -> PROGRAMS-> OFFICE -> EXCEL


STEP 2: Enter the Header Test Marks dta for a class under E1
STEP 3: Enter Register Number,name,subject marks in the columns.
STEP 4: The total is calulated on the G3 =SUM(D4:G4)
STEP 5: The percentage is calulated bt the formula =SUM(H4)/4
STEP 5: The maximum percentage is clulated using the Statistical formula
max() by giving the range of value =MAX(I4:I13)
STEP 6 : The range of value for the graph is obtained by the selecting the
column register no A1: A12 and hold ctrl and next select the column
total G1: G12
Step 7 : Insert the graph select the graph selcte the bar graph and view
STEP 8: give the header of the graph
STEP 9 : The range of value for the graph is obtained by the selecting the
rows a4:g4
Step 10 : Insert the graph select the graph selcte the pie graph and view
STEP 11: give the header of the graph

508
eÁw

A B C D E F G H I J K L
1 TESTMARKSDATAOFACLASS
REGISTER NAME SUBJECT SUBJECT SUBJECT SUBJECT TOTAL PERCENTAGE HIGHEST LOWEST
2 4 SCORE
2 NUMBER 1 3
3 2013AN001 Shankar 89 99 100 99 387 96.75 98.5 74.5
4 2013AN002 Pooja 93 96 89 93 371 92.75
5 2013AN003 Ramya 99 78 99 100 376 94
6 2013AN004 Punith 100 100 100 94 394 98.5
7 2013AN005 Sarayana 49 99 79 88 315 78.75
8 2013AN006 James 77 89 90 99 355 88.75
9 2013AN007 Daryill 85 90 99 100 374 93.5
10 2013AN008 Domnic 70 83 67 78 298 74.5
11 2013AN009 Hema 80 98 100 100 378 94.5
12 2013AN010 Gowri 89 99 100 100 388 97
13
14
15 =SUM(C12:F12) =MIN(H3:H12)
16
17 =SUM(G12)/4 =MAX(H3:H12)
18
19

509
4. A housewife maintains the budget expenditure in a spreadsheet under the
headings Income and Expenses. Income includes husband’s and Wife’s
income separately under different headings. Expenses include Rent, Bills,
Household expenses and medical expenses.

Budget for the Month


Income Expenses Total Savings
Husband Wife Rent Bills Household Medical Expenditure

a) Type the Income and Expenses data for the entire mo nth in the
spreadsheet.
b) Format all numbers as currency.
c) Center the spreadsheet headings across the spreadsheet.
d) Create a formula to compute the Total expenditure and copy this to
all the cells.
e) Create a formula to compute the savings a nd copy this to all the
cells.
f) Draw a bar graph to show expenditure under each heading.
g) Draw Pie chart to show the distribution of salary.

STEP 1: START -> PROGRAMS-> OFFICE -> EXCEL


STEP 2: Enter the Header Income and Expenses E1
STEP 3: Enter Husband and wife income for the month in the A4 and B4
STEP 4: The Toptal income for the mointh =SUM(A4:B4) place on C4
STEP 5: The total expenditure is calculated =SUM(E5:H5)
STEP 6 : The Saving for the month is calulated by giving =D5-I5
STEP 7: Select the range of values and the insert the bar gaph and for
expenditures and by selectingthe range of values form D,E,F,G columns
by holding the crl key
Step 8 : Select the insert graph bar graph and view
Step 9: Select any one of the rows and insert pie chart and view

510
eÁw

511
5. A Bank offers loan for housing and vehicle at an interest of 10.25%
for housing and 14.2% for vehicle. For a loan applicants compute the
monthly premium (EMI), given total installments as 24 months. Also
compute the monthly interest and monthly principal amount and the
total amount of principal and Interest paid using Financial library
functions in a spreadsheet.

STEP 1: START -> PROGRAMS-> OFFICE -> EXCEL


STEP 2: Enter the Header Bank Loan D1
STEP 3: Enter The vehicle loan details for Rate under b5,No of installments under b6, amount in
$ value using format $80,000 on b7
STEP 4: The using the formula =PMT(B3/24,B4,B5,B6,B7)
STEP 5: Amount to be paud for the 24 months is calulated =3585.43*24
Step 6 : Toatl amount of intrest paid for 24 month =B10-b5

STEP 6 : Intrest paid for the month is claulated by givin gthe formula =B12/24
STEP7: The amount to be per month '=3585.43-252.1
in the same way the Home loan is claulated and the EMI ic calulate for 24 month
The working is shown in the sample chart

Note the Rupee symbol can be used provided the symbol is download and using ~ sign to insert
the general $ symboll is used using format commands.

512
eÁw

A B C D E F G H I J K
1 BANKLOAN
2
3 VehicleLoan VehicleLoan HOMELOAN
4
5 Rate 14.20% 10.25%
6 Noof installements 24 24
7 Principleamount 80000 $ 1,500,000.00
balanceamountleft
8 attheend 0 0
9 paymentatthebeginning 0 0
amount
to bepaid
10 per month ($3,585.43) =PMT(B3/24,B4,B5,B6,B7) ($65,891.09) =PMT(D3/24,D4,D5,D6,D7)
11
total
amount
tobe
12 paid 86050.32 =3585.43*24 $1,581,386.16 =65891.09*24
13
14 intrestpaid 6050.32 =B10-B5 $81,386.16 =D10-D5
15
16 intrest/ month $ 252.10 =B12/24 $3,391.09 =D12/24
17
18 amountper month $3,333.33 =3585.43-252.1 62500 =65891.09-3391.09
19

513
6. Implement five functions each for Arithmetic, Date and Time, Financial,
Logical, text and statistical functions. Write the syntax, example and output
for simple problems.

The different calulation with the deading is used in the text book in the library functions
Please refer : two functions are given here as sample :

514
A B C D E F G
eÁw

1 RATE RATE()
2 NUMBERofMONTHS 48
3 Perodicpayment $ 550.00
4 totalAmount $ 24,000.00
5 Balanceleftattheend $ -
6 InitialPayment $ -
7 $ 4.75
8
9 =RATE(B2,-B3,B4,B5,B6)*12*100
10
11 PMT(interest_rate,number_payments,PV,[FV],[Type]) =PMT(7.5%/12,2*12,5000,0,1) ($223.60)
12 RATE(number_payments,payment,PV,[FV],[Type],[Estimate]) =RATE(2*12,-250,5000) 2%
13 FV(interest_rate,number_payments,payment,[PV],[Type]) =FV(7.5%/12,2*12,-250,-5000,1) $12,298.46
14 NPER(interest_rate,payment,PV,[FV],[Type]) =NPER(7.5%/12,-150,5000) 37.49506232
15 IPMT(interest_rate,period,number_payments,PV,[FV],[Type]) =IPMT(7.5%/12,8,2*12,5000) ($22.61)
16
17
18 StatisticalFunctions
19 10.5 8.85
20 7.2
21 200
22 5.4 small
23 8.1 #NUM!
24

515
7. Create a data form to implement a student database and perform all
related operations with the data form.

DATA FORM
Data Form : Interaction of Data Base with ESS
Step 1: The data base which is existing in the data base / New database must be created using
access.
Step 2: go to ESS -> data -> from access -> the fields will be inserted in the form of table
Step 3: Each columns will be the fields
Step 4: Each row will be the record –the records can be entered ie data entry
Step 5 :The fields can be data filtered.
Step 6: The table tools can be seen on top of the title Bar.

516
eÁw

SECTION C
Web Designing
MANUAL

517
1. Create a Web page to display your details using different tags.
Step 1: start -> programs->accessories -> notepad
Step 2: File-> new
Step 3 : Type the Html tags
Step 4 : save the file on the desktop with the extension .html
Step 5: View the html file using web browsers

<HTML>
<HEAD>

<TITLE> This title name will be displayed on the window title </TITLE>

</HEAD>
<BODY>
<H1> Header tag One will display in big size </h1>
<h6> Header tag six will in small size </h6>
<p>
The paragraph will begin and end with p and all the matter can
controlled with formating commands
like align,size, colour, style etc.,
</p>
<p>
In order to save the html file <br>
Please save the file on the desktop, so that you need not search the path
<br>
Please save the file with the extension filename.html
Br tag is used to break at the end of the line
</p>
<p>
To view the html file use the web browsers
Namely Internet explorer,MSn,Google crome, Mozilla firefox etc.,
</P>

</BODY>
</HTML>

518
eÁw

519
2. Create a model Web site for your college making using different
tags.

Step 1: start -> programs->accessories -> notepad


Step 2: File-> new
Step 3 : Type the Html tags
Step 4 : save the file on the desktop with the extension .html
Step 5: View the html file using web browsers
<!DOCTYPE html>
<html>
<head>
<title>P U DEPARTMENT</title></head>
<body>
<h1><center> MY COLLEGE</h1></center>
<p><h3><center> Most prestigious institutions in KARNATAKA.<bR>
Has been a pioneer in the field of education, for many years, excellency <br> in imparting quality
knowledge.</center><br></p>

<p><center> Courses offered here includes <BR>


science,<Br> commerce,<br> arts courses. </center><br></h3></p>

</body>
<marquee direction="right"> Admission for the Eligilble STUDENTS </marquee>

</html>

520
eÁw

521
522

You might also like