Professional Documents
Culture Documents
CS Textbook
CS Textbook
GOVERNMENT OF KARNATAKA
COMPUTER SCIENCE
TEXT BOOK
FOR
FIRST PUC
i
Director’s Message
Dear Students,
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. Hemalatha N
Member
Vijaya College, R.V. Road
Basavanagudi, Bengaluru.
Sri. Srinivas K. P
Members
Govt. Pre-UniversityCollege for Women
Balmatta, Mangalore.
iv
eÁw
ACKNOWLEDGEMENT
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.
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
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
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
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
xii
BLUE PRINT
eÁw
FIRST PUC – COMPUTER SCIENCE FINAL EXAMINATION
Knowledge 30% 31
Understanding 40% 43
Application 20% 21
Skill 10% 10
Total 100% 105
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
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)
C Programming in 5 3 4 5 48
C++
xiv
I PUC - Computer Science
eÁw
Practical’s Syllabus
BLUE PRINT
TOTAL 20 marks
Practical List
Section A
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
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
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
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
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.
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
a) PROGRAMS ON C++
b) PROBLEM on ESS
c) PROBLEM on HTML
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.
*************
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.
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:
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.
5
Fundamentals of Computers
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.
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.
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.
8
Fundamentals of Computers
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.
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
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.
10
Fundamentals of Computers
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
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),”
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.
12
Fundamentals of Computers
that fundamentally, changed the way computers operated. These helped to develop smaller, economical ,
powerful, efficient and reliable devices.
eÁw
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.
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
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
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
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.
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
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
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.
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.
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.
19
Fundamentals of Computers
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.
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.
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.
21
Fundamentals of Computers
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.
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
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
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
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?
27
Fundamentals of Computers
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.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.
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
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)
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.
33
Input output Memory Devices
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
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.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.
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.
PRINTERS
IMPACT NON-IMAPACT
Ø 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
37
Input output Memory Devices
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.
38
Input output Memory Devices
eÁw
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.
Table 1.0
Units of Measurements in computer for Primary Memory and secondary memory
40
Input output Memory Devices
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
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
43
Input output Memory Devices
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
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.
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
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.
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.
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.
47
Input output Memory Devices
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
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.
53
Data Representation
Table 3.1 shows the weightage of the positional values of the decimal number:
Table 3.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:
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).
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:
Table 3.3
The table 3.6 shows the weightage of the positional values of the hexadecimal number:
Table 3.6
55
Data Representation
Example 3.5 Consider the decimal number 53(10) which can be represented in binary as:
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
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:
57
Data Representation
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:
Table 3.6
Therefore, 5AF.D (16) = 1455.8125(10)
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.
59
Data Representation
Table 3.5 shows each hexadecimal number may be represented as a 4-digit number.
Table 3.5
60
Data Representation
eÁw
61
Data Representation
1 7 5 3 3 6
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.
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.
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
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
75 = 64 + 8 + 2 +1 = 1001011
25 = 16 + 8 + 1 = 11001
Borrow
Minuend 1001011
Subtrahend 11001
ddd
Difference 110010
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.
Minuend 011001
1’s compliment of Subtrahend + 001011
100100
There is no carry. Therefore re-complement and insert a negative sign, we get - 011011
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.
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
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.
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
72
Data Representation
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.
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”.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
87
4.6.3 Comparison of CUI and GUI
CUI GUI
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
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
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.
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.
***************
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
95
Problem Solving Methodology
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:
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.
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
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.
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.
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
Pre-defined
Subprogram
process
Connector Connection
103
Problem Solving Methodology
START
INPUT a, b
temp = a
a=b
b = temp
OUTPUT a, b
STOP
START
INPUT rad
STOP
104
Problem Solving Methodology
s = (s1 + s2 + s3)/2
area = sqrt(s * (s – s1) * (s – s2) * (s –s3))
OUTPUT area
STOP
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
Y More
Numbers?
N
O
average = sum/count
O
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
START
INPUT n
>=2
limit = sqrt(n)
for i = 2 to limit
Is T
n % i = 0?
F
i
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.
108
Problem Solving Methodology
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.
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
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.
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
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.
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.
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
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
117
Problem Solving Methodology
Is
expression
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”;
}
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.
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?
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
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).
123
fileAdd the needed libraries or
Reregister them in register
Database and re-link
Problem Solving Methodology
124
Problem Solving Methodology
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.
125
Problem Solving Methodology
B C D
E F G H
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
126
Problem Solving Methodology
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.
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.
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
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
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.
131
Problem Solving Methodology
132
eÁw
CHAPTER 6
Object Oriented Concepts
OBJECTIVES
To Understand the basic concepts of Object Oriented Methodology
133
134
Object Oriented Concepts
135
Object Oriented Concepts
Object X Object Y
Data Data
Functions Functions
Object Z
Data
Functions
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.
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.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.
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
………. ………..
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
Paint(house) Paint(college)
Items
Paint()
Paint(furniture) Paint(fabric)
Polymorphism allows objects to have different internal structures to share the same external interface.
It supports to implement inheritance to a great extent.
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
college.marks( result)
141
Object Oriented Concepts
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.
143
Object Oriented Concepts
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++
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.
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
Constant is a fixed value that does not change during the execution of the program.
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
152
Introduction to C++
Example 7.5
eÁw
18 . 45
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.
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.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
Operator Name
155
Introduction to C++
Operator Name
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.
157
Introduction to C++
> 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.
158
Introduction to C++
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.
^ 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
All assignment operators have lower precedence than the conditional operator (?).
160
Introduction to C++
161
Introduction to C++
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.
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
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.
163
Introduction to C++
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.
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,
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.
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++
#include<iostream.h>
void main()
{
cout<<"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.
167
Introduction to C++
Let us understand each section one by one in detail by considering the above figure 7.4.
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.
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.
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.
#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.
170
Introduction to C++
log(x) logarithm of 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++
Function Meaning
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.
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)
172
Introduction to C++
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.
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
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++
175
Introduction to 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.
179
Data types
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
181
Data types
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.
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;
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.
The above example 8.5 depicts how another variable of the type enum can be created.
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.
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.
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.
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
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.
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 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.
• endl is same as the escape sequence \n. It causes a line feed to be inserted
into the stream.
• iomanip.his aheader file that holds the objects endl and setw.
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( ).
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.
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
202
Control Statements
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( );
}
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();
}
205
Control Statements
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
207
Control Statements
#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( );
}
208
Control Statements
#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( );
}
209
Control Statements
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
#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();
}
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?
212
Control Statements
213
Control Statements
Is
expression
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();
}
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.
216
Control Statements
eÁw
217
Control Statements
#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();
}
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
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
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
#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
If the number can be expressed as the sum of cube of its digits, the number is called an Armstrong
number.
while do-while
223
Control Statements
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.
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();
}
225
Control Statements
#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();
}
#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();
}
226
Control Statements
All these can be done by using break, exit, and continue statements.
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();
}
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);
}
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();
}
statement1;
statement2;
gotolabel_name;
statement3;
statement4;
label_name: statement5;
statement6;
230
Control Statements
loop: cout<<setw(5)<< n;
n--;
if ( n > 0 ) goto loop;
cout<< “END OF LOOP“ ;
getch();
}
231
Control Statements
232
Control Statements
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
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.
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
240
Arrays
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.
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.
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.
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;
getch( );
}
242
Arrays
#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;
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( );
}
243
Arrays
#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<<”Largest = “<<largest<<endl;
cout<<”Second Largest = “<<secondlar<<endl;
getch( );
}
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;
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
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.
#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;
getch( );
}
246
Arrays
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.
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.
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
Column-numbers
0 1 2 3 …. n-1
0
R 1
o 2 a[2][3]
w …
s
m-1 Row-number Column-number
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.
a is a two dimensional array which contains 2 rows and 3 columns and these assignments
would be
248
Arrays
The above code first reads all the columns for row-no 0.
a[0][0]
a[0][1]
a[0][2]
249
Arrays
The above code then reads all the columns for row-no 1.
a[1][0]
a[1][1]
a[1][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;
getch( );
}
251
Arrays
#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( );
}
252
Arrays
clrscr( );
cout<<”Enter the order of the of the first matrix: ”;
cin>>m1>>n1;
253
Arrays
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
clrscr();
cout<<”Enter the order of the first matrix: ”;
cin>>m1>>n1;
cout<<”Enter the order of the second matrix: ”;
cin>>m2>>n2;
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];
}
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;
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;
258
Arrays
else
eÁw cout<<”It is a rectangular matrix”<<endl;
getch();
}
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.
259
Arrays
Review questions:
260
Arrays
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.
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.
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.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.
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.
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.
12.2.4 iostream.h
This header file contains C++ streams and i/o routines andarelisted below in the 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.
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.
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
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;
clrscr();
cout<<”Type-in a character: “;
ch = cin.get();
getch();
}
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
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.
This declaration reserves 50-bytes to store the characters of the string variable st.
There are only 9 characters in the string. The null character (‘\0’) is automatically appended to the
end of the string.
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.
The string is initialized with only 4-characters and the null character is appended to the end of the
string.
272
Functions
cin.getline(string, size);
cout.write(string, size);
273
Functions
#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);
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();
}
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);
cout<<”Length = “<<i<<endl;
getch( );
}
275
Functions
clrscr( );
cout<<”Enter the first string: “;
cin.getline(f, 100);
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
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);
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
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.
278
Functions
clrscr( );
cout<<”Enter the string: “;
cin.getline(s, 100);
if(strcmpi(s, r) == 0)
cout<<”It is palindrome”<<endl;
else
cout<<”It is not palindrome”<<endl;
getch();
}
279
Functions
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++;
}
Sample run: Enter the string: Enter the string: Dr. A P J Abdul Kalam
Number of vowels: 5
Number of consonants: 10
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.
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.
Function-header
285
User Defined Functions
286
User Defined Functions
#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
287
User Defined Functions
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.
288
User Defined Functions
int cube(int x)
{
return(x*x*x);
}
289
User Defined Functions
return(expression); OR return 0;
290
User Defined Functions
clrscr();
cout<<”Enter a non-negative number: ”;
cin>>n;
fact=factorial(n);
cout<<n<<”! = ”<<fact<<endl;
getch();
}
f=1;
for(int i=1; i <= n; i++)
f = f * i;
return(f);
}
291
User Defined Functions
OR
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
a and b are the actual arguments. Actual arguments have values stored in them before the function
call hence the name actual.
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.
293
User Defined Functions
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
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();
}
295
User Defined Functions
296
User Defined Functions
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;
297
User Defined Functions
298
User Defined Functions
sum = x + y + y;
avg = sum/3.0;
cout<<“Average = “avg<<endl;
}
299
User Defined Functions
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
clrscr();
cout<<”Enter the base: “;
cin>>x;
cout<<”Enter the Exponent: “;
cin>>y;
301
User Defined Functions
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;
303
User Defined Functions
#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();
}
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();
}
305
User Defined Functions
void main()
{
void swap(int , int);
int a, b;
clrscr();
cout<<”Enter two numbers: “;
cin>>a>>b;
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.
306
User Defined Functions
void main()
{
void swap(int&, int&);
int a, b;
clrscr();
cout<<”Enter two numbers: “;
cin>>a>>b;
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
308
User Defined Functions
clrscr();
cout<<”Enter the first string: “;
cin.getline(s1,50);
concatenate(s1,s2);
cout<<”Concatenated string: “<<s1<<endl;
getch();
}
void concatenate(char st[], char str[])
{
int l1 = strlen(st);
int l2 = strlen(str);
309
User Defined Functions
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
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
311
User Defined Functions
#include<iostream.h>
#include<conio.h>
struct time
{
int h;
int m;
};
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;
}
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
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.
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.
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
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.
31 bytes
Figure 14.1 Memory allocations for a structure
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.
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
manager
assistant
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.
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
#include<iostream.h>
#include<iomanip.h>
#include<string.h>
void main( )
{
struct student
{
int regno;
char name[15];
char combination[4];
float perc;
}st;
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.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.
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
#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;
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
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.
#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
327
Structures
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.
s[1]
………
s[99]
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
329
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?
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
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
338
Word Processor
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!
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
All the pages from first to last page of the Printing from first to fifteen page.
document.
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
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
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.
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
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
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
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
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
365
Word Processing
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.
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.
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.
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 .
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
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
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.
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.
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.
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”.
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
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
380
Spreadsheets
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.
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.
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 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
383
Spreadsheets
384
Spreadsheets
385
Spreadsheets
=D3+E3+F3+G3+H3+I3 =SUM(D3:i3)
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.
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.
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.
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
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.
391
Spreadsheets
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
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
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.
To find the square root of a number located within a worksheet cell follow the steps below:
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
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.
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
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:
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.)
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:
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:
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
398
Spreadsheets
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
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
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-
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
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 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
6 48.26 The result with the formula using the NPER 48.26123273
function. =NPER(A1/12,-
a2,a3,a4,a5)
403
Spreadsheets
Logical Functions
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 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 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
AVERAGEA Returns the average of its arguments, including numbers, text, and logical values
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)
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.
406
Spreadsheets
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.
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.
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.
408
Spreadsheets
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
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?
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.
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.
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.
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:
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.
420
Web Designing
4. Newsgroups:
eÁw
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:
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
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:
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:
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.
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
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
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.
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.
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.
426
Web Designing
<html>
<body>
<p>This is a paragraph.</p>
</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
428
Web Designing
<html>
<body>
The resultant web page after opening this in the web browser appears as shown in figure 7.14.
Example 17.2:
<i> VIRTUAL MEMORY </i>
displays
VIRTUAL MEMORY
429
Web Designing
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.
430
Web Designing
<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.
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>
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>
</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>
<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.
434
Web Designing
435
Web Designing
Tag Description
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?
437
Web Designing
438
MODEL QUESTION PAPER
eÁw
FIRST PUC - COMPUTER SCIENCE
PART –A
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();
}
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();
}
447
Practical problem 2
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();
}
448
Practical problem 3
Write a eÁw
C++ program to find the area of a triangle given three sides.
#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();
}
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();
}
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();
}
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();
}
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( );
}
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( );
}
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
457
START
T F
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();
}
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%
#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;
}
}
461
START
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();
}
Practical problem 12
Write a program to input principal amount, rate of interest and time period, calculate the compound
interest using while statement.
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:
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();
}
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();
}
Practical program 14
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();
}
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();
}
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( );
}
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( );
}
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
481
Practical problem No. 23
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;
}
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:
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
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
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];
488
eÁw
489
Practical problem No. 26
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( );
}
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);
}
493
Practical problem No. 28
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( );
}
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
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:
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.
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
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
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.
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
=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.
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
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.
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.
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 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.
</body>
<marquee direction="right"> Admission for the Eligilble STUDENTS </marquee>
</html>
520
eÁw
521
522