You are on page 1of 255

Chapter-1

OVERVIEW OF COMPUTER
Definition:
“Computer is an electronic machine that can store, recall and process data. It can perform tasks
or complex calculation according to a set of instructions or programs.

How does the computer work?


It is as simple as making tea. To prepare tea, we add water, tea powder, milk, and sugar. These are all
considered as input. After adding all, we have to boil. That boiling is called processing. After boiling,
we get tea. That is called output.

Input-Process-Output cycle (IPO Cycle)

Similarly, the computer works based on the input, processing and output.

Characteristics of Computer:

 Speed  Versatility
 Storage  Flexibility
 Accuracy  Cost effectiveness
 Diligence
 Speed:

The computer works very fast. The speed of Computer is measured in terms of MIPS (Million
Instructions Per Second) or BIPS (Billion Instructions Per Second).
For Example A money counting machine counts money faster than man.
 Storage:
The computer can store a large volume of data and information. The storage capacity of the
computer is measured in terms of Bytes. A group of 8 Bits is called a Byte.

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

 Diligence
Unlike human beings, a computer does not suffer from limitations like tiredness and lack of
concentration. It can work for hours without making any errors.

 Versatility
Computers are capable of performing any task. Multi-processing features of computer make it
quite versatile in nature. The computer can be adapted to any field easily. It is used for scientific
calculations, business processing, for playing games, teaching, training etc.

 Flexibility
Flexibility would involve the number of things you can do with a computer. While some are
best used for simple business tasks, and filing of tasks, others are good for multimedia, gaming, and so
on.

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

Components of Computer system:

There are four components in the computer system. They are:


 Hardware  Data & Information
 Software  User(s)

 Hardware

The physical parts of a computer system called as hardware. The hardware components can be
seen, touch and feel. The hardware components are fixed inside or outside the computer system.

Example Keyboard, Mouse, Monitor, Printer, RAM, CPU etc.


 Software

A Set or collection of programs is known as software. The software is a computer program


written using some computer programming languages to operate the computer. Software tells the
hardware what to do. Unlike hardware, we can’t touch the software.

Example Operating System, TUX Paint, Office Packages, Nudi, Adobe Reader, Computer
Games etc.

The software is broadly classified into two types. They are

. System Software: It is a type of computer program that is designed to control and work with
computer hardware, to run a computer's hardware and application programs.
Example: Microsoft Windows, Linux, DOS etc.

. Application software: It is a type of Software written by the user to perform a particular task like
drawing a picture, playing computer games.
Example: Paint, Nudi and Office Package etc.

 Difference between Hardware and Software


 Hardware Software
Physical components of a computer are
Set of programs is called Software.
called Hardware.
Hardware can touch, see and feel. The software can not touch and feel.
Constructed using physical materials or Developed by the programming
components. language.
Not affected by computer viruses. Affected by computer viruses.
User cannot make copies User can make copies
Example: Monitor, Keyboard, RAM Example: OS, Text Editor, Nudi

 Data
Data is a collection of unprocessed items, which can include text, numbers, audio or video. Data
is the raw information or basic facts that computer can process.
For Example: “PARAM” 16

The computer processed data is called information, which gives particular meaning.
For Example: Name=“PARAM” Age=16.
 User(s)
People who use the computers are called users. These computer operators are called computer
users.

Functional components of a computer:

Basically any computer is supposed to carry out the following functions.

 Accepts the data and program as input.


 Stores the data, program and retrieve as and when required.
 Process the data as per instructions given by the program and convert it into useful
information.
 Communicate the information as output.

Block diagram of a computer

A computer is designed using four basic units. They are:

1. Input Unit
2. Central Processing Unit(CPU)
 Control Unit
 Arithmetic and Logic Unit (ALU)
3. Memory Unit
4. Output Unit

Control Unit

Input Unit Output Unit


Arithmetic &
Logic Unit

CPU

Memory Unit

Primary Memory

Secondary Memory

Fig: Block Diagram of Computer


 Input Unit

Computers need to receive data and instructions in order to solve a problem. The Input unit
performs this operation. The Input Unit basically links the external world or environment to the
computer system. The input unit may consist of one or more input devices. The Keyboard and mouse
of a computer are the most commonly used input devices.

 Central Processing Unit (CPU)

It is the main part of a computer system like the heart of a human being. Most computers are
identified by the type of CPU that is present in them. The function of the CPU is to interpret the
instructions in the program and execute them one by one. It consists of two major units.
1. Control Unit: It controls and directs the transfer of program instructions and data between
various units. The main activity is to maintain order and direct the operations of the entire
system.
2. Arithmetic and Logic Unit (ALU): Arithmetic and Logic Unit performs arithmetic and
logical operations and controls the speed of these operations. Arithmetic operations like
addition, subtraction, multiplication and division (+,-,*, /) and logical operations like AND,
OR, NOT and relational operations like (<,>, <=,>=) are being carried out in this unit.

 Memory Unit

The data and the instructions required for processing have to be stored in the memory unit before
the actual processing starts. In a similar manner, the results generated from processing have to be
preserved before it is displayed. The memory units thus provide space to store input data, intermediate
results and the final output generated.

Secondary storage devices are additional memory (storage) devices such as floppy disks,
magnetic tapes, Hard Disk Drive (HDD), Compact Disk (CD), Digital Versatile Disk (DVD) etc.,
which are used to store huge information for future use.

Note: The input unit, an output unit, and secondary storage devices are together known as
Peripheral Devices.

 Output Unit

It is used to print or display the results, which are stored in the memory unit. The actual
function of the output unit is just the reverse of the input unit. Thus, the output unit links the computer
to the outside world. The Monitor and Printer are the most commonly used output devices.
Evolution of computer:

 Abacus
Approximately 4,000 years ago, the Chinese invented the Abacus. It was the first machine used
for counting and calculating. It is made of a wooden frame, metal rods, and wooden beads Abacus
was mainly used for addition, subtraction and later for division and multiplication. Today, the abacus
is still used widely in China and other Asian countries to count and calculate, just as we use
calculators.

 Napier’s bones
In the early 17th century, John Napier, a Scottish mathematician, invented another calculating
tool. “Napier’s bones” was based upon manipulation of rods with printed digits. The rods were made
of bone, ivory, wood or metal. The set consists of 10 rectangular blocks with multiples of a different
digit on each of the four sides.

 The slide Rule


The slide Rule was invented by William Oughtred. It is based on the principle that acutal
distance from the starting point of the rule is directly proportional to the logarithm of the numbers
printed on the rule. The slide rule is emboided by the two sets of scales that are joined together, with a
marginal space between them.

 Adding Machine-Pascaline
In 1642, at the age of 19, a French mathematician by the name of Biaise Pascal invented the
Pascaline. The Pascaline is known as the first mechanical and automatic calculator.
The Pascaline was a wooden box that could only add and subtract by means of a series of gears
and wheels. It had a box with eight movable wheels called dials. When each wheel rotated one
revolution, it would then turn the neighboring wheel.

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

 Jacquard loom
In 1801, Joseph Mary Jacquard invented the Jacquard loom. A poweed loom that used
punched wooden cards to automatically weave incredibly detailed patterns including pictures and text.
This can be taken as the first “Read only Memory” device.
 Difference and Analytical Engine
In the early 1820s, an English mathematician by the name Charles Babbage designed a
computing machine called the Difference Engine. This machine was to be used in the calculating and
printing of simple math tables. In the 1830s, he designed a second computing machine called the
Analytical Engine. This machine consited five units, which became the basic principle for the
development of modern computer. Hence Charles Babbage is known as the "Father of Computers”.

 1833-First Programmer
Lady Ada Lovelace was a first computer programmer, who designed program for Babbage’s
Analytical Engine.

 1890 AD – Hollerith Tabulating Machine


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

Generations of Computer

Depending on the development of the technology the generation of computer is classified into
five generations.

 First Generation of Computer (1940-1956)

1. The first generation of computers is started with using vacuum tubes as the basic components.
2. The speed of these computers was very slow, storage capacity was very less and these computers
are large in size.
3. This generation computers operated only on machine language.
4. Input was based on punched card, paper tapes an output was obtained as printout.

Some computers of this generation were ENIAC (Electronic Numerical Integrator and
Calculator), UNIVAC (Universal Automatic Computer).

ENIAC:

 It stands for Electrical Numerical Integrator and Computer.


 It used a word of ten decimal digits instead of binary ones like previous automated calculators
/computers.
EDVAC
 It stands for Electronic Discrete Variable Automatic Computer.
 It was to be a vast improvement upon ENIAC. Mauchly and Eckert started working on it two
years before ENIAC even went into operation.
 This idea was to have the program for the computer stored inside the computer.

UNIAC
 Universal Automatic Computer was the first commercial computer produced in the United
States.

 Second Generation of Computer (1956-1963)

1. In this generation transistors were used in place of vacuum tubes.


2. These machines were much faster, more reliable than their earlier machines.
3. It generates less heat and consumed less electricity as compared to first generation computers.
4. Second Generation computers used punched cards for input and printout for output.
5. This computer moved from the use of machine language to assembly languages.
6. The computer stored their instructions in their memory, which moved from magnetic drum to
magnetic core technology.

Some computers of this generation were IBM 1620, IBM 7094, CDC (Control Data
Corporation) 1604 and 3600, and UNIVAC 1108.

 Third Generation of Computer (1964-1971)

1. In the third generation of computer Integrated Circuits (IC's) were used in place of transistors.
2. In this generation, Keyboard and monitors were used instead of punched cards and printout.
3. These IC’s were increased the speed of processing and storage capacity.
4. These computers were more reliable, smaller in size and faster.
5. Maintenance cost was low comparing to the previous generation and consumed less electricity.

Some computers of this generation were IBM-360 series, Honeywell-6000 series, PDP
(Personal Data Processor), IBM-370/168.

 Fourth Generation of Computer (1971-1980)

1. In the fourth generation of computer, microprocessors were used in place of Integrated Circuits
(IC’s).
2. The fourth generation of computers is marked by the use of Very Large Scale Integrated (VLSI)
circuits.
3. This made computers smaller in size became more powerful, they could bi linked to form network.

Some computers of this generation were Mini Computer and Mainframe computer, Personal
computers.

 Fifth Generation of Computer (1980-till date)

1. Fifth generation computer involves the concept of Artificial Intelligence (AI) which made the
computer think like human beings.
2. This generation uses VLSI (Very Large Scale integration) and ULSI (Ultra Large Scale
Integration) technology.
3. These computers are more intelligent and faster comparing to other generation computers.
4. Types of this generation computers are Desktop, Laptop, Notebook, and R obot. etc.

Generations of Computer

Remember

Generation Material used Features

First very slow, large in size and storage capacity


Vacuum tube based
Generation was very less
Second faster, more reliable than their earlier
Transistor
s based
Generation machines
Smaller in size and faster. Maintenance cost
Third Integrated Circuit
was low comparing to the previous
Generation based
generation
Fourth VLSI microprocessor Fourth Generation computers became more
Generation based powerful, reliable and more efficient.
These computers are more intelligent and
Fifth ULSI microprocessor
faster comparing to other generation
Generation based
computers.
Classification of Computer:

Classification based on Purpose

According to purpose, computers are classified into general purpose and


specific purpose. General purpose computers are designed to perform a range of tasks. They have an
abilityto store numerous programs but lack in speed and efficiency. Specific purpose computers are
designed to handle a specific problem or to perform a specific task.

Classification based on Principles of Operation

According to principles of data handling, computers are classified into three types
1. Analog Computers
2. Digital Computers
3. Hybrid Computers

 Analog Computers
Analog computers work upon continuous data. Analog computer operates by measuring rather than
counting. The analog computers are that all calculation 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. Computations are carried out with the physical
quantities, such as voltages, length, current, temperature etc. The device that measures such quantities
are analog devices.

 Digital Computer
The digital computer works upon discontinuous data. 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. They convert the data into digits (Binary Digit 0 and 1) and all operations carried
out on these digits at extremely fast rates. A digital computer basically knows how to count the digits
and add the digit. Digital Computers are much faster than an analog computer and far more accurate.
Computers used for business and scientific applications are digital computers.

 Hybrid Computers

Hybrid computer are the combination of both analog and digital computer. They accept both the
analog and digital data for processing. 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.
Now-a-days analog- to- digital computer (ADC) and digital-to analog computer(DAC) rare used
to transforming data into suitable form.
In these computers, some calculations take place in analog manner and rest of them takes place
in a digital manner. Hybrid computers are best used in the hospital where the analog part is responsible
for measurement of patient’s heart beat, blood pressure, temperature and other vital signs and then the
operation is carried out in a digital fashion to monitor patient’s vital signs. Hybrid Computers are also
used in weather forecasting.

 Differences between Analog & Digital computers

Analog Computer Digital Computer

Operates on continuous values of data Operates on discrete values of data

They give only approximate results They give accurate results

Processing is slow Processing is fast

They have very limited use They are versatile

They have large memory & more


They have small memory & less reliable
reliable

 Classification based on Configuration

Based on the performance, size, cost, capacity, the digital computers are classified into four
types:

1. Micro Computers
2. Mini Computers
3. Mainframe Computers
4. Supercomputers
 Micro Computers
1. Also, know as PC (Personal Computer), it was introduced in 1970.
2. The number of processors in microcomputers will be one or two processors.
3. It contains input devices, output devices, storage device and processor.
4. The number of processor will be one or two. It is used by one person at a time.
5. Example: Desktops (PC, Macintosh), Laptops, Notebooks, Tablets, Palmtops, Smart Phones.

Uses of Micro computers


 They are used as desktops either in offices or even in homes.
 Children enjoy playing games & watching movies in these computers.
 They are cheap and user-friendly.
 Their operation can be easily learned by anyone having the logical aptitude.

 Mini Computers
1. Mini computers were introduced in the 1960’s.
2. Minicomputer is larger and more powerful than personal computer.
3. In can execute five million instructions per second.
4. It generally consists of two or more processors.
5. Minicomputer can serve up to 4000 connected users simultaneously.
6. It is normally accessed by users via personal computer or terminal. A device with a monitor
and keyboard is called terminal.
7. It is also known as dumb terminal. It has no processing power and cannot work as stand-alone
computer.
8. Example: Digital Alpha, VAX-800, AS 400

Uses of Mini computers


 They are often used by small and medium sized companies to provide centralized store of
information.
 They are used for data processing.

 Mainframe Computers
1. Mainframe computers were introduced in 1975.
2. It is very large computer in size.
3. It is more powerful than mini computers and consists of multiple processors.
4. It is designed to perform multiple tasks for multiple users at the same time.
5. The user access a mainframe computer through personal computer.
6. It can execute 16 million instructions per second.
7. Example: CDC 6600, NEC 610, DEC 10

Uses of Mainframe Computers


 Mainframe computers are used in large organizations.
 They are big computer systems sensitive to temperature, humidity, dust etc.
 Qualified & trained operators are required to operate them.
 They have a wide range of peripherals attached.
 They have large storage capacity.
 They can use a wide variety of software’s.
 They are not user-friendly.
 They can be used for more mathematical calculations.

 Supercomputers
1. Supercomputers were introduced in 1980. Super computer is the fastest computer.
2. Supercomputer is the biggest in size and the most expensive in price than any other computers.
3. Supercomputer is the most sophisticated, complex and advance computer.
4. It has a very large storage capacity.
5. It can process trillions of instructions in one second.
6. Supercomputers are used for highly calculations intensive task.
7. Supercomputers are designed for ultra-high performance tasks such as weather analysis,
encryption cracking, and the creation of animation.
8. Example: IBM Roadrunner, IBM Blue Gene, PARAM Padma, etc.

Uses of Supercomputers
 Weather Forecasting
 Animated Graphics like Hollywood Movies
 Nuclear energy research
 Space Science
 Weapons and Missile design
 Petroleum Exploration etc.
 Supercomputing in India

India's supercomputer program was started in the late 1980s because Cray supercomputers
were denied for import due to an arms embargo imposed in India, as it was a dual use technology and
could be used for developing nuclear.

PARAM 8000 was India's first supercomputer. It was indigenously built in 1990 by Centre for
Development of Advanced Computing and was replicated and installed at ICAD Moscow in 1991
under Russian collaboration.

Supercomputer Organization
Anupam Bhabha Atomic Research Centre (BARC)
SAGA-220 Indian Space Research Organization (ISRO)
EKA Computational Research Laboratories
Vikram-100 Physical Research Laboratory
PARAM Yuva Centre for Development of Advanced Computing

Applications of computers:

 Schools and colleges


 Banks
 Office
 Stock control in business firms
 Stock exchange
 Research and developments
 Entertainment and news
 Government office
 Satellite communication
 Publishing
 Travel
 Computer-aided manufacturing (CAM)
 Hospital.
Chapter-2

INPUT OUTPUT MEMORY DEVICE

 Input Device:
 An input device is used to feed data into computer.
 Input devices are capable of converting data into a form which can be recognized by computer.
 A computer has several input device namely, Keyboard, Mouse, Trackball, Joystick, Scanner,
Light pen, Bar Code Reader, OCR, OMR, MICR etc.

Note: The device used to accept the data and instructions from the user is called input device.

 Keyboard:

 The most common input device is the keyboard.


 It is used to enter both numerical and character type data.
 It is like a mechanical type writer with alpha numeric and special keys, punctuation keys,
functional keys to perform specific. The keyboards contain 101 keys or 104 keys.
 The keyboard detects the key pressed and generates the corresponding ASCII codes which can be
recognized by the computer.
 Types of keyboard:
1. Standard keyboard: The standard keyboards have their basic layout. The average number of
keys on a regular keyboard is 105/108; QWERTY keyboards are the most common and have
the six alphabets Q, W, E, R, T, and Y in the first row.
2. Ergonomics: It refers to study of method 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.
3. Wireless keyboard: It is a keyboard that does not need to connect to the computer via a wire.
This makes very convenient for the use the keyboard comfortably. Wireless keyboard use
Bluetooth, Infrared (IR) to connect to the computer.
4. Virtual keyboard: It is a software device that led to use input data just like hardware
keyboard. They open up as an application and can be controlled by a mouse or wire touch
screen.
5. Compact keyboard: These keyboards are slim and usually do not have the numerical keypad
that is present on the right side of the keyboard these are typically used in laptops.
 MOUSE:

 Mouse is an input device that controls the movement of the cursor on the display screen.
 MOUSE stands for “Mechanically Operated User Serial Engine”.
 The Mouse is used as a pointing device.
 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.
 There are two types of mouse.
o Mechanical
o Optical
 Mechanical: This mouse has a small rubber ball underneath that moves against two rollers as it
passes across a flat surface.
 Optical: This mouse more accurate and has no moving parts. Ts use a laser to detect movement.

 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.
 The joystick can be moved in all four directions. The function of the joystick is similar to that of a
mouse.
 It is mainly used in playing computer games.
 Joysticks are also used for controlling machines such as cranes, trucks, underwater unmanned
vehicles, surveillance cameras and zero turning radius lawn mowers.

 SCANNER:

 The scanner is an input device which works more like a photocopy machine.
 It is used when some information is available on a paper and it is to be transferred to the computer
for further manipulation.
 The scanner captures images from the source which are then converted into the digital form.

 Optical Mark Reading and Recognition (OMR)

 Optical Mark Reader is a devce that reads pencil marks and converts them into computer
processable form.
 Special pre-printed forms are designed with boxes which can be marked with a dark pencil or ink.
 Such documents are read by a reader, which transcribes the marks into electrical pulses which are
transmitted to the computer.
 They are widely used in applications like objective type answer papers evaluation in which large
number of candidates appear, time shits of factory employees etc.

 Optical Character Recognition (OCR)

 The main use of these devices is to recognize alphabetic and numeric character printed on paper.
 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 a letters and punctuations marks and
stores.
 This can be edited using a word processor the size (width, height and depth) of the scanned.
 OCR’s are used in applications such as Credit Card billing and reading of pin code numbers in
large post office to sort mail geographically.

 Magnetic Ink Character Recognition (MICR)

 MICR is a form of character recognition that reads the text printed with magnetic charged ink.
 The shapes of the characters by sensing the magnetic charge in the ink and translates these shapes
into computer processed format.
 MICR is widely used by banks to process cheques.
 The cheque can be read using a special input unit, which recognizes magnetic ink characters.
 This method eliminates the manual errors. It also save time ensures security and accuracy of data.

 Output device:

 When the data and instruction are fed into the computer and processed the next step is get the
desired output.
 This output may be displayed on the monitor or printed on the computer.
 The output displayed on the monitor is called soft copy output.
 The output produced on a computer is called hard copy output.

Note: The device that displays output to the user is called output device.

 Monitor:

 It is commonly used output device sometimes called as display screen/VDU.


 Monitors are connected with the computer are similar in appears to a television set.
 Monitor display image and text.
 The smallest dot that can be displayed is called a pixel.
 The resolution of the monitor determines the quality of the display. Some popular resolutions are
640X480 pixels, 800X600 pixels and 1024X768 pixels.
 The different size of the monitor is measured diagonally may be 12”, 14”, 17”, 19”, 21”.
 The different types of monitors:
o CRT (Cathode Ray Tube)
o LCD (Liquid Crystal Display)
o TFT ( Thin Film Transistors)
o LED (Light Emitting Diode)

 Printer:

 Printer is an output device that prints text or images on paper.


 By printing you create a ‘hard copy’ of data.
 There are different kinds of printers, which vary in their speed and print quality.
 The two main types of printer namely;
 Impact Printers
 Non Impact Printers.

 Impact printers

 It includes printers that print by striking device against inked ribbon.


 Impact printers use a print head containing a number of metal pins, which strike an inked ribbon
placed between the print head and the paper.
 Line printers, dot-matrix printers are some of the impact printers.
 Characteristics of Impact Printers

1. In impact printers, there is physical contact with the paper to produce an image.
2. Due to being robust and low cost, they are useful for bulk printing.
3. Impact printers are ideal for printing multiple copies because they can easily print through many
layers of papers.
4. Due to its striking activity, impact printers are very noisy.
5. Since they are mechanical in nature, they tend to be slow.
6. Impact printers do not support transparencies.
7. Measured with characters per second.

 Line printer:

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

 Dot matrix printer:

 The most popular serial printer is the dot matrix printer.


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

 Non impact printer:

 Non impact printer don’t use striking device.


 The ink or semi –solid ink is stored in the printer cartridges and the flow of ink is controlled by the
processor.
 It is much faster and can print color, different font and size also.

 Characteristics of non impact printers:

1. They possess the ability to change type face automatically.


2. These printers produce high quality graphics.
3. These printers usually support the transparencies.
4. Measured in dots pen inches.
5. The speed is calculated by the number of pages per minute (PPM).
6. The size of the printing various A4, A3, A2, A0 and jumbo size.

 Thermal printer:

 Thermal printers are printers that produce images by pulling electrically heated pins against special
heat-sensitive paper.
 They are inexpensive and used widely in fax machine and calculators.
 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.

 Laser printer:

 Laser printer uses a laser beam and dry powered ink to produce a fine dot matrix pattern.
 In can produce very good quality of graphics images.
 Laser printers print one entire page at a time and are typically faster and have better quality output.
 One of the chief characteristics o laser printer is their resolution- how many dots per inch (dpi)
they lay down.
 The available resolutions range from 300 dpi at the low end to around 1200 dpi at the higher end.

 Inkjet printer:

 Inkjet printers use color cartridges which combine magenta, yellow and cyan links to create color
tones.
 A black cartridge is also used for crisp monochrome output.
 Inkjet printers works by spraying ionizing ink at a sheet of paper.
 Magnetized plates in the ink’s path direct the ink onto the paper in the described shape.
 It prints one line at a time. Print quality is high, speed is slow, typically about 100 CPS.

 Plotter:

 Plotter is an output device that draws shapes on paper based on commands from a computer.
 Plotter differs from printers in that they draw lines using a pen.
 As a result, they can produce continuous lines, whereas printers can only stimulate lines printing a
closely spaced series of dots.
 Multicolor plotters use different colored pens to draw different colors.
 Plotters are more expensive than printers.
 They used in engineering applications.

 Speakers:

 The speakers are the output device.


 The sound signals from analog/ digital are converted in to 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.
 Namely 2.1 or 5.1 which indicates the position of the speakers and tracking systems.

 Computer Memory

 Memory is an essential component of any digital computer.


 It is storing device. It stores programs and data, which is required by the CPU, and the results
generated after processing.
 This storage enables us to use the stored data to in future.

 There are two kinds of memory are commonly used in computers.


1. Primary Memory (Semi-Conductor Memory)
2. Secondary Memory ( Magnetic Memory)
 The storage capacity of a computer is measured in terms of Bytes.
 One byte includes a total of 8 individual units called as bits. One bit can store either a 0 or 1 in it.
 The table below gives the storage capacities.

Unit Symbol Equal to


Byte B 8 Bits
Kilobyte KB 1,024 B
Megabyte MB 1,024 KB
Gigabyte GB 1,024 MB
Terabyte TB 1,024 GB
Petabyte PB 1,024 TB
Exabyte EB 1,024 PB
Zettabyte ZB 1,024 EB
Yottabyte YB 1,024 ZB

 Primary Memory

 The Primary memory is the main memory of the computer.


 It stores the programs and data, which are currently needed by the CPU.
 The size of the main memory is comparatively much smaller than that of the secondary memory
because of its high cost.
 The CPU communicates directly only with the main memory.
 As the CPU works at very high speed, its matching memory must be very fast.
 Only primary memory devices can provide the matching speed.
 RAM and ROM’s are used as the main memory of the computer.
 Primary memory is of two types.
1. RAM (Random Access Memory)
2. ROM (Read Only Memory)

 Random Access Memory (RAM)

 RAM is also called as the main memory of a computer.


 This is really the main store and is the place where the program gets stored temporary.
 When the CPU runs a program, it fetches the program instructions from the RAM and carries them
out.
 If the CPU needs to store the results of the calculations it can store them in RAM.
 When we switch off a computer, whatever is stored in the RAM gets erased.
 It is a volatile form of memory.
 Types of RAM
o EDO RAM (Extended data output RAM)
o SRAM ( Static RAM)
o DDR RAM ( Double Data Rate RAM)

EDO RAM:

 EDO RAM stands for Extended Data Output RAM.


 It improves the time to read from memory on faster microprocessor such as Intel Pentium.
 EDO RAM was initially optimized for the 66 MHz Pentium

SRAM:

 SRAM stands for Static Random Access Memory.


 It is type of semiconductor memory that uses bi-stable latching circuitry to store each bit.
 Unlike dynamic RAM (DRAM), which stores bits in cells consisting of a capacitor and a
transistor,
 SRAM does not have to be periodically refreshed.

DDR RAM:

 DDRRAM stands for Double Data Rate Synchronous Dynamic Random Access Memory.
 It is type of very fast computer memory.
 It’ based on the same architecture as SDRAM, but uses the clock signal differently to transfer
twice the data in the same amount of time.

 Read Only Memory (ROM)

 ROM stands for “Read Only memory”.


 The information is pre-recorded into to 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 ROM are not erased, but remain stored
permanently.
 ROM is non-volatile memory.
 ROM stores critical programs such as the programs that boot the computer.
 Types of ROM
o PROM (Programmable ROM)
o EPROM (Erasable Programmable ROM)
o EEPROM (Electrically Erasable Programmable ROM )
 Programmable ROM: It is a memory on which data can be written only once. A variation of the
PROM chip that is not burnt at the manufacturing time, but can be programmed using PROM
programmer or a PROM burner.
 Erasable Programmable ROM: The information can e erased and re-programmed using a special
PROM – programmer. AN EPROM differs from a PROM in that PROM can be written only once
and cannot be erased. But an ultraviolet light is used to erase the contents of EPROM.
 Electrically Erasable Programmable ROM: This is equivalent to EPROM, but does not require
ultraviolet light to erase its content. It can be erased by exposing it to an electrical charge.

 Difference between RAM and ROM

RAM ROM

RAM stands for Random Access Memory ROM stands for Read-Only Memory
RAM allows the computer to read ROM stores the program required to
data quickly to run applications. It allows initially boot the computer. It only allows
reading and writing. reading.
It is non-volatile i.e. its contents are
RAM is volatile i.e. its contents are lost
retained even when the device is powered
when the device is powered off.
off.
The two main types of RAM are static The types of ROM include PROM,
RAM and dynamic RAM. EPROM and EEPROM.

 Secondary Memory

 Since the storage capacity of the primary memory is not very large, it cannot hold a large amount
of data, including programs, which may be needed for processing. Thus, secondary storage devices
are necessary.
 The secondary memory is used as auxiliary memory. The secondary memory is used for bulk
storage or mass storage of programs, data, and other information.
 It has much larger capacity than main memory.
 The secondary memory retains the information once stored on it.
 The magnetic memory such as Hard Disk Drive (HDD), Compact Disk, Pen Drive, Memory cards
is the most commonly used secondary memory in the computer.
 The average time required to reach a storage location and obtain its contents is called its access
time.
 Magnetic Disks:

 Magnetic disks are thin circular plastic plates on which some magnetic material is coated.
 Magnetic disks come in various sizes and materials.
 They use the properties of magnetism to store the data on a magnetic surface.
 A disk pack normally consists of such disks mounted on a central shaft.
 The central shaft rotates at speeds of about 7200 revolutions per minute (RPM).
 In a disk plate information is stored on both surfaces. The surface is further divided into a number
of invisible concentric circles called as tracks.
 The tracks are further divided into various sections called as sectors.
 To store information, it is necessary for us to identify the track and sector where it has to be stored.
 The stored information can be read any number of times without affecting the stored data. But
when new data is written it erases the previously written data.
 Two types of magnetic disks are
o Hard Disk
o Floppy Disk

 Hard Disk:

 The most common physical device for storing files in the hard disk.
 The hard disk typically contains several rotating disk plates, which are permanently encased in a
hard disk.
 The surfaces of the plates are covered by metal oxide; electromagnetic recording heads.
 It performs read/write operation.
 There is one head for each surface, and all the head move together.
 The disk rotates at around 7200 rpm.
 Modern disks typically hold 260 GB to 1000 GB (TB) of data.
 The surface of a plate is organized has a number of concentric tracks. Each track is divided into
sectors. Set of matched tracks are called cylinders.

 Floppy Disk:

 Floppy diskette contains a single flat piece of circular plate (the disk) coated with metal oxide and
enclosed in plastic cover.
 Floppy disks are small and portable.
 The three common sizes are 3.5”, 5.25” and 8” diameter.
 Most commonly used floppy disks is of 3.5" in size with storage capacity of 1.44 MB of data.
 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.

 Optical Disk

 Optical disk is a random access, removable disk on which data is written and read through the use
of laser beam.
 Optical disk consists of rotating disk, which is coated with highly reflective material.
 Data recording on the disk is done by focusing a laser beam on the surface of the spinning disk,
which stores data as microscopic light and dark spots on the disk surface.
 The dark spots are called pits. The lighter, non-spitted surface areas of the disk are called lands.
 The process of recording data onto a optical disk are called burning.
 There are different types of optical laser disks.
o CD ROM
o DVD ROM
o BD ROM

 CD ROM

 CD-ROM stands for Compact Disk Read Only Memory.


 It is read only optical storage medium capable of holding up to 682 MB of data.
 Accessing of data from CD ROM is quite a bit faster than a floppy disk but slower than hard disk.
 To read a CD-ROM a device called CD-ROM drive is needed.
 CD technology uses a near infrared laser.
 There are two types of CD-ROM’s.
o CD-R: It is also called as Recordable CD
o CD-RW: It is also called as Re-Writable CD

 DVD

 DVD stands for “Digital Versatile Disk”.


 It is an optical disk technology with a 4.7 GB storage capacity.
 DVD can be single or double sided, and can have two layers on each side.
 A double sided, two-layered DVD will hold up to 17 GB of Video, Audio or other information.
 DVD technology uses a red laser.
 There are two types of DVD.
o DVD-R: It is also called as DVD Recordable.
o DVD-RW: It is also called as DVD Re-Writable.

 Blu-Ray Disk

 Blu-ray Disk, referred as BD.


 It is a high capacity storage technology with 25 GB to 50 GB capacity to store HD movies and
other information.
 The name Blu-ray is derived from the blue-violet color laser, used to read data stored on disk.

 Portable Storage Device:

 A Portable Storage Device (PSD) is a small hard drive designed to hold any kind of digital data.
 This is slightly different from a portable media player which stores and plays music and movies.
 Some are fixed size hard drives of 256 GB, 320 GB, 500 GB and 1 TB.
 It may be useful alternative to backing up or purging memory cards if a computer is unavailable
for downloading.

 Difference between Primary and Secondary Memory:

Primary Memory Secondary Memory


Semiconductor memory. Magnetic or Optical memory.
Volatile(Temporary) Non-Volatile(Permanent)
Expensive Less Expensive
Faster Slower
Also called as Main Memory Also called as Auxiliary Memory
Example: RAM, ROM Example: HDD, Pen drive etc.

 Cache Memory

 The cache memory (pronounced as cash) is placed in between the CPU and Main memory.
 It is much faster than main memory.
 Its access time is much less compared to that of the main memory.
 The cache memory is an intermediate memory and is not accessible to users.
 It stores instructions and data, which are to be immediately executed.
 It is used to reduce the average access time reading data, which normally stored in the main
memory.
 The cache memory increases the operating speed of the system. But it is much costlier than main
memory.
 There are two levels of cache memory L1 and L2.
 L1 cache memory will present inside the CPU, whereas L2 cache will be present on the
motherboard.
Chapter -3
DATA REPRESENTATION
DATA REPRESENTATION

Introduction:
In Digital Computer, data and instructions are stored in
computer 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 converted to bits, understandable by the
computer.
Number systems:
Number systems are basically classified into two types. They
are:
1. Non-positional number system
2. Positional number system
Non-Positional Number System
• In olden days people used this type of number system for
simple calculations like additions and subtractions.
• The non-positional number system consists of different
symbols that are used to represent numbers.
• Roman number system is an example of the non-positional
number system i.e. I=1, V=5, X=10, L=50.
• This number system cannot be used effectively to perform
arithmetic operations.
Positional Number System
In this number system, the value of each digit depends
on its position.
Different types of positional number system are:
– Decimal number system
– Binary number system
– Octal number system
– Hexadecimal number system
• The total number of digits present in the number system
is called its Base or Radix.
• Every number is represented by a base (or radix) x,
which represents x digits.
• The base is written after the number as subscript such as
512(10) Since it is a Decimal number its base is 10.
Decimal Number System
• It is the most widely used number system.
• The decimal number system consists of 10 digits from 0 to 9.
• It has 10 digits and hence its base or radix is 10.
• These digits can be used to represent any numeric value.
Example: 123(10), 456(10), 7890(10).
• The positional values of each digit is represented in power of 10.
Consider a decimal number 542.76(10) . Its positional values are given
as follows:
Hundreds Tens Units One-tenth One-hundredth
Weights 102 101 100 10-1 10-2
Digits 5 4 2 7 6
Positional 100 10 1 0.1 0.01
Values
Binary Number System
• Digital computer represents all kinds of data and information in the
binary system.
• Binary number system consists of two digits 0 (low voltage) and 1
(high voltage) hence its base or radix is 2.
• Each digit or bit in binary number system can be 0 or 1.
Example: 1011(2), 111(2), 100001(2)
• The positional values of each bit is expressed in power of 2.
Consider a binary number 11011.101(2) Its positional values are given
as follows:

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

Bits 1 1 0 1 1 1 0 1

Positional 16 8 4 2 1 0.5 0.25 0.125


Values
Octal Number System
• The octal number system has digits starting from 0 to 7.
• The base or radix of this system is 8.
• Any digit in this system should be always less than 8.
Example: 123(8), 236(8), 564(8)
• The number 6418 is not a valid octal number because 8 is not a valid
octal digit.
• The positional values of octal digits are expressed in power of 8.
Consider a Octal number 234.56(8) Its positional values are given as
follows:
Weights 82 81 80 8-1 8-2

Digits 2 3 4 5 6
Positional 64 8 1 0.125 0.03125
Values
Hexadecimal Number System
• The hexadecimal number system consists of 16 digits from 0 to 9 and
A to F.
• The letters A to F represent decimal numbers from 10 to 15.
That is, ‘A’ represents 10, ‘B’ represents 11, ‘C’ represents 12, ‘D’
represents 13, ‘E’ represents 14 and ‘F’ represents 15.
• The base or radix of this number system is 16.
Example: A4 (16), 1AB(16), 934(16), C (16)
• The positional values of the hexadecimal digits are expressed in
power of 16.
Consider a Hexadecimal number 5AF.D(16) Its positional values are
given as follows:
Weights 162 161 160 16-1
Digits 5 A F D
Positional 256 16 1 0.0625
Values
Note:
In a binary number, the left most bit is the highest order bit. It is
called as Most Significant Bit (MSB). The right most bit is the
lower order bit. It is called as Least Significant Bit (LSB).
Example: In the binary number 11010(2)
The left most bit 1 is the highest order bit. It is called as Most
Significant Bit (MSB).
The right most bit 0 is the lower bit. It is called as Least
Significant Bit (LSB).
Number system Base Digits
Binary 2 0,1
Octal 8 0,1,2,3,4,5,6,7
Decimal 10 0,1,2,3,4,5,6,7,8,9
Hexadecimal 16 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
Computer codes:
• Computer codes are used for internal representation of
data in computers.
• Since computers use binary digits, computer codes use
binary coding schemes.
• Some of the commonly used computer codes are:
– Binary Coded Decimal (BCD)
– Extended Binary Coded Decimal Interchange Code (EBCDIC)
– American Standard Code for Information Interchange (ASCII)
– Excess-3 Code.
BCD code (or Weighted BCD Code or 8421 Code)
• BCD stands for Binary Coded Decimal.
• It is one of the early computer codes.
• In this code each decimal digit is represented by a 4-bit binary
number.
• In this coding system, the bits are given from left to right, the weights
8,4,2,1 respectively.
• In BCD code only 24=16 combinations are possible which is
insufficient for data representation in computers.

The BCD equivalent of each decimal digit is shown in table.

Example: The decimal number 537 is represented in BCD code as:


5 3 7
0101 0011 0111 Hence, the BCD of 537 is 010100110111
Excess-3 BCD code (or XS-3 Code)
• The Excess-3 BCD code is a non-weighted code used to express
decimal number.
• The name Excess-3 code derived from the fact that each binary code
is the corresponding BCD code plus 0011(2) (i.e. Decimal 3).
• This code is used in some old computers.
The following table gives the Excess-3 code equivalent of decimal (0-9).

The decimal number 537 is represented in Excess-3 code as:


5 3 7 Decimal Digit
0101 0011 0111 BCD Code
0011 0011 0011 Add 3
1000 0110 1010 Excess-3 Code
EBCDIC code
• It stand for Extended Binary Coded Decimal Interchange
Code.
• This was developed by IBM.
• It uses an 8-bit code and hence possible to represent
28 = 256 different characters or bit combinations.
• It is a coding method generally used by larger computers as
mainframes.
• EBCDIC is an 8-bit code; therefore, it is divided into two 4-
bit groups, where each 4-bit can be represented as 1
hexadecimal digit.
ASCII code
• It stands for the American Standard Code for Information
Interchange.
• It is a 7-bit code, which is possible to represent 27=128 characters.
• This coding is used to represent alphanumeric and some special
characters.
• It is used in most microcomputers ,minicomputers and in mainframe
computers.
• Since micro computers use 8 bits, the ASCII was extended to an 8 bit
code.
• The ASCII code is used for the transfer of alphanumeric information
between a computer and input/output devices.

Example: The ASCII code for uppercase M is 77.


The ASCII code for lowercase m is 109.
Number System Conversions
1. Conversion from Decimal to Binary:
Steps to convert decimal whole number to binary number:
Step 1: Divide the given decimal number by 2.
Step 2: Take the remainder and record it on the right side.
Step 3: Repeat the Step 1 and Step 2 until the quotient
becomes zero. (i.e., until the decimal number cannot be
divided further)
Step 4: The first remainder will be the LSB and the last
remainder is the MSB. The equivalent binary number is
then written from bottom to top i.e. from MSB to LSB.
Example: To convert the decimal number 53(10) to binary.

So decimal number 53 is written as 110101 in binary.


It can be written as 53(10)= 110101(2)
Steps to convert decimal fraction number to binary
number:
Step 1: Multiply the given decimal fraction number by 2.
Step 2: Note the carry and the product.
Step 3: Repeat step 1 and 2 until the fractional part
becomes zero.
Step 4: The first carry will be the MSB and the last carry is
the LSB. The equivalent binary fraction number is
written from top to bottom i.e. MSB to LSB.
Example 1: To convert the decimal number 0.3125(10) to binary.
Multiply by 2 Carry Product
0.3125 x 2 0 (MSB) 0.625
0.625 x 2 1 0.25
0.25 x 2 0 0.50
0.50 x 2 1(LSB) 0.00

Therefore, 0.3125(10) = 0.0101(2)


(2nd method)
Example 2: To convert the decimal number 152.671875(10)
to binary.
2. Conversion from Binary to Decimal:
Steps to convert binary number to decimal number:
Step 1: Multiply each bit of the binary number by its positional weight.
Step 2: Then, add all the products.
Step 3: After addition, the resultant is equal to the decimal value of
the binary number.
Example 1: To convert the binary number 1010111(2) to decimal.

Therefore, 1010111(2) = 87(10)


Example 2: To convert the binary number 11011.101(2) to decimal.
= 1x24 + 1x23 + 0x22 + 1x21 + 1x20 + 1x2-1 + 0x2-2 + 1x2-3
= 1x16 + 1x8 + 0x4+ 1x2 + 1x1 + 1x0.5+ 0x0.25+ 1x0.125
= 16 + 8 + 2 + 1 + 0.5 + 0.125
= 27.625(10)
3. Conversion from Decimal to Octal
Steps to convert decimal number to octal number
Step 1: Divide the given decimal number by 8.
Step 2: Take the remainder and record it on the side.
Step 3: Repeat the Step 1 and Step 2 until the decimal number cannot be
divided further(or quotient becomes zero).
Step 4: The first remainder will be the LSB and the last remainder is the MSB.
The equivalent octal number is then written from bottom to top i.e.
from MSB to LSB.
Example : To convert the decimal number 459(10) to octal number.

Note: If the decimal number is less than 8, then the octal equivalent is same as
decimal number.
4. Conversion from Octal to Decimal:
Steps to convert Octal number to decimal number:
Step 1: Multiply each bit of the Octal number by its
positional weight.
Step 2: Then, add all the products.
Step 3: After addition, the resultant is equal to the
decimal value of the Octal number.
Example : To convert the octal number 234.56(8) to decimal
number.
= 2x82 + 3x81 + 4x80 + 5x8-1 + 6x8-2
= 2x64+ 3x8 + 4x1 + 5x0.125+ 6x0.015625
= 128 + 24 + 4 + 0.625 + 0.09375
= 156.71875(10)
5. Conversion from Decimal to Hexadecimal:
• Steps to convert decimal number to hexadecimal number:
• Step 1: Divide the given decimal number by 16.
• Step 2: Take the remainder and record it on the right side.
• Step 3: Repeat the Step 1 and Step 2 until the quotient becomes zero.
(i.e., until the decimal number cannot be divided further)
• Step 4: The first remainder will be the LSB and the last remainder is
the MSB. The equivalent binary number is then written from bottom
to top i.e. from MSB to LSB.
Example: To convert Decimal number 559(10) to hexadecimal.
6. Conversion from Hexadecimal to Decimal:
Steps to convert hexadecimal number to decimal number:
Step 1: Multiply each bit of the hexadecimal number by its
positional weight.
Step 2: Then, add all the products.
Step 3: After addition, the resultant is equal to the
decimal value of the hexadecimal number.
Example : To convert the hexadecimal number 5AF.D(16)to
decimal number.
(Here A=10, F=15 and D=13)
= 5x162 + 10x161 + 15x160 + 13x16-1
= 5x256+ 10x16 + 15x1 + 13x0.0625
= 1280 + 160 + 15 + 0.8125
= 1455.8125(10)
Decimal Octal Binary Decimal Hexadecimal Binary
0 0 0000
0 0 000
1 1 0001
1 1 001
2 2 0010
2 2 010 3 3 0011
3 3 011 4 4 0100
5 5 0101
4 4 100
6 6 0110
5 5 101 7 7 0111
6 6 110 8 8 1000
9 9 1001
7 7 111
10 A 1010
11 B 1011
12 C 1100
13 D 1101
14 E 1110
15 F 1111
Conversion from Binary to Octal
Steps to convert from Binary to octal
Step 1: Group the binary digits into groups of 3 bits starting
from the binary point.
Step 2: If you are not able to form a group of three:
• For whole numbers, add a zero as the MSB until we
get group of 3 bits.
• For fractions, add a zero as the LSB until we get group
of 3 bits.
Step 3: Write the octal equivalent of each group.
Step 4: The resultant is equal to the octal equivalent of the
Binary number.
• Example 1: Consider the binary number 1010111(2)
001 010 111
1 2 7
Therefore, 1010111(2) = 127(8)
• Example 2: Consider the binary number 0.110111(2)
0.110 111
0. 6 7
Therefore, 0.110111(2) = 0.67(8)
• Example 3: Consider the binary number 1101.10111(2)
001 101.101 110
1 5 .5 6
Therefore, 1101.10111(2) = 15.56(8)
Conversion from Octal to Binary
Steps to convert from octal to binary
Step 1: Take the each digit from octal number
Step 2: Convert each digit to corresponding 3-bit binary
number.
• Example 1: Convert the octal number 456(8) into binary
4 5 6 Octal number
100 101 110 Binary equivalent
Therefore, 456(8) = 100101110(2)
• Example 2: Convert the octal number 73.16(8) into binary
7 3 . 1 6 Octal number
111 011 . 001 110 Binary equivalent
Therefore, 73.16(8) = 111011.001110(2)
• Conversion from Binary to Hexadecimal
Steps to convert from Binary to hexadecimal
Step 1: Group the binary digits into groups of 4 bits starting
from the binary point.
Step 2: If you are not able to form a group of four:
• For whole numbers, add a zero as the MSB until we
get group of 4 bits.
• For fractions, add a zero as the LSB until we get group
of 4 bits.
Step 3: Write the hexadecimal equivalent of each group.
Step 4: The resultant is equal to the hexadecimal equivalent
of the Binary number.
• Example 1: Consider the binary number 1011001(2)
0101 1001
5 9
Therefore, 1011001(2) = 59(16)
• Example 2: Consider the binary number 0.11010111(2)
0.1101 0111
0. D 7
Therefore, 0.110111(2) = 0.D7(16)
• Example 3: Consider the binary number 100110.111010(2)
0010 0110.1110 1000
2 6 . E 8
Therefore, 100110.111010(2) = 26.E8(16)
Conversion from Hexadecimal to Binary
Steps to convert from hexadecimal to binary
Step 1: Take each digit from hexadecimal number
Step 2: Convert each digit to 4-bit binary number.
Example1 : Consider the hexadecimal number CEBA(16)
C E B A Hexadecimal number
12 14 11 10
1100 1110 1011 1010 Binary equivalent
Therefore, CEBA(16) = 1100 1110 1011 1010(2)

Example 2: Consider the Hexadecimal number D2.45(16)


D 2 . 4 5 Hexadecimal number
13 2 4 5
1101 0010 . 0100 0101 Binary equivalent
Therefore, D2.45(16) = 11010010.01000101(2)
Conversion from Octal to Hexadecimal
Steps to convert from Octal to Hexadecimal
Step 1: Write the binary equivalent of each octal digit.
Step 2: Regroup them into 4 bits from the right side. Add zeros as MSB
if necessary.
Step 3: Convert each 4 bit group into its equivalent hexadecimal digit.
Example: Consider the octal number 274 (8)
2 7 4 Octal number
010 111 100 Binary equivalent
Now group the binary equivalent into 4 bits from right side.
0000 1011 1100
0 B C Hexadecimal equivalent
Therefore, 274 (8)= BC(16)
Conversion from Hexadecimal to Octal
Steps to convert from Hexadecimal to Octal
Step 1: Write the binary equivalent of each hexadecimal digit.
Step 2: Regroup them into 3 bits from the right side. Add zeros as MSB
if necessary.
Step 3: Convert each 3 bit group into its equivalent Octal digit.
Example: Consider the hexadecimal number FADE (16)
F A D E Hexadecimal number
15 10 13 14
1111 1010 1101 1110 Binary equivalent
Now group the binary equivalent into 3 bits from right side.
001 111 101 011 011 110
1 7 5 3 3 6
Therefore, FADE(16)= 175336(8)
Binary arithmetic
• It involves addition, subtraction, multiplication
and division operations.
• Binary arithmetic is much simpler to learn
because system deals with only two digit 0’s
and 1’s.
• When binary arithmetic operations are
performed on binary numbers, the results
are also 0’s and 1’s.
Binary Addition
• The addition of two binary numbers is performed in same
manner as the addition of decimal number.
The basic rules of binary addition are:
Addend 1 Addend 2 Sum Carry
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1

If there are three 1’s to be added:

Addend 1 Addend 2 Addend 3 Sum Carry


1 1 1 1 1
Example 1: Add the following numbers
a) 4 and 3 b) 9 and 5
Decimal Binary Decimal Binary
4 0100 9 1001
+3 +0 0 1 1 +4 +0 1 0 0
7 0111 13 1101
Example 2: Add 75 and 18.
First convert 75 and 18 to binary.
26 25 24 23 22 21 20

64 32 16 8 4 2 1
75(10)=64+0+0+8+0+2+1=1001011(2)
18(10)=16+0+0+2+0=10010(2)
Adding two 1’s
Sum=0, Carry=1
Carry 1
1001011
+10010
1011101 Sum = 93(10)
Example 3: Add 27 and 1.
First convert 27 and 1 to binary.
24 23 22 21 20
16 8 4 2 1

27(10)=16+8+0+2+1=11011(2)
1(10) =0001(2) Adding two 1’s
Sum=0, Carry=1

Carry 1 1

1 1 0 1 1
0 0 0 1
1 1 1 0 0 Sum=28(10)
Example 4: Add 1010101 and 1010111

Adding three 1’s


Carry 1 1 11 Sum=1, Carry=1
1010101
1010111
10101100 Sum
Example 5: Add binary number 1011.011 and
1101.111
Adding three 1’s
Sum=1, Carry=1
Carry 1 1 1 1 .1 1

1 0 1 1 .0 1 1
1 1 0 1 .1 1 1
1 1 0 0 1. 0 1 0 Sum
Binary Subtraction
• The subtraction of two binary numbers is performed in
same manner as the addition of decimal number.
The basic rules of binary addition are:
Minuend Subtrahend Difference Borrow
0 0 0 0
0 1 1 1
1 0 1 0
1 1 0 0

When we subtract 1 from 0, it is necessary to borrow 1


from the next left column i.e. from the next higher order
position.
Example 1: Subtract the following numbers:
a)10 from 14 b) 9 from 29
Decimal Binary Decimal Binary
14 1110 29 11101
- 10 -1010 - 09 - 01 0 0 1
4 0100 20 10100

c) 3 from 5 d) 0110100 from 1011000


Decimal Binary
1011000
5 0101 0110100
-3 0011 0100100
2 0010
Example 2: Subtract 25 from 75
First convert 75 and 25 to binary.

Therefore 75(10)-25(10)=50(10)
=1001011(2)- 11001(2)=110010(2)
Representation of signed Integers
• The digital computer handle both positive and negative
integer.
• It means, is required for representing the sign of the number
(- or +), but cannot use the sign (-) to denote the negative
number or sign (+) to denote the positive number.
• So, this is done by adding the leftmost bit to the number
called sign bit.
• A positive number has a sign bit 0, while the negative has a
sign bit 1.
• It is also called as fixed point representation.
• A negative signed integer can be represented in one of the
following:
1) Sign and magnitude method
2) One’s complement method
3) Two’s complement method
Sign and magnitude method
• An integer containing a sign bit followed by magnitude bits
are called sign-magnitude integer.
• In this method, first bit (MSB) is considered as a sign bit
and the remaining bits stand for magnitude.
• Here positive number starts with 0 and negative number
starts with 1.
1’s Complement representation
• This is the simplest method of representing negative binary
number.
• The 1’s complement of a binary number is obtained by
changing each 0 to 1 and each 1 to 0.
• In other words, change each bit in the number to its
complement.
Example 1: Find the 1’s complement of 101000.
Original binary number 101000
1’s compliment 010111
Example 2: Find the 1’s complement of 1010111.
Original binary number 1010111
1’s compliment 0101000
2’s Complement representation
• The 2’s complement of a binary number is obtained by
taking 1’s complement of the number and adding 1 to the
Least Significant Bit (LSB) position.
• The general procedure to find 2’s complement is given by:
2’s Complement = 1’s Complement + 1
Example 1: Find the 2’s complement of 101000.
Original binary number 101000

Find 1’s compliment 010111


Add 1 to LSB 1
2’s compliment 011000
Example 2: Find the 2’s complement of 1011101.
Original binary number 1011101

Find 1’s Complement 0100010


Add 1 to LSB 1
2’s Complement 0100011
Subtraction using 1’s Complement
Case 1: 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 1: Subtract 15 from 23 using 1’s complement.
Decimal Binary
Minuend 23 10111
Subtrahend 15 01111
Find 1’s complement of subtrahend and add it to Minuend.
1’s complement of subtrahend is 10000
Minuend + 1’s complement of subtrahend is 1 0 1 1 1
+1 0 0 0 0
End around carry 1 00111
Add end around carry to LSB +1
Difference is 1000
Example 2: Subtract 14 from 25 using 1’s complement.
Decimal Binary
Minuend 25 11001
Subtrahend 14 01110
Find 1’s complement of subtrahend and add it to Minuend.
1’s complement of subtrahend is 10001
Minuend + 1’s complement of subtrahend is 1 1 0 0 1
+10001
End around carry 1 01010
Add end around carry to LSB +1
Difference is 1011
Case 2: Subtracting a larger number from a smaller
number (Minuend is less than Subtrahend)
Step 1: Find the 1’s complement of the subtrahend.
Step 2: Add this to the minuend.
Step 3: There will be no carry, Re-complement (find the 1’s
complement of) the answer.
Step 4: Place a negative sign in front of the answer to get the
difference.
Example 1: Subtract 23 from 15 using 1’s complement.
Decimal Binary
Minuend 15 01111
Subtrahend 23 10111
Find 1’s complement of subtrahend and add it to Minuend.
1’s complement of subtrahend is 01000
Minuend + 1’s complement of subtrahend is 0 1 1 1 1
+0 1 0 0 0
No carry 10111
1’s complement of answer is 01000
Difference is -1 0 0 0
Example 2: Subtract 25 from 14 using 1’s complement.
Decimal Binary
Minuend 14 01110
Subtrahend 25 11001
Find 1’s complement of subtrahend and add it to Minuend.
1’s complement of subtrahend is 00110
Minuend + 1’s complement of subtrahend is 0 1 1 1 0
+00110
No carry 10100
1’s complement of answer is 01011
Difference is -1 0 1 1
Subtraction using 2’s Complement
Case 1: Subtracting a smaller number from a larger
number (Minuend is greater than Subtrahend)
Step 1: Find the 2’s complement of the subtrahend.
Step 2: Add this to the minuend.
Step 3: Carry is generated, discard the carry.
Step 4: The remaining bits give the final difference.
Example 1: Subtract 9 from 17 using 2’s complement.
Decimal Binary
Minuend 17 10001
Subtrahend 9 01001
Find 2’s complement of subtrahend and add it to Minuend.
2’s complement of subtrahend is = 1’s complement of
subtrahend + 1
= 10110+1
= 10111
Minuend + 2’s complement of subtrahend is 1 0 0 0 1
+10111
End around carry 1 01000
Discard the carry
Difference is 1000
Example 2: Subtract 8 from 20 using 2’s complement.
Decimal Binary
Minuend 20 10100
Subtrahend 8 01000
Find 2’s complement of subtrahend and add it to Minuend.
2’s complement of subtrahend is = 1’s complement of
subtrahend + 1
= 10111+1
= 11000
Minuend + 2’s complement of subtrahend is 1 0 1 0 0
+11000
End around carry 1 01100
Discard the carry
Difference is 1100
Case 2: Subtracting a larger number from a smaller
number (Minuend is less than Subtrahend)
Step 1: Find the 2’s complement of the subtrahend.
Step 2: Add this to the minuend.
Step 3: There will be no carry. Find the 2’s complement of the
answer.
Step 4: Place a negative sign in front of the answer to get the
difference.
Example 1: Subtract 17 from 9 using 2’s complement.
Decimal Binary
Minuend 9 01001
Subtrahend 17 10001
Find 2’s complement of subtrahend and add it to Minuend.
2’s complement of subtrahend is = 1’s complement of
subtrahend + 1
= 01110+1
= 01111
Minuend + 2’s complement of subtrahend is 0 1 0 0 1
+01111
No carry 11000
2’s complement of answer is = 1’s complement of answer + 1
= 00111+1
= 01000
Difference is -1000
Example 2: Subtract 20 from 8 using 2’s complement.
Decimal Binary
Minuend 8 01000
Subtrahend 20 10100
Find 2’s complement of subtrahend and add it to Minuend.
2’s complement of subtrahend is = 1’s complement of
subtrahend + 1
= 01011 +1
= 01100
Minuend + 2’s complement of subtrahend is 0 1 0 0 0
+01100
No carry 10100
2’s complement of answer is = 1’s complement of answer + 1
= 01011+1
= 01100
Difference is -1 1 0 0
Chapter-4

SOFTWARE CONCEPTS

 Introduction
 A computer system has three components viz.
o Hardware
o Software
o User
 Hardware: It consists of the physical components of a computer.
 Software: A set of instructions that tells the computer to perform an intended task.

 Types of Software
 Software is broadly classified into two categories namely,
o System Software
o Application Software

 System Software
 System software is a computer program that controls the system hardware and interacts with
application software.
 System software is hardware dependent and not portable.
 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 the
system software.
 System software is of three types:
o Language Translators
o Operating System
o Utilities Software

 Application Software
 Application software that has been written to process performs a specific job.
 Application software is generally written in high level languages.
 It focus is on the application, not the computing system.
 Application software is classified into two types:
o Application Specific
o General Purpose
 Application specific software is created to execute an exact task.
 It has a limited task. For example accounting software for maintaining accounts.
 General purpose software is not limited to only one function.
 For example: Microsoft office (MS-Word, MS-Excel), Tally, Oracle etc.

COMPUTER SOFTWARE

APPLICATION SOFTWARE SYSTEM SOFTWARE

Application Specific Language Translators Operating System Utilities Software

General Purpose Assembler LINUX Anti Virus

Compiler Windows Backup


Software
Interpreters

Loader & Linker

 Introduction to Computer Languages


 Programming Language is a set of rules called syntax which user has to follow, to instruct the
computer what operation are to be performed.
 Computer language are classified into two categories:
o Low-Level Languages
 Machine level languages
 Assembly languages
o High-Level Languages
 General Purpose languages (Ex: BASIC, PASCAL, C)
 Specific purpose languages (Ex: COBOL, FORTAN, C++)

 Machine Level Language


 Machine level language is the fundamental language of a computer.
 It is written using binary numbers i.e. 0‟s and 1‟s.
 A program written in the machine level language is called Machine code.
 The instructions provided in machine language are directly understood by the computer and
converted into electrical signals to run the computer.
 For example a typical program in machine language to add two numbers:
STATEMENTS ACTION
0001 00110010 Load the data
0100 10100101 Add the contents
1000 00101001 Store the results
0000 00000000 Stop

 An instruction given in the machine language has two parts:


o OPCODE (Operation Code)
o Operand (Address/ Location)
 The first 4-bit represents Opcode denoting operation such as load, move, store etc.
 The last 8-bit represents the operand denoting the address.
 Advantages: It can be directly typed and executed and no compilation or translation is requires.
 Disadvantage: These instructions are machine dependent and it is difficult to program, modify
and debug errors.

 Assembly Level Language:


 Assembly level language is a low-level programming language that allows a user to write
programs using letters, words and symbols called mnemonics, instead of the binary digits used in
machine level languages.
 A program written in the assembly level language is called Assembly code.
 For example a typical program in assembly language to add two numbers:
STATEMENTS ACTION
STA A Load the data to accumulator
ADD B Add the contents of B to Accumulator
STR C Store the results in location C
PRT C Print the results
HLT Stop

 However a program in assembly language has to be converted to its equivalent machine language
to be excuted on computer.
 The translator program that converts an assembly code into machine code is called an assembler.
 Advantages: Mnemonic code are easy to remember, easy to understand, easy to modify and
debug.
 Disadvantage: These languages are the mnemonic are machine dependent and assembly language
programming takes longer to code.
 High-level Languages
 A language designed to make programming easier through the use of familiar English words and
symbols.
 High-level languages used English like language, which are easier to learn and use.
 High-level languages are machine independent. Therefore, a program written for one computer can
be executed on different computers with no or only slight modifications.
 Some of the high-level languages are C, C++, JAVA, FORTRAN, QBASIC, and PASCAL.
 For example a typical program in high level language to add two numbers:
cin>>a>>b;
c = a + b;
cout<< “ Answer = “ << c;
 However a program in high-level language has to be converted to its equivalent machine language
to be excuted on computer.
 The translator program that converts an high level code into machine code is called an compiler.
 Advantage:
o HLL‟s are machine independent.
o Easy to learn and understand.
o Easy to modify and debug the program.
 Disadvantage:
o HLL is slower in execution.
o HLL requires a compiler to convert source code to object code.
o HLL take more time to execute and require more memory.

 Language Translators
 The translator translates the high-level language to low level language.
 There are three types of translators: Compilers, Interpreters, and Assemblers.

Translators

Assembler Complier Interpreters

 Assembler:
 Assembler is system software which translates an assembly language program into its machine
language.
 It recognizes the mnemonics used in the assembly level languages and substitutes the required
machine code for each instruction.
 Example: TASM (Turbo Assembler), MASM (Microsoft Macro Assembler) etc.

 Compilers:
 Compiler is system software that translates high-level language (source code) into the machine
level language (machine/object code).
 It reads the whole program and translates the entire program at once into a series of machine level
language instructions.
 Once compiled, the program normally gets saved automatically and can be executed directly.
 Examples: C, C++.

 Interpreters:
 An Interpreter reads once a statement of a high-level language program at a time and translates it
into machine level language and executes it immediately.
 It continues to read, translate and execute the statements one by one until it reaches the end of the
program.
 Therefore, it is slower than a compiler.
 The machine code produced by the interpreter is not saved and hence, to execute a statement again,
it has to be interpreted again.
 Example: BASIC, PROLOG

 Linker and Loader:


 A source program written in high-level languages may contain a number of modules or segments.
To execute properly the modules are to be linked so that execution of the program is sequential.
 This operation is performed by software called as the linker.
 A linker is system software that links (combines) smaller programs to form a single 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 software called as the loader.
 A loader is system software that loads machine code of a program into the system memory
and prepares these programs for execution.

 Utility Software
 Utilities are those helpful programs that assist the computer by performing helpful functions like
backing up disk, scanning/cleaning viruses etc.
 Utility software is generally called as Application oriented ready-made system programs.
 Some of the important utility software is: Text editor, Backup utility, Disk Defragmenter,
Antivirus software.

 Operating System(OS):
 An operating system is a set of programs which acts
as an interface between the user and the computer.
 The main system software is the operating systems,
which starts up the computer and control its
operation.
 Operating system manages the resource, resolves
conflicts‟ and tries to optimize the performance of the
system.
 The user communicates with the computer through
operating system commands and program
instructions.
 Operating System plays an important role in loading programs from disk into memory, displaying
message, translating program and in outputting the results.
 Some examples of operating system are: UNIX, LINUX, MS-DOS, and Microsoft Windows such
as Win 95, Win 98, Win 2000, Win XP, Win 7, Win 8, Android, Mac OS etc.

 Functions of Operating System(OS):


 Main functions of the operating system are as follows:
o Memory Management o File Management
o Process Management o Protection and Security
o Device Management o User interface or Command interpreter.
 Memory Management:
 The activities of memory management handled by OS are:
o Allocate memory
o Free Memory
o Re-allocate memory to a program when a used block is freed
o Keep track of memory usage.

 Process Management:
 The activities of process management handled by OS are:
o Control access to shared resources like file, memory I/O and CPU
o Control execution of applications
o Create, execute and delete a process
o Cancel or resume a process
o Schedule a process
o Synchronization, communication and deadlock handling for process

 Device Management:
 The activities of device management task handled by OS are:
o Open, close and write device drivers.
o Communication, control and monitor the device drivers.

 File Management:
 The activities of file management task handled by OS are:
o Create and delete both files and directories
o Provide access to files
o Allocate space for files
o Keep back-up of files
o Secure files

 Protection and Security:


 OS protects the resource of system.
 User authentication, file attributes like read, write, encryption and back-up of data are used by OS
to provide basic protection.

 User Interface or Command Interpreter:


 OS provides an interface between the user and the computer hardware.
 The user interface is a set of commands or a Graphical User Interface via which the user interacts
with the application and the hardware.

 Types of Operating System(OS):

 The different types of operating system are:


o Single user Operating System
o Batch Operating System
o Multiprogramming Operating System
 Multitasking Operating System
 Multiuser Operating System
 Time sharing System (Online /Multiuser)
 Real time system
o Distributed Operating System
o Network Operating System
o Multithreading Operating System

 Single User Operating System:


 This OS allows only one user to share the system resource including the CPU.
 These are mainly the operating system configured for the use of desktop PC and laptops.
 DOS and Windows- 95, Win- 98, Apple Macintosh etc are example.

 Batch Operating System:


 Batch is defined as a group of job with
similar needs and similar resource
requirements.
 The operating system that allows users to
create batches and execute each batch
sequentially, processing all jobs of batch
considering them as a single process is
called “Batch Operating system”
 It allows litter or no interaction between users and executing programs.
 This is well suited for applications with large computation time and no user interaction.
 Payroll, forecasting, statistical analysis are programs example for its usage.
 Advantages:
o User need not wait during its execution.
o It will function in FIFO (First In First Out) order.
 Disadvantages:
o Non-interactive mode of execution
o Offline debugging
 IBM System/360 Operating system is an example for Batch Operating system
 In DOS, we can emulate the batch processing using .BAT file.

 Multiprogramming Operating System:


 Multiprogramming is the capability of CPU to execute two or more
programs concurrently.
 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.
 Only one program is executed at a time.

 Multitasking Operating System:


 Multitasking operating systems allow more than one program to run at a time.
 Int gives you the perception of 2 or more tasks running at the same time. It does this by dividing
system resources amongest these tasks.
 Multitasking is usually implemented by code
and data of several programs in memory
simultaneously and multiplexing processor
and I/O device among them.
 Multitasking is also called context switching.
 Multitasking usually refers to a single user.
 Example: Windows 98

 Multi-user Operating System:


 A multi-user operating system allows multiple users on different computers or terminal to access a
single system with one OS on it.
 It creates and maintains individual user environments, individual authentication and security level
privileges, provides per user resource usage accounting.
 Time-Sharing Operating System:
 Time-Sharing operating system allows many users to share the computer resource simultaneously.
 Time sharing refers to the allocation of computer resource in time slots to several programs
simultaneously.
 Large CAD and text processing systems belong to time-
sharing OS.
 Most of the time-sharing operating systems adopted time-
slicing/ round robin scheduling algorithm.
 Each user/process will receive a portion of the time slot.
 UNIX, Windows Server is the example for multiprogramming, multi-use and time sharing
systems.

 Real-time Operating System:


 Real time systems refer to a computer and software systems that respond to events before the
events become obsolete.
 The primary objective of real-time systems is to provide quick event – response times and thus
meeting the scheduling deadlines.
 The main applications where real time systems are used include medical imaging systems,
industrial control systems, flight control and military application.
 Windows CE, Symbian, Lnux OS are example for real-time systems.

 Distributed Operating System:


 A distributed operating system is a collection of autonomous computer systems capable of
communication and cooperation via the software and hardware interconnections.
 For example: if we have „N‟ systems in a distributed environment then the distributed OS helps us
in balancing the load by sharing processors, I/O devices and memory etc.
 The ATM centers of a bank are example of distributed operating system.

 Network Operating System:


 A network operating system is a collection of software and associated protocols that allow a set of
autonomous computer which are interconnected by a computer network.
 It can be used in a convenient and cost-effective manner.
 In a network operating system the user are aware of the existence of multiple computers and can
log in to remote machines and copy files from one machine to another machine.
 Windows NT, windows server, LINUX are example.
 Multithreaded Operating System:
 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.
 It provides many logical paths through the program to be
executed simultaneously.
 Sun Solaris, Windows 2000, Multithreaded UNIX, LINUX are
examples.

 Functional Features of Operating System(OS):


 There are two types of user interface:
o Command-Line User Interface (CUI)
o Graphical User Interface (GUI)

 CUI Interface:
 CUI interface allows the user to interact with a computer through text terminal.
 It is a Non-graphical and text-based user interface.
 MS-DOS is an operating system which provides a CUI.
 The commands must be given at the command prompt ( C:\>)
 Both input and output are character based, the interface is also known as Character User Interface.

 GUI Interface:
 The GUI was first introduced in 1984 by Apple with Macintosh.
 GUI is an interface where the commands are selected from menus and icons rather the typing them
from the keyboard.
 It allows user to click on the required icon, with the help of Mouse.
 Windows Operating System is the most popular OS based on GUI.

 Difference between CUI and GUI:


CUI GUI
1. Command-line User Interface Graphical User Interface
The user must type the commands at
2. The user must click on icons, menus, dialog
command prompt to interact with the
boxes etc. to interact with the computer.
computer
3. The user must remember the commands The user need not remember any
and their parameters commands as it is available in the form of
menus and icons on monitor.
4. Mouse operation required to select the
Mouse operation not available for DOS
commands.
Chapter-5

PROBLEM SOLVING METHODOLOGY

 Introduction

 The term problem solving is used in many disciplines, sometimes with different perspectives and
often with different terminologies.
 The problem-solving process starts with the problem specification and end with a correct program.
 The steps to follow in the problem-solving process are:
 Problem definition
 Problem Analysis
 Algorithm development
 Coding
 Testing & Debugging
 Documentation & Maintenance
 The stages of analysis, design, programming, implementation and maintenance form the life cycle
of the system.

 Problem definition:
 This step defines the problem thoroughly. Here requirements are specified. This step includes
understanding the problem very well. The problem solver must understand problem very well to
solve problem efficiently.

 Problem Analysis:
 Analyzing the problem or analysis involves identifying the following:
 Inputs, i.e. the data you have to work with.
 Outputs i.e. the desired results.
 Any additional requirements on the solutions.

 ALGORITHM
 An Algorithm is a step-by-step procedure to solve a given problem.
 The word algorithm originates from the word „algorism‟ which means process of doing arithmetic
with Arabic numerals.
 In 9th-century Arab Mathematician, Mohammed Al-Khowarizmi, who developed methods for
solving problems which is, used specific step-by-step instructions.

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

Example: An algorithm to find the area of a rectangle can be expressed as follows:


 Given the length l and the breadth b, this algorithm finds the area of rectangle rec.
Step 1: START
Step 2: [Read the vales of l, b]
INPUT l, b
Step 3: [Calculate are of rectangle]
rec = l * b
Step 4: [Print the area of rectangle]
OUTPUT rec
Step 5: [End of Algorithm]
STOP
In the above example, we used = that represents assignment.

1. Design an algorithm to find the average of four numbers


Step 1: START
Step 2: INPUT A, B, C, D
Step 3: [Calculate] AVG = (A+B+C+D)/4
Step 4: OUTPUT AVG
Step 5: STOP
2. Design an algorithm to calculate the Simple Interest, given the Principal (P), and Rate (R)
and Time (T)
Step 1: START
Step 2: INPUT P, T, R
Step 3: [Calculate] SI = (P*T*R)/100
Step 4: OUTPUT SI
Step 5: STOP

3. Design an algorithm to find the greatest of three number (A, B, C)


Step 1: START
Step 2: INPUT A, B, C
Step 3: [Assign A to large]
Large = A
Step 4: [Compare large and B]
If( B > large )
Large = B
Endif
Step 5: [Compare large and C]
If( C > large )
Large = C
Endif
Step 6: [Print the largest number]
OUTPUT large
Step 7: STOP

4. Design an algorithm to find factorial of a number ( N )


Step 1: START
Step 2: 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: STOP
5. Design an algorithm to find Fibonacci series ( N )
Step 1: START
Step 2: INPUT N
Step 3: [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 loop]
Step 7: STOP

6. Design an algorithm to find the GCD of two numbers ( A, B )


Step 1: START
Step 2: INPUT A, B
Step 3: Repeat while ( B != 0 )
Rem = A % B
A=B
B = Rem
[End of While loop]
Step 4: [Print the last divisor]
PRINT A
Ste 5: STOP

 Advantage of Algorithm
1. It is a step-by-step representation of a solution to a given problem, which is very easy to
understand.
2. It has got a definite procedure, which can be executed within a set period of time.
3. It is independent of programming language.
4. It is easy to debug as every step has got its own logical sequence.
 Disadvantage of Algorithm
 It is time-consuming
 An algorithm is developed first which is converted into a flowchart and then into a computer
program.

 Analysis of Algorithm
 There may be more than one approach to solve a problem. The choice of a particular algorithm
depends on the following performance analysis and measurements.
o Space complexity: The amount of memory needed by the algorithm to complete its run.
o Time Complexity: The amount of time, the algorithm needed to complete its run.
 When we analyze an algorithm depends on input data, there are three cases
o Best Case
o Average Case
o Worst Case

 FLOWCHART
 A Flowchart is a pictorial or graphical representation of an algorithm.
 Flowchart plays an important role in the programming of a problem and helpful in understanding
the logic of program.
 Once the flow chart is drawn, it becomes easy to write program in any high level language.
 Flowcharts are classified into two categories:
1. Program Flowcharts
2. System Flowcharts
 Program flowcharts present a diagrammatic representation of a sequence of instructions for
solving a program.
 System flowcharts indicate the flow of data throughout a data processing system, as well as the
flow into and out of the system. Such flowcharts are widely used by designers, to explain a data
processing system.

 Importance of Flowchart
1. Communication: Flowcharts are better way of communication of the logic of a program.
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 programs.
PURPOSE
SYMBOLS

TERMINAL (START or STOP)


The beginning, end, or point of interruption in a program

INPUT OR OUTPUT
Input or Output data or information
PROCESSING
An instruction or group of instructions which changes the
program
PREPARATION[Looping]
An instruction or group of instructions which changes the
program
DECISION or BRANCHING
Represents a comparison, a question or a decision that
determinates alternative paths to be followed
PREDEFINED PROCESS
A group of operation not detailed in the particular set of
flowcharts
CONNECTOR
An entry form, or an exit to the another part of the
program flowchart
FLOW DIRECTION
The direction of processing or data flow.

4. Efficient coding: The flowchart acts as guide or blueprint during the system analysis and
program development phase.
5. Proper Debugging: The flow chart helps in debugging process.
6. Efficient program maintenance: The maintenance of a program become easy with the help of
flowcharts.

 Symbols Used In Flowcharts

Example: Design a flow chart and an algorithm to find the area of a square.
Step 1: START
Step 2: INPUT Side
Step 3: [Calculate Area]
s = (s1 + s2 + s3)/2
area = sqrt ( s * (s – s1) * (s – s2) * (s – s3))

Area = Side * Side OUTPUT area

Step 4: OUTPUT Area


Step 5: STOP
STOP

Swap 2 Number area of Circle & Circumference Area of triangle

1. Write a program, design a flow chart and an algorithm to find the larger of two numbers.
Step 1: Start
Step 2: Input A and B
Step 3: If(A>B) then
Output A
Else
Output B
[End if]
Step 4: Stop

START
START

INPUT A, B
INPUT rad

Temp = A;
area = 3.14 * rad * rad;
A = B;
circum = 2 * 3.14 * rad;
B = Temp;

OUTPUT A, OUTPUT area,

STOP STOP
2. Write a program, design a flow chart and an algorithm to find given number is odd or even.
Step 1: Start

Step 2: Input Num


Step 3: If((Num%2)!=0) then
Output Odd
Else
Output Even
[End if]
Step 4: Stop

 Advantage of Flowcharts

1. Flowcharts provide an excellent means of communication, which is very easy to understand.


2. It has got a definite procedure, which shows all the major parts of a program, It is easy to
convert it into a program.
3. It is independent of programming language.
4. It is easy to debug as every step has got its own logical sequence.

 Disadvantages of Flowcharts
1. It is time-consuming and it requires the uses of a number of symbols which are to be
properly represented.
2. The represented of complex logic is difficult in a flowchart.
3. Alterations and modifications can be only made by redrawing the flowcharts.

 Pseudo code:
 This is an abstract representation of program in English statement.
 In pseudo code English words & phrases are used to represent operations.
 Advantages: Easy to read, understand & modify.

 Coding or Programming
 The process of writing program instructions for an analyzed problem in a programming
language.
 It is the process of translating the algorithm or flowchart into the syntax of given purpose
language.

 You must convert each step of the algorithm into one or more statements in a programming
language such as C, C++, and Java etc.

Testing and Debugging

 Testing is the process of checking whether the program works according to the requirement
of the user.
 Debugging is the process of identifying and correcting or removing the Bugs (errors).
 There are four types of errors. They are
 Syntax errors
 Run-time errors
 Semantic errors
 Logic errors (bugs)

 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.
 Example:
void main( )
{
int a, b;
cout << „Enter the numbers” ;
cin >> a >> b;
cout << a + b
}
 In the example program, the fourth statement produces an syntax error as the missing semicolon.

 Run-time Error
 During execution of the program, some errors may occur. Such errors are called run-time
errors.
 Example: Divide by zero.

 Semantic Error
 An error, which occurs due to improper use of statements in programming language.
 Consider an expression C = A + B, indicating the values of the variable A and B are added and
assigned to variable C.
 If we written A + B = C, through the values of A and B are added, it cannot be assigned to variable
C written to the right of = Sign.
 This is semantic error.
 Logical Error
 Logical errors occur when there are mistakes in the logic of the program.
 Unlike other errors logical errors are not displayed while compiling because the compiler does not
understand the logic of the program.
 Example: To find the area of the circle, the formula to be used is area = 3.14 * r * r. But if we
written area = 3.14 * 2 * r, then the required output is not obtained even though the program is
successfully executed.

 Documentation and Maintenance


 Documentation is a reference material which explains the use and maintenance of the
program application for which it has been written.
 There are two types of documentation.
o Internal Documentation
o External Documentation.

 Internal Documentation:
 This is also known as technical documentation.
 It is meant for the programmer who may update the program code at later stages.
 It is done by:
o Defining meaningful variable names.
o Including comments in program code.
o Presenting the program code clearly.

 External Documentation:
 The program or application is supported with additional textual information about the application.
 It is useful for the user, administrator or developer.

 Maintenance:
 Program maintenance means periodic review of the programs and modifications based on
user’s requirements.
 Maintenance is a continuous task
 Documentation plays an important role in program maintenance. It helps speedy and efficient
maintenance.

 Programming Constructs
 A programming constructs is a statement in a program.
 There are 3 basic programming constructs.
o Sequential Constructs
o Selection Constructs
o Iteration Constructs

 Sequential Constructs:
 The program statements are executed one after another, in a sequence.
 Sequential constructs are:
o Input Statement
o Assignment Statement
o Output Statement

 Input Statement
 This statement is used to input values into the variables from the input device.
 Example: INPUT A, B, C
 Assignment Statement
 This statement is used to store a value in a variable.
 In many languages „=‟ is used as the assignment operator.
 Example: A = 10;
B = 5;
C = A + B;
 Output Statement
 This statement is used to display the values of variables on the standard output device.
 Example: OUTPUT C;

 Selection construct
 It is also known as conditional construct.
 This structure helps the programmer to take appropriate decision.
 There are five kinds of selection constructs, viz.
o Simple – if
o if – else
o if – else – if
o Nested – if
o Multiple Selection
 Simple - if :
 This structure helps to decide the execution of a particular statement based on a condition.
 This statement is also called as one-way branch.
 The general form of simple – if statement is:
if (Test Condition) // This Condition is true
Statement 1;
Statement 2;
 Here, the test condition is tested which results in either a TRUE
or FALSE value. If the result of the test condition is TRUE then
the Statement 1 is executed. Otherwise, Statement 2 is executed.
Ex: if( amount > = 5000 )
discount = amount * (10/100);
net-amount = amount – discount;

 if – else statement :
 This structure helps 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;
 Here, the test condition is tested. If the test-condition
is TRUE, statement-1 is executed. Otherwise
Statement 2 is executed.
Ex: if( amount > = 5000 )
discount = amount * (10/100);
else
discount = amount * (5/100);

 if – else - if statement :
 This structure helps 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.
 This statement is also called as multiple-way branch.
 The general form of if – else – if statement 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
 Here, Condition 1 is tested. If it is TRUE, Statement 1 is executed control 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 condition is satisfied, a statement called default statement is executed.
 Example:
if( marks > = 85 )
PRINT “Distinction”
else
if( marks > = 60 )
PRINT “First Class”
else
if( marks > = 50 )
PRINT “Second Class”
else
if( marks > = 35 )
PRINT “Pass”
else
PRINT “Fail”

 Nested if statement :
 The statement within the if statement is another if statement is called Nested – 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
tatement 4;

Ex: To find the greatest of three numbers a, b and c.


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

 Multiple Selection constructs or Switch statement :


 If there are more than two alternatives to be selected, multiple selection construct is used.
 The general form of Switch statement is:
Switch ( Expression )
{
Case Label-1: Statement 1;
Break;
Case Label-2: Statement 1;
Break;
…………..
Case Label-N: Statement N;
Break;
Default : Default- Statement;
}
 Ex: To find the name of the day given the day number
Switch ( dayno )
{
Case 1: PRINT “Sunday”;
Break;
Case 2: PRINT “Monday”;
Break;
Case 3: PRINT “Tuesday”;
Break;
Case 4: PRINT “Wednesday”;
Break;
Case 5: PRINT “Thursday”;
Break;
Case 6: PRINT “Friday”;
Break;
Case 7: PRINT “Saturday”;
Break;
default: PRINT “Invalid Day Number”;
}

 Iterative Constructs or Looping


 The process of repeated execution of a sequence of statements until some condition is
satisfied is called as iteration or repetition or loop.
 Iterative statements are also called as repetitive statement or looping statements.
 There are two iterative constructs, viz.
o Conditional Looping
o Unconditional Looping

 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 are:
o While
o do while

 Unconditional Looping :
 This statement executes a group of instructions is repeated for specified number of times.
 The unconditional looping constructs is for statement.

 While Constructs:
 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 of while structure is
While ( Test Condition)
Statement 1
Statement 2
……..
Statement N
End of While
 Example:
i = 1;
While ( i < = 5)
PRINT i;
i = i + 1;
end of while
Output: 1 2 3 4 5

 do while Constructs:
 This is 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 of while structure is
do
Statement 1
Statement 2
……..
Statement N
while ( Test Condition)
End of While
 Example:
sum = l;
i = 1;
do
sum = sum + i;
i = i + 1;
while ( i < = 100);

 Difference between while and do while loop:


while do while
This is pre- tested loop This is post tested loop
Minimum execution of loop is zero Minimum execution of loop is once.
Syntax: Syntax:
while ( Test condition ) do
{ {
statement 1; statement 1;
statement 2; statement 2;
…………….; statement n;
statement n; }
} while ( Test condition);
Semi colon is not used. Semi colon is used.

 for Constructs:
 This structure is the fixed execution structure.
 This structure is usually used when we know in advance exactly how many times asset of
statements is to be repeatedly executed again and again.
 This structure can be used as increment looping or decrement looping structure.
 The general form of for structure is as follows:
for ( Expression 1; Expression 2; Expression 3)
{
Statement 1;
Statement 2;
Statement N;
}
Where, Expression 1 represents Initialization
Expression 2 represents Condition
Expression 3 represents Increment/Decrement
 Example:
sum = 0;
for ( i=1; i<=10; i++)
sum = sum + i;

 Characteristics of a good program:


 The best program to solve a given problem is one that requires less space in memory, takes less
execution time, easy to modify and portable.
 Modification: A good program is the one which allows any modifications easily whenever
needed.
 Portability: A good program is the one which can be run on different type of machine with a
minimum or no change.
 Approaches to problem solving:

1. Top-down design:
 Top-down design involves dividing a problem into sub-problems and further dividing the sub-
problems into smaller sub-problems until it leads to sub-problems that can be implemented as
program statements.

 Where A is the main problem and remaining are the sub-problems.


 The top-down approach is taken for program design; the programs can be developed easily,
quickly, committing a minimum of errors.

2. Stepwise refinement:
 The process of breaking down the problem at each stage to obtain a computer solution is
called stepwise refinement.

3. Bottom-up design:
 A design method, in which system details are developed first, followed by major process.
 This approach is the reverse of top-down design.
 The process starts with identification of set of modules which are either available or to be
constructed.
 An attempt is made to combine the lower level modules to form modules of high level.
 Examples include object oriented programming using C++.

4. Programming techniques:

i. Unstructured programming:
 During learning stage by writing small and simple programs
without planning leads to unstructured programming.
Chapter 5- Problem Solving Methodology I PUC, MDRPUC, Hassan

ii. Procedural programming:


 This method allows us to combine the returning
sequences of statements into one single place.
 A procedure call is used to invoke the procedure.
After the sequence is processed, flow of control
proceeds right after the position where the call was
made.
 Procedures (sub procedures) programs can now be written as more structured and error
free.

iii. Structured programming:


 Structured programming is method of programming by using the following type of code
structures to write program:
o Sequence (input, output, assignment)
o Selection (if, if-else etc.)
o Iteration (while, do-while, for)
o Subroutines (functions)

iv. Modular programming:


 The process of splitting the lengthier and complex programs into number of smaller units
(modules) is called modularization and programming with such an approach is called
modular programming.
 This technique provides grouping of procedures
which are common functionality into separate
modules.
 Advantages of modular programming:
o Reusability
o Debugging is easier
o Building library
o Portability
Chapter-6
OBJECT ORIENTED CONCEPTS
 Introduction
 The programming languages deal with two important aspects – data and algorithm.
 Data is the main substance of the program and the algorithms are the methods that use these
programs.
 OOP is the principle of design and development of programs using the modular approach.

 Procedural programming:
 The procedural programming focuses on processing of
instructions in order to perform a desired computation.
Therefore it emphasizes more on doing things like
algorithms.
 This programming is lengthy, increases the complexity of
program, difficult to understand and modify the program.
 This technique is used in conventional programming languages such as C and Pascal.
 For example, procedural programs make use of branching statements, where the flow of
control changes its path according to the result of the test expression.
 Structured programming:
 Structured programming approach was a disciplined approach which limits the branching to a
small set of well-behaved construction (ex: if, if-else, while etc).
 The idea of Top-down design is to break a large program into smaller programs.
 The major drawback is that it is very difficult to model the real world scenario using this
model.

 Object oriented programming:


 Object oriented programming (OOP) is a concept that combines both the data and the
functions that operate on that data into a single unit called the object.
 Object is an identifiable entity with some characteristics and behavior.
 Top-down design is an approach of dividing a problem into sub problems and then dividing
the sub problems further into still smaller sub problems until it can be implemented for a
computer solution.
 Bottom up design is vice versa where solutions to smaller modules are integrated to find the
solution of overall problem.
 OOP follows bottom-up design technique.
 Class is the major concept that plays important role in this approach. Class is a template that
represents a group of objects which share common properties and relationships.

 OOPs characteristics:
The general concepts of OOPs includes
1. Modularity:
 Module is a logically self contained unit that can be tested and executed independently.
 Modularity is a technique adopted to divide a complex problem into a number of
self contained independent programming fragments or modules.

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

3. Data Encapsulation:
 Wrapping of data and functions into a single unit is called data
encapsulation.
 The concept of insulating the data from direct access by the program is called data hiding.

4. Inheritance:
 Inheritance is the process by which objects of one class acquires the properties of
the objects of another class. (Or)
 The process of deriving a new class from the existing class is called inheritance.

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.

6. Dynamic Binding:
 Binding means linking of a procedure call to the code to be executed when it is called.
 Dynamic binding means binding the procedure call during program run rime.

7. Message Passing:
 Passing message objects and invoking the function by the object by sending a message
is known as message passing.

 OOPs Benefits:
1. OOPs model the real world entity very well.
2. Inheritance eliminates the redundancy (repetition) of code and hence supports code
reusability.
3. Data hiding helps to build secured programs.
4. Multiple instances (objects) can be created.
5. Work can be divided easily.
6. OOPs can be easily upgraded from small to large systems.
7. Complexity can be easily managed.
8. Message passing concept helps the objects to communicate and share data.

 OOPs disadvantages:
1. OOPs use tricky method to do the programming.
2. Special skills such as thinking in terms of design skills, programming skills and object is
required for a programmer.
3. Proper planning and design is required before programming using OOPs technique.

 OOPs Applications:
1. Object oriented databases.
2. Hypermedia, expert text and hypertext.
3. Artificial intelligence and expert systems.
4. Decision support systems and office automation systems.
5. Parallel programming and neural networks.
6. CAD, CAM, CIM systems.
7. Simulation and modeling.
Chapter-7
INTRODUCTION TO C++
 History of C++:
 Until 1980, C programming was widely popular, and slowly people started realizing the drawbacks of
this language, at the same time a new programming approach that was Object Oriented Programming.
 The C++ programming language was created by Bjarne Stroustrup and his team at Bell Laboratories
(AT&T, USA) to help implement simulation projects in an object-oriented and efficient way.
 C++ is a superset of C because; any valid C program is valid C++ program too but not the vice versa
is not true.
 C++ can make use of existing C software libraries with major addition of “Class Construct”.
 This language was called “C with classes” and later in 1983, it was named “C++” by Rick Mascitii.
 As the name C++ implies, C++ was derived from the C programming language: ++ is the increment
operator in C.

 Characteristics of C++:
 Object-Oriented Programming: It allows the programmer to design applications like a
communication between object rather than on a structured sequence of code. It allows a greater
reusability of code in a more logical and productive way.
 Portability: We can compile the same C++ code in almost any type of computer & operating system
without making any changes.
 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.
 C Compatibility: Any code written in C can easily be included in a C++ program without making
any changes.
 Speed: The resulting code from a C++ compilation is very efficient due to its duality as high-level
and low-level language.
 Machine independent: It is a Machine Independent Language.
 Flexibility: It is highly flexible language and versatility.
 Wide range of library functions: It has huge library functions; it 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
system, Compilers, Editors and Database.
 C++ Character Set:
 Character Set means the valid set of characters that a language can recognizes.
 The character set of C++ includes the following:
Upper letters case A, B, C, D ............ X, Y, Z
Alphabets
Lower letters case a, b, c, d… ............ x, y, z
Digits 0,1,2,3………9
, comma . Period ` Apostrophe
: Colon ; Semicolon ? Question mark
! Exclamation _ Underscore | Pipeline
{Left brace } Right Brace # Hash
Special
[Left bracket ] Right Bracket ^ Caret
Characters
(Left parenthesis ) Right parenthesis & ampersand
/ Slash \ Back slash ~ Tilde
+ Plus sign - Minus Sign < Less Than
* Asterisk % Percentage > Greater Than

 C++ Tokens:
 The smallest individual unit in a program is known as token.
 These elements help us to construct statements, definitions, declarations, and so on, which in turn
helps us to construct complete program.
 Tokens used in C++ are:
1. Identifier
2. Reserved Keywords
3. Constants or Literals
4. Punctuators
5. Operators

 Identifiers:
 Identifiers is a name given to programming elements such as variables, functions, arrays, objects,
classes, etc.
 It contains letters, digits and underscore.
 C++ is a case sensitive; it treats uppercase and lowercase characters differently.
 The following are some valid identifiers: Pen time580 s2e2r3 _dos _HJI3_JK
 Rules to be followed while creating identifiers:
o Identifiers are a sequence of characters which should begin with the alphabet either from A-Z
(uppercase) or a-z (lowercase) or _ (underscore).
o C++ treats uppercase and lowercase characters differently. For example, DATA is not same as
data.
o No Special character is allowed except underscore “_”.
o Identifier should be single words i.e. blank spaces cannot be included in identifier.
o Reserved Keywords should not be used as identifiers.
o Identifiers should be of reasonable length.

 Keywords:
 Keyword is a predefined word that gives special meaning to the complier. The programmer is not
allowed to change its meaning.
 These are reserve for special purpose and must not be used as identifier name.
 Example: for, if, else, this, do, float, while, switch etc.
 There are keywords in C++ as mentioned below:

 Constants:
 A constant are identifiers whose value does not change during program execution.
 Constants are sometimes referred to as literal
 A constant or literal my be any one of the following:
o Integer Constant
o Floating Constant
o Character Constant
o String Constant

 Integer Constant:
 An integer constant is a whole number which can be either
positive or negative.
 They do not have fractional part or exponents.
 We can specify integer constants in decimal, octal or hexadecimal form.
o Decimal Integer Constant: It consists of any combination of digits taken from the set 0 to 9.
For example:
int a = 100; //Decimal Constant
int b = -145 // A negative decimal constant
int c = 065 // Leading zero specifies octal constant, not decimal
o Octal Integer Constant: It consists of any combination of digits taken from the set 0 to 7.
However the first digit must be 0, in order to identify the constant as octal number.
For example:
int a = 0374; //Octal Constant
int b = 097; // Error: 9 is not an octal digit.
o Hexadecimal Integer Constant: A Sequence of digits begin the specification with 0X or 0x,
followed by a sequence of digits in the range 0 to 9 and A (a) to F(f).
For example:
int a = 0x34;
int b = -0XABF;
o Unsigned Constant: To specify an unsigned type, use either u or U suffix. To specify a long
type, use either the l or L suffix.
For example:
unsigned a = 328u; //Unsigned value
long b = 0x7FFFFFL; //Long value specified as hex constant
unsigned long c = 0776745ul; //Unsigned long values as octal constant

 Floating Point Constant:


 Floating point constants are also called as “real constants”.
 These values contain decimal points (.) and can contain exponents.
 They are used to represent values that will have a fractional part and can be represented in two forms
(i.e. fractional form and exponent form)
 Floating-point constants have a “mantissa”, which specifies the value of the number, an “exponent”
which specifies the magnitude of the number, and an optional suffix that specifies the constant‟s type.
 The mantissa is specified as a sequence of digits followed by a period, followed by an optional
sequence of digits representing the fractional part of the number.
 The exponent, if present, specifies the magnitude of the number as a power of 10.
 Example: 23.46e0 // means it is equal to 23.46 x 100 = 23.46 x 1 = 23.46
 It may be a positive or negative number. A number with no sign is assumed to be a positive number.
For example, 345.89, 3.142

 Character Constants:
 Character constants are specified as single character enclosed in pair of single quotation marks.
 For example char ch = „P‟; //Specifies normal character constant
 A single character constant such as „D‟ or „r‟ will have char data type. These character constants will
be assigned numerical values.
 The numerical values are the ASCII values which are numbered sequentially for both uppercase and
lowercase letters.
 For example, ASCII value of A is 65, B is 66, …..Z is 90 (uppercase), a is 97, b is 98……. Z is 122
(lowercase), 0 is 48, 1 is 49, …… 9 is 57 (digits).
Escape Sequence Meaning Escape Sequence Meaning
\‟ Single Quote \” Double Quote
\? Question Mark \\ Back Slash
\0 Null Character \a Audible Bell
\b Backspace \f New Page
\n New Line \r Carriage Return
\t Horizontal Tab \v Vertical Tab
\nnn Arbitrary octal value \xnn Arbitrary Hexa Value
 There are certain characters used in C++ which represents character constants. These constants start
with a back slash ( \ ) followed by a character. They are normally called as escape sequence. Some
of the commonly used escape sequences are.

 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.
 String Constants:
 A string constant consists of zero or more character enclosed by double quotation marks (“).
 Multiple character constants are called string constants and they are treated as an array of char.
 By default compiler adds a special character called the “Null Character” (\0) at the end of the string
to mark the end of the string.
 For example: char str[15] = “C++ Programming” ;
 This is actually represented as char str[15] = “C++ Programming\0” in the memory.

 Punctuators:
 Punctuators in C++ have syntactic and semantic meaning to the compiler.
 Some punctuators can be either alone or in combination.
 The following characters are used as punctuators which are also known as separators in C++.
Punctuator Name Function
! Exclamation Used along with “=” to indicate “not equal to”
% Percentage Used along with format specifiers
& Ampersand Used to represent address location or bitwise operation
; Semicolon Used to represent statement terminator.
[] Brackets Used to array subscripts
() Parenthesis Used to represent function calls and function parameters.
{} Braces Used to represent start and end of a block of code.
# Ash sign Used to represent preprocessor directives.
\ Back slash Used to represent escape sequence
: Colon Used to represent labeled statement
= Equal to Used to represent an assigning operator.

 C++ Operators:
 An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.
 C++ is rich in built-in operators and there are almost 45 different operators.
 Operators in C++ are can be divided into the following classes:
o Arithmetic Operator o Conditional Operator
o Relational Operator o Bitwise Operator
o Logical Operator o Assignment Operator
o Unary Operator o Other Operator
 Operator operates on constants and variables which are called operands. Operators may also be
classified on the number of operands they act on either:

Unary Binary Ternary


The ternary operator
Unary operators operate The binary operator
operates on three
on only one operand. operates on two operands.
operands.

Example: ++, - - +, -, *, /, %, &&, || ?:

 Unary Operators
 Unary operators have only one operand; they are evaluated before any other operation containing
them gets evaluated.
 The following are the list of unary operators.
Operator Name Function
If a condition is true then Logical NOT operator will
! Logical NOT
make false.
& Address-of Used to give the address of the operand
One‟s Converts 1 to 0 and 0 to 1
~
Complement
Pointer Used along with the operand to represent the pointer data
*
dereference type.
+ Unary plus Used to represent a signed positive operand
++ Increment Used to increment an operand by 1
- Unary negation Used to represent a signed negative operand
-- Decrement Used to represent an operand by 1

 Increment Operator
Increment operator is used to increasing the value of an integer by one. This is represented by “++”.
Example: a++, a+1

 Decrement Operator
Decrement operator is used to decreasing the value of an integer by one. This is represented by “--”.
Example: a--, a-1

Let a=10 and b=5


a++; //a becomes 11
b--; //b becomes 4
Hint
 Both the increment & decrement operators come in two versions:

Prefix increment/decrement:
 When an increment or decrement operator precedes its operand, it is called prefix increment or
decrement (or pre-increment / decrement).
 In prefix increment/decrement, C++ performs the increment or decrement operation before using the
value of the operand.
 Example: If sum = 10 and count =20 then
Sum = sum + (++count);
 First count incremented and then evaluate sum = 31.

Postfix increment/decrement:
 When an increment or decrement operator follows its operand, it is called postfix increment or
decrement (or post-increment / decrement).
 In postfix increment/decrement, C++ first uses the value of the operand in evaluating the expression
before incrementing or decrementing the operand‟s value.
 Example: If sum = 10 and count =20 then
Sum = sum + (count++);
 First evaluate sum = 30, and then increment count to 21.

 Binary Operators
Operator Description Example( a=10, b=20)
+ Adds two operand a + b = 30
- Subtracts second operand from the first a - b = -10
* Multiply both operand a * b = 200
/ Divide numerator by denominators b/a=2
Modulus operators and remainder of after an
% b%a=0
integer division

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

 Arithmetic Operator
 Arithmetic operators are used to performing the basic arithmetic operations such as arithmetic,
subtraction, multiplication, division and modulo division (remainder after division).
 Relational Operator
 Relational Operator is used to comparing two operands given in expressions.
 They define the relationship that exists between two constants.
 For example, we may compare the age of two persons or the price of two items….these comparisons
can be done with the help of relational operators.
Operator Description Example (a=10, b=5)
Checks if the value of left operand is less than the
< a < b returns false(0)
value of right operand
Checks if the value of left operand is less than or equal
<= a <= b returns false(0)
to the value of right operand
Checks if the value of left operand is greater than the
> a > b returns true(1)
value of right operand
Checks if the value of left operand is greater than or
>= a >= b returns false(0)
equal to the value of right operand
== Checks if the value of two operands is equal or not a = = b returns false(0)
!= Checks if the value of two operands is equal or not a != b returns true(1)

 The result in either TRUE(1) or FALSE(0).Some of the relational operators are:

 Logical Operators
Operator Meaning Description Example
If both the operands are non-zero If a=10 and b=5 then,
&& Logical AND
then condition becomes true. ((a==10) && (b>5)) returns false.
If any of the two operands is non- If a=10 and b=5 then,
|| Logical OR
zero then condition becomes true. ((a==10) || (b>5)) returns true.
If a condition is true then the Logical If a=10 then,
! Logical NOT
NOT operator will make false. !(a==10) returns false.

 Logical operators are used to testing more than one condition and make decisions. Some of the logical
operators are

 Bitwise Operators
 A bitwise operator works on bits and performs bit by bit operation.
 Bitwise operators are used in bit level programming.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement

 The truth table for bitwise AND ( & ), Bitwise OR( | ), Bitwise XOR ( ^ ) are as follows:
A B A&B (Bitwise AND) A | B (Bitwise OR) A ^ B (Bitwise XOR)
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

 Assume A = 60 and B =13; the following operations take 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 operation. The result is given below.
A & B = 0000 1100 = 12
A | B = 0011 1101 = 61
A^B = 0011 0001 = 49
Operator Description Example
& Binary AND Operator copies a bit to the result if it (A&B) will give 12 which is
exists in both operands 0000 1100
| Binary OR Operator copies a bit if it exists in either (A|B) will give 61 which is
operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set in one (A^B) will give 49 which is
operand but not both. 0011 0001
~ Binary Ones complement Operator is unary and has the (~A) will give -60 which is
effect of „Flipping‟ bits 1100 0011
<< Binary Left Shift Operator. The left operands value is A<<2 will give 240 which is
moved left by the number of bits specified by the right 1111 0000

~A = 1100 0011 = -60


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

 Operator Same as Example
 = a=b a=b
 += a=a+b a+=b
 -= a=a-b a-=b
 *= a=a*b a*=b

/= a=a/b a/=b

%= a=a%b a%=b

<< = a = a<<2 a<<=2

>>= a = a>>2 a>>=2

&= a=a&2 a&=2

^= a=a^2 a^=2

 |= a=a|2 a|=2

 Assignment Operators
 The most common assignment operator is =. This operator assigns the value on the right side to the
left side.
 Example: var = 5 //5 is assigned to var
a = b; //value of b is assigned to a
5 = b; // Error! 5 is a constant.
The assignment operators supported by C++ are listed below:

 C++ Shorthand’s:
 C++ Offers special shorthand‟s that simplify the coding of a certain type of assignment statements.
 The general format of C++ shorthand‟s is:
 Variable Operator = Expression
 Following are some examples of C++ shorthand‟s:
x - = 10; Equivalent to x = x – 10;
x * = 5; Equivalent to x = x * 5;
x/=2; Equivalent to x = x / 2;
x % = z; Equivalent to x = x % z;
 Conditional Operator:
 A ternary operator pair ”? :” is available in C++ to construct conditional expressions of the form:
exp1? exp2: exp3, where exp1,exp2, and exp3 are expressions,
 The operator “?:” works as follows: exp1 is evaluated first. If it is true, then the expression exp 2 is
evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value
becomes the value of the expression.
 Example: a=10; b=5;
x = (a>b) ? a:b;

 Special Operator:
Operators Meaning of operators
It is a unary operator which is used in finding the size of the data
sizeof()
type. Example: sizeof(a)
Comma operators are used to linking related expressions
, (comma)
together. Example: int a=10, b=5
. (dot) and Member Operator used to reference individual members of
-> (arrow) classes, structure and unions.
cast Casting Operator convert one data type to another.
& Address Operator & returns the address of the variable.
* Pointer Operator * is pointer to a variable.

 Precedence of Operators or Hierarchy of Operators In C++:


 An expression is a combination of opcode and operand.
 The operators would be arithmetic, relational, and logical operators.
 If the expression contains multiple operators, the order in which operations carried out is called the
precedence of operators. It is also called as priority or hierarchy.
 The Operators with highest precedence appear at the top of the table and those with the lowest appear
at the bottom.
Category Operator Associativity
Postfix ( ) [ ] -> . ++ -- Left to Right
Unary = - ! ~ ++ -- (type) * & sizeof Right to Left
Multiplicative */% Left to Right
Additive +- Left to Right
Shift << >> Left to Right
Relational <<= >>= Left to Right
Equality == != Left to Right
Bitwise AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR | Left to Right
Logical AND && Left to Right
Logical OR || Left to Right
Conditional ?: Right to Left
Assignment = += -= *= /= %= Right to Left
Comma , Left to Right

What is operator precedence in C++?


 “The order in which different types of operators are evaluated is called as operator precedence”.
 It is also known as hierarchy of operators.
 In any expression, Operators having higher precedence are evaluated first.
 The expression is evaluated in the following sequence.
o Arithmetic
o Relational
o Logical
 There are some operators which are given below. The higher the position of an operator is, higher is
its priority.

Operator Meaning
! Logical NOT
() Parenthesis
*, /, % Arithmetic and modulus
+, - Arithmetic
<, >, <=, >= Relational
==, != Relational
&& Logical AND
|| Logical OR
= Assignment
 Type Conversion:
 Converting an expression of a given type into another type is known as type-casting or type
conversion.
 Type conversions are of two types, they are:
o Implicit Conversion
o Explicit Conversion

 Implicit Conversion:
 Implicit Conversions do not require any operator.
 They are automatically performed when a value is copied to a compatible type.
 The C++ compiler will implicitly convert or promote values if it can be done safely.
 If not it will generate a warning or an error depending on the conversion req uired.
 For Example:
short a = 2000;
int b;
b = a;
 Explicit Conversion:
 C++ is a strong-typed language. Many coversions, eqpecially those that imply a different
interpretation of the value, require an explicit conversion.
 For Example:
short a = 2000;
int b;
b = (int) a; //c-like cast notation
b = int (a) // functional notation
 Implicit Conversions do not require any operator.

 Translating a C++ program:


 General Structure of C++ Program:
General Syntax Example Program
/* General Structure */ /* A Simple Program to display a Message * /
Pre-processor Directives #include<iostream.h>
main ( ) void main( )
{ {
Variable Declarations; cout<<” This is the first C++ Program”;
Executable Statements; }
}
Different programming languages have their own format of coding. The basic components of a C++
program are:

 Comments or Documentation Section:


 Comments are the pieces of code that compiler ignores to compile. There are two types of comments
in C++.
1. Single line comment: The comments that begin with // are single line comments. The Compiler
simply ignores everything following // in the same line.
2. Multiline comment: The multiline comment begin with /* and end with */ . This means
everything that falls between /* and */ is consider a comment even though it is spread across
many lines.

 Pre-processor Directives (Linker Section):


 The linker section begins with a hash (#) symbol. #include …… is a preprocessor directive.
 It is a signal for preprocessor which runs the compiler.
 The statement directs the compiler to include the header file from the C++ Standard library.
 Example:
# include<iostream.h>
#include<conio.h>
# include<math.h>

 Definition:
 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.
 Example:
# define PI 3.14
 Global Declaration
 We can declare variables here and those variables which are declared before the main function or any
other function then the life or scope of such variables remain throughout function and can be used by
other functions of the program.

 main( ) Function:
 As the name itself indicates, this is the main function of every C++ program.
 Execution of a C++ program starts with main ( ).
 No C++ program is executed without the main () function.
 The function main () should be written in the lowercase letter and shouldn‟t be terminated with a
semicolon.
 It calls other library functions and user-defined functions.
 There must be one and only main ( ) in every C++ program.

 Braces { }:
{
…………..;
…………..;
}
 The statements inside any function including the main ( ) function is enclosed with the opening and
the closing braces.

 Declarations:
 The declaration is the part of the C++ program where all the variables, arrays, and functions are
declared with their basic data types.
 This helps the compiler to allocate the memory space inside the computer memory.
 Example:
int sum, x, y;

 Statements:
 These are instructions to the computer to perform some specific operations.
 These statements can be expressions, input-output functions, conditional statements, looping
statements, function call and so on. They also include comments.
 Every statement end with semicolon “;” except control statements.
 Semicolon “;” also known as Terminator.
 Example:
cout<<”Welcome to Computer Science Class”;
Example: A Simple C++ program to display a message on the screen:

#include<iostream.h>
#include<conio.h>
void main ()
{
clrscr();
cout<< “Welcome to Computer Science Class”;
getch();
}
The program produces following output:
Welcome to Computer Science Class

 Library Function:
 C++ provides many built-in functions that save the programming time.
 They include mathematical functions, character functions, string functions, and console input-output
functions.
 Mathematical Function:
 Some of the important mathematical functions in header file math.h are
Function Meaning
sqrt(x) Square Root of X
pow(x, y) x raised to the power y
sin(x) Sine of an angle x (measured in radians)
cos(x) Cosine of an angle x (measured in radians)
tan(x) Tangent of an angle x (measured in radians)
asin(x) Sin-1(x) where x (measured in radians)
acos(x) Cos-1(x) where x (measured in radians)
exp(x) Exponential function of x (ex)
log(x) Logarithm of x
log 10(x) Logarithm of number x to base 10
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x

 Character Function:
 Some of the important mathematical functions in header file ctype.h are
Function Meaning
isalpha(c) It returns True if C is an uppercase letter and false if c is lowercase.
isdigit(c) It returns True if c is a digit (0 to 9) otherwise false
It returns True if c is digit from 0 through 9 or an alphabetic character
isalnum(c)
(either uppercase or lowercase) otherwise false
islower(c) It returns True if c is a lowercase letter otherwise False
isupper(c) It returns True if c is a uppercase letter otherwise False
toupper(c) It converts c to uppercase letter
tolower(c) It converts c to lowercase letter.

 String Function:
 Some of the important mathematical functions in header file string.h are
Function Meaning
strlen(s) It gives the no. of characters including spaces present in a string s.
It concatenates the string s2 onto the end of the string s1. The
strcat(s1, s2)
string s1 must have enough locations to hold s2.
It copies character string s2 to string s1. The s1 must have enough
strcpy(s1, s2)
storage locations to hold s2.
strcmp((s1,s2)==0)
strcmp((s1,s2)>0) It compares s1 and s2 and find out whether s1 equal s2, greater
than s2 or s1 less than s2.
strcmp((s1,s2)<0)
strcmpi((s1,s2)==0)
strcmpi((s1,s2)>0) It compares s1 and s2 ignoring case and find out whether s1 equal
s2, greater than s2 or s1 less than s2.
strcmpi((s1,s2)<0)
strrev(s) It converts a string into its reverse.
strupr(s) It converts a string s into upper case.
strlwr(s) It converts a string into lower case.

 Console I/O Function:


 Some of the important mathematical functions in header file stdio.h are
Function Meaning
It returns a single character from a standard input device (keyboard). It takes
getchar()
no parameter and the returned value is the input character.
putchar() It takes one argument, which is the character to be sent to the output device.
It also returns this character as a result.
It gets a string terminated by a newline character from the standard input
gets()
stream stdlin.
puts() It takes a string which is to be sent to output device.

 General Purpose standard Library Function:


 Some of the important mathematical functions in header file stdio.h are
Function Meaning
randomize() It initialize/seeds the random number generator with a random number.
random(n) It generates a random number between 0 to n-1.
atoi(s) It converts string s into a numerical representation.
itoa(n) It converts a number to a string.

 Some more Function:


 getch( ) and getche( ) functions
 The genral form of the getch( ) and getche( ) is
ch = getche( );
ch1 = getch( );
 ch and ch1 are the variables of type character. They take no argument and require the conio.h header
file.
 On execution, the cursor blinks, the user must type a character and press enter key.
 The value of the character returned from getche( ) is assigned to ch.
 The getche( ) function echoes the character on the screen.
 Another function, getch( ), is similar to getche( ) but does not echo character to the screen.
Chapter-8
DATA TYPES
 Introduction
 To understand any programming languages we need to first understand the elementary concepts
which form the building block of that program.
 The basic building blocks include the variables, data types etc.
 C++ provides a set of data types to handle the data that is used by the program.

 Variable:
 A variable is an object or element and it is allowed change during the execution of the program.
 Variable represents the name of the memory location.

 Declaration of a variable:
 The syntax for declaring a variable is:
datatype variable_name;
 The variable_name is an identifier. These variables are used to denote constants, arrays, function,
structures, classes and files.
 The variables are named storage location whose values can be manipulated during program run.
 Examples:
Some valid variables are:
reg_no, marks, name, student1, dob;
Some invalid variables are:
Double - keyword cannot be name of the variable.
Total marks - empty spaces are not allowed between variables names
2student - variable name should be begin with an alphabet
?result - variable should begin with alphabet or underscore only.

 Initializing a variable:
 The syntax to initialize a variable is:
data_type variable_name = value;
 Example: Let b be a variable declared of the type int. then
int b = 100;
 There are two values associated with a variable known as lvaue and rvalue. It means, for example,
let p be a variable declared of the type int. then
int p = 100;
Memory Variable Values
 Here, name of the variable is p
2000 p 100
values assigned to variable is 100 i.e. rvalue
memory address location is 2000 i.e. lvalue
 Lvalue is the location value. It holds the memory address location at which the data value is stored.
 Rvalue is the data value. It holds the value assigned to the variable by the programmer i.e. Rvalue
of p = 100.
 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.
 The access modifier ‘const’ prefixed along with the data type for a variable does not allow the
value to be changed at all throughout the program.
cont int a = 100;
 The keyword const becomes an access modifier for the variables.
o A value can be assigned to lvalue only in an expression.
o Value can be assigned to a variable using the assignment operator ‘=’.
o The expression to the left of an assignment operator should always be an lvalue (memory
location) because that memory location should be available to store the rvalue.
o Constant identifiers can appear to the right of the assignment operator only since are not
lvalues.

 Data Types:
 Data Types 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.
 The main aim of C++ program is to manipulate data.
 C++ defines several types of data and each type has unique characteristics.
 C++ data types can be classified as:
1. The fundamental data type(built-in data)
2. Derived Data type
3. User-defined data type
 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, double and void.
 The int type:
 The int type is used to store integers.
 Integers are whole numbers without any fractional parts.
 This includes number such as 1, 45 and -9 are integers.
 5.2 is not an integer because it contains a decimal point.
 The integer can be positive or negative values and the ranges of number we can store are from
-32786 to 32767.
 An integer is allocated 2 bytes (16 bits) of memory space.
 The possible operations include addition, subtraction, multiplication, division, remainder etc.
 The General form of an integer declaration is:
int variable_name;
 Example: int a, b=5;

 The char type:


 It is character data type to store any character from the basic character set.
 Characters are enclosed in single quotation marks (‘). ‘A’, ‘a’, ‘b’, ‘9’, ‘+’ etc. are character
constants.
 When a variable of type char is declared, the compiler converts the character to its equivalent
ASCII code.
 A character is allocated only 1 byte (8 bits) of memory space.
 A character is represented in a program by the keyboard char.
 The general form of a character declaration is:
char variable_list;
 Example: char alpha=’a’;
 The float type:
 This represents the number with fractional part i.e. real numbers.
 The float type is used to store real numbers.
 Number such as 1.8, 4.5, 12e-5 and -9.66 are all floating point numbers.
 It can also be both positive and negative. The range of numbers we can store from -34e-38 to
3.4e38.
 Float is allocated 4 bytes (32 bits) of memory space.
 The general form of a float declaration is:
float variable_name;
 Example: float a=5.5;

 The double type:


 The double and float are very similar. The float type allows you to store single precision floating
point numbers, while the double keyword allows you to store double precision floating point
numbers.
 Its size is typically 8 bytes of memory space.
 The range of numbers we can store are from -1.7e308 to 1.7e308.
 The general form of a double declaration is:
double variable_list;
 Example: double a = 5.5e-7; //a is equivalent to 5.5x10-7

 The void type:


 The void data type has no values and no operations.
 In other words both the set of values and set of operations are empty.
 Example: void main( )
 In this declaration the main function does not return any value.

 The bool type:


 The bool type has logical value true or false. The identifier true has the value 1, and the identifier
false has the value 0.
 The general form of a bool declaration is:
bool variable_name;
 Example: bool legal_age=true;
 The statement legal_age= (age>=21); assigns the value true if age is greater than or equal to 21 or
else it returns the value false.
Type Size in bytes Range Examples
int 2 -32768 to 32767 8, 100, -39
char 1 -128 to 127 ‘d’, ‘6’, ‘#’
float 4 3.4 x 10-38 to 3.4 x 1038 -1 45.345, 0.134, 3.142
double 8 1.7 x 10-308 to 1.7 x 10308 -1 3.14156778888888888

 Derived data types


 These data types are constructed using simple or fundamental data types.
 This includes arrays, functions, pointers and references.

 User defined data types


 These data types are also constructed using simple or fundamental data types.
 Some user defined data types include structure, union, class and enumerated.

 Enumerated data type:


 AN enumeration is a user defined type consisting of a set of named constants called enumerators.
 enum is a keyword that assigns values 0, 1, 2…… automatically.
 This helps in providing an alternative means for creating symbolic constants.
 The syntax for enum is as follows:
enum [tag] { enum – list} ; //for definition for enumerated type
enumtaddeclarator; //for declaration of variable type tag
 Example 1:
enum choice { very_bad, bad, satisfactory, good, very_good};
choice mychoice;
 Example 2:
enum MyEnumType { ALPHA, BETA, GAMMA };
Here, ALPHA takes the value 0, BETA takes the value of 1, GAMMA takes the value of 2.
 Example 3:
enum footsize { small = 5, medium = 7, large = 10};

 C++ enum type conversion rules:


 These rules apply to C++ only.
 There is an implicit conversion from any enum type to int. Suppose this type exists.
enum MyEnumType { ALPHA, BETA, GAMMA };
 Then the following lines are legal
int i = BETA; //give i value of 1
int j = 3 + GAMMA //give j a value of 5
 On the otherhand, C++ does not support an implicit conversion form int to an enum type. This type
conversion is always illegal.
MyEnumType x = 2; //should not be allowed by compiler
MyEnumType y = 123; //should not be allowed by compiler
 Note that it does not matter whether the int matches one of the constants of the num type.
Chapter-9
INPUT AND OUTPUT OPERATORS
 Introduction
 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 able to interact with the user by printing
message on the screen and getting the user‟s input from the keyboard.
 A stream is an object where a program can either insert/extract characters to/from it.
 The standard C++ library includes the header file iostream, where the standard input and output
stream objects are declared.

 Input Operator “>>”:

 The standard input device is usually the keyboard.


 Input in C++ is done by using the “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:
int age;
cin>>age;
 The first statement declares a variable of the 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.
 We must always consider the type of the variable that we are using as a container with cin
extraction. For example, if we request an integer we will get an integer.

 Output Operator “<<”:


 The standard output device is the screen (Monitor).
 Outputting in C++ is done by using the object followed by the “stream insertion” (<<).
 cout stands for console output.
 Example:
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.
 The sentence in the instruction is enclosed between double quotes ( ” ), because it is 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 the variables name.
 Example:
cout<<”sum”; //prints sum
cout<<sum; //prints the content of the variable sum
 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 new-line character is an
escape sequence character and helps in formatting the output statement.
 Program: To demonstrate the cout statement:
#include<iostream.h>
#include<conio.h>
void main( )
{
cout<<”C++ is an Obejct Orinted Programming Language”<<”\n”;
cout<<”C++ is an case sensitive language\n”;
getch();
}

 Cascading of I/O Operators:


 C++ supports the use of stream extraction (>>) and stream insertion (<<) operator many times in a
single input (cin) and output (cout) statements.
 If a program requires more than one input variable then it is possible to input these variables in a
single cin statement using multiple stream extraction operators.
 Similarly, when we want to output more than one result then this can be done using a single cout
statement with multiple stream insertion operators.
 This is called cascading of input output operators.
 Example:
cout<<”Enter the first number”;
cin>>a;
cout<<”Enter the second number”;
cin>>b;
 Instead of using cin statement twice, we can use a single cin statement and input the two numbers
using multiple stream extraction operators.
cout<<”Enter the two number”;
cin>>a>>b;
 Similarly, we can even output multiple results in a single cout statements using cascading of
stream insertion operators.
cout<<”The sum of two number is”<<sum<<endl;

 Formatted Output (Manipulators) :


 Manipulators are the operators used with the insertion operator << to format the data display. The
most commonly used manipulators are endl and setw.
1. The endl manipulator : The endl manipulator, when used in a output statement , causes a line
feed to be inserted. It has same effect as using new line character “\n”.
cout<< “ Morarji Deasi Residential PU Science College”<<endl;
cout<< “ Guddenahalli, Hassan”;

The output of the above code will be:

Morarji Deasi Residential PU Science College


Guddenahalli, Hassan

2. The setw( ) Manipulator : The setw( ) manipulator sets the width of the field assign for the
output. It takes the size of the field (in number of character) as a parameter. The output will be
right justified. Example the code :

cout<<setw(6)<<”R” ;
Generates the following output on the screen (each underscore represent a blank space)
_____R
In order to use this manipulator, it is must to include header file iomanip.h
Program 1: To fins the sum of two numbers: Program: Convert the temperature in
#include<iostream.h> Fahrenheit into Celsius:
#include<conio.h> #include<iostream.h>
void main( ) #include<conio.h>
{ void main( )
int a, b, add; {
clrscr( ); float fah, cel;
cout<<”Enter the two numbers”; clrscr( );
cin>>a>>b; cout<<”Enter the value of Fahrenheit”;
add = a + b; cin>>fah;
cout<<”The sum of two number cel = ((5.0/9.0) * fah – 32.0);
is”<<sum<<endl; cout<<fah<<”F = ”<<cel<<” C”<<endl;
getch(); getch();
} }
Program: To interchange the values of two Program: To interchange the values of two
variables using third variable. variables without using third variable.
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int a, b, temp; int a, b;
clrscr( ); clrscr( );
cout<<”Enter the two numbers”; cout<<”Enter the two numbers”;
cin>>a>>b; cin>>a>>b;
cout<<”Before Interchanging : a = “ cout<<”Before Interchanging : a = “
<<a<<” and b = “<<b<<endl; <<a<<” and b = “<<b<<endl;
temp = a; a=a+b;
a = b; b=a–b;
b = temp; a=a–b;
cout<<”After Interchanging : a = “ cout<<”After Interchanging : a = “
<<a<<” and b = “<<b<<endl; <<a<<” and b = “<<b<<endl;
getch(); getch();
} }
Program: To find the area and circumference Program: To find the area of triangle given
of a circle. three sides.
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main( ) #include<math.h>
{ void main( )
float rad, area, circum; {
clrscr( ); float s1, s2, s3, s, area;
cout<<”Enter the radius”; clrscr( );
cin>>rad; cout<<”Enter the length of three sides”;
area = 3.142 * rad * rad; cin>>s1>>s2>>s3;
circum = 2 * 3.142 * rad; s = (s1 + s2+ s3)/2;
cout<<”Area of circle = “<<area<<endl; area = sqrt( s* (s-s1) * (s-s2) * (s-
cout<<”Circumference of circle = s3));
“<<circum<<endl; cout<<”Area of triangle = “<<area<<endl;
getch(); getch();
} }
Program: To convert days into years, months Program: To convert seconds into hours,
and days. minutes and seconds.
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int totaldays, days, year, month; int totalsec, min, hrs, secs;
clrscr( ); clrscr( );
cout<<”Enter the total days”; cout<<”Enter the total seconds”;
cin>>totaldays; cin>>totalsec;
year = totaldays/365; hrs = totalsec / 3600;
totaldays = totaldays % 365; totalsec = totalsec % 3600;
month = totaldays/30; min = totalsec/60;
days = totaldays % 30; secs = totalsec % 60;
cout<<”Years = “<< years<<endl; cout<<”Hours = “<<hrs<<endl;
cout<<”Months = “<<month<<endl; cout<<”Minutes = “<<min<<endl;
cout<<”Days = “<<days<<endl; cout<<”Seconds = “<< secs<<endl;
getch(); getch();
} }
Chapter 10 Conrtol Statements

Introduction 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 statement
that are separated by semicolon and enclosed within curled braces { and } is called a block or
compound statement.

The order in which statements are executed in a program is called flow of control. Types of control
statements:

C++ supports two basic control statements.

• Selection statements

• Iteration statements

Selection Statements:

This statement allows us to select a statement or set of statements for execution based on some
condition. It is also known as conditional statement. This structure helps the programmer to take
appropriate decision.

The different selection statements are:

• if statement

• if – else statement

• Nested – if statement

• switch statement

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 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
of simple if statement is:

if (Test Condition)

Statement 1;

Statement 2;
Here, the test condition is tested which results in either a TRUE or FALSE value. If the result of
the test condition is TRUE then the Statement 1 is executed. Otherwise, Statement 2 is executed.

Example:

if( amount > = 5000 )

discount = amount * (10/100);

net-amount = amount – discount;

if – else statement :

This structure helps 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 branching.

The general form of if – else statement is:

if (Test Condition)

Statement 1;

else

Statement 2;

Here, the test condition is tested.

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

Otherwise Statement 2 is executed.


Example:

if( n % 2 == 0 )

cout<<“Number is even”;

else

cout<<“Number is odd”;

if – else - if statement : (Format-1)

This structure helps 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. This statement is
also called as multiple-way branch.

The general form of if – else – if statement 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;

Here, Condition 1 is tested. If it is TRUE, Statement 1 is executed control 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 condition is satisfied, a statement called
default statement is executed.
if-else-if statement: (Format-2)

The general form is:

if (Test Condition 1)

if (Test Condition 2)

Statement 1;

else

Statement 2;

else

if (Test Condition 3)

Statement 3;

else

Statement 4;

Switch Statement :

C++ has built in multiple-branch selection statement i.e. switch. If there are more than two
alternatives to be selected, multiple selection construct is used.
The general form of Switch statement is:

switch(Expression) {

case Label-1: Statement 1;

break;

case Label-2: Statement 1;

break;

…………..

case Label-N: Statement N;

break;

default : default- Statement;

The switch 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.


 All cases must be included within curled braces.
 While executing, depending on the label, the corresponding set of statements are executed.
 If the value of the expression is not matched with label then default statement is executed.
 Every statement must consist of break statement to terminate corresponding cases.
Otherwise the following statements are executed until break is encountered.

Iterative Constructs or Looping:


Iterative statements are the statements that are used to repeatedly execute a
sequence of statements until some condition is satisfied or a given number of times.
The process of repeated execution of a sequence of statements until some condition is
satisfied is called as iteration or repetition or loop. Iterative statements are also called as
repetitive statement or looping statements. There are three types of looping structures in
C++.
 while loop
 do while loop
 for loop

while loop:
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 of while structure is:
while ( Test Condition)
{
Statement 1;
Statement 2;
……..
Statement N;
}
Example:
n = 10;
while ( n > 0)
{
cout<<n<<“\t”;
--n;
}
cout<<“End of while loop\n”;
Output is: 10 9 8 7 6 5 4 3 2 1 End of while loop

do while statements:
This is 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 of while structure is:
do
{
Statement 1;
Statement 2;
……..
Statement N;
} while(Test Condition);
Example:
i = 2;
do
{
cout<<i<< “\t”;
i=i+2;
}while(i<=25);

Comparison of while and do while statements


for statement:

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 or decrement looping structure.

The general form of for structure is as follows:

for ( Expression 1; Expression 2; Expression 3)

Statement 1;

Statement 2;

Statement N;

Where, Expression 1 represents Initialization,

Expression 2 represents Condition,

Expression 3 represents Increment/Decrement.

Example:

sum = 0;

for ( i=1; i<=10; i++)

sum = sum + i;
for looping structure works as follows:

• Initialization is executed. Generally it is an initial value setting for a counter variable and is
executed only one time.

• Condition is checked. if it is TRUE the loop continues, otherwise the loop ends and control
exists from structure.

• Statement is executed as usual, is can either a single statement or a block enclosed in curled
braces {and }.

• At last, whatever is specified in the increase field is executed and the loop gets back to
executed step 2.

• The initialization and increase fields are optional. They can remain empty, but in all cases the
semicolon sign between them must be written compulsorily.

• Optionally, using the comma operator we can specify more than one expression in any of
the fields included in a for loop.

Jump statements or Transfer of control from within loop:

Transfer of control within looping is used to:

• Terminate the execution of loop.

• Exiting a loop.

• Half way through to skip the loop.

All these can be done by using break, exit and continue statements.

break statement:

The break statement has two uses:

You can use it to terminate a case in the switch statement. You can also use it to force immediate
termination of a loop like while, do-while and for, bypassing the normal loop conditional test. When
the break statement is encountered inside a loop, the loop is immediately terminated and program
control resumes at the next statement.

The general form of break statement is: break;

Example:

for (n=0; n<100; n++)

cout<<n;

if(n==10)

break;

}
exit( ) function:

This function causes immediate termination of the entire program, forcing a return to the
operating system. In effect, exit( ) function acts as if it were breaking out of the entire program.

The general form of the exit( ) function is:

exit( ); or void exit( int return_code);

The return code is used by the operating system and may be used by calling programs. An exit code
of 0 means that the program finished normally and any other value means that some error or
unexpected results happened.

continue statement:

The continue statement causes the program to skip the rest of the loop in the current
iteration as if end of the statement block has been reached, causing it to jump to start of the
following iteration. Instead of forcing termination, however continue forces the next iteration of the
loop to take place, skipping any code in between.

The general form of the continue statement is: continue;

Example:

for (n=10; n<0; n--)

if(n==10)

continue;

cout<<n;

goto statement:

The goto allows to makes an absolute jump to another point in the program. This statement
execution causes an unconditional jump or transfer of control from one statement to the other
statement with in a program ignoring any type of nesting limitations. The destination is identified by
a label, which is then used as an argument for the goto statement. A label is made of a valid
identifier followed by a colon (:).

The general form of goto statement is:

statement1;

statement2;

goto label_name;

statement 3;

label_name: statement4;

statement5;
Chapter-10
CONTROL STATEMENTS
 Introduction
 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 statement that are separated by semicolon and enclosed within curled braces { and } is
called a block or compound statement.
 The order in which statements are executed in a program is called flow of control.

 Types of control statements:


 C++ supports two basic control statements.
o Selection statements
o Iteration statements
 Selection Statements:
 This statement allows us to select a statement or set of statements for execution based on some
condition.
 It is also known as conditional statement.
 This structure helps the programmer to take appropriate decision.
 The different selection statements, viz.
o if statement
o if – else statement
o Nested – if statement
o switch statement

 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 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 of simple – if statement is:

if (Test Condition) // This Condition is true


Statement 1;
Statement 2;
 Here, the test condition is tested which results in either a TRUE or
FALSE value. If the result of the test condition is TRUE then the
Statement 1 is executed. Otherwise, Statement 2 is executed.
Ex: if( amount > = 5000 )
discount = amount * (10/100);
net-amount = amount – discount;

Practical Program 5: Write a C++ program to find the largest, smallest


and second largest of three numbers using simple if statement.

#include<iostream.h>
#include<conio.h>
void main( )
{
int a, b, c;
int largest, smallest, seclargest;
clrscr( );
cout<<”Enter the three numbers”<<endl;
cin>>a>>b>>c;
largest = a; //Assume first number as largest
if(b>largest)
largest = b;
if(c>largest)
largest = c;

smallest = a; //Assume first number as smallest


if(b<smallest)
smallest = b;
if(c<smallest)
smallest = c;

seclargest = (a + b + c) – (largest + smallest);


cout<<”Smallest Number is = “<<smallest<<endl;
cout<<”Second Largest Number is = “<<seclargest<<endl;
cout<<”Largest Number is = “<< largest<<endl;
getch( );
}
Practical Program 6: Write a C++ 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 simple if statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
float TAmount, discount, FAmount ;
clrscr( );
cout<<”Enter the Total Amount”<<endl;
cin>>TAmount;

discount = 0; //Calculate Discount


if(TAmount>1000)
Discount = (8/100) * TAmount;

FAmount = TAmount – Discount //Calculate Final Amount

cout<<”Toatal Amount = “<<TAmount<<endl;


cout<<”Discount = “<<discount<<endl;
cout<<”Final Amount = “<< FAmount<<endl;
getch( );
}
 if – else statement :
 This structure helps 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 branching.
 The general form of if – else statement is:
if (Test Condition)
Statement 1;
else
Statement 2;
 Here, the test condition is tested. If the test-
condition is TRUE, statement-1 is executed.
Otherwise Statement 2 is executed.
Ex: if( n % 2 == 0 )
cout<<” Number is Even”;
else
cout<<” Number is Odd”;

Practical Program 7: Write a C++ program to check whether a given year is a leap year not, Using if
- else statement.
#include<iostream.h>
#include<conio.h>
void main( )
{
int year ;
clrscr( );
cout<<”Enter the Year in the form YYYY”<<endl;
cin>>year;
if(year%4 ==0 && year%100!=0 || year%400 ==0)
cout<<year<<” is a leap year”<<endl;
else
cout<<year<<” is not leap year”<<endl;
getch( );
}
Practical Program 8: Write a C++ program to accept a character. Determine whether the character is
a lower-case or upper-case letter.

#include<iostream.h>
#include<conio.h>
void main( )
{
char ch ;
clrscr( );
cout<<”Enter the Character”<<endl;
cin>>ch;
if(ch>= „A‟ && ch <=‟Z‟)
cout<<ch<<” is an Upper-Case Character”<<endl;
else
if(ch>= „a‟ && ch <=‟z‟)
cout<<ch<<” is an Lower-Case Character”<<endl;
else
cout<<ch<<” is not an alphabet”<<endl;
getch( );
}
 Nested if statement :
 If the statement of an if statement is another if statement then such an if statement is called as
Nested-if Statement.
 Nested-if statement contains an if statement within another if statement.
 There are two forms of nested if statements.

 if – else - if statement :
 This structure helps 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.
 This statement is also called as multiple-way branch.
 The general form of if – else – if statement is:
if (Test Condition 1)
Example:
Statement 1; if( marks > = 85 )
else PRINT “Distinction”
else
if (Test Condition 2)
if( marks > = 60 )
Statement 2; PRINT “First Class”
else else
if( marks > = 50 )
………..
PRINT “Second Class”
else else
if( test Condition N) if( marks > = 35 )
Statement N; PRINT “Pass”
else
else PRINT “Fail”
Default Statement;
 Here, Condition 1 is tested. If it is TRUE, Statement 1 is executed control 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 condition is satisfied, a statement called default statement is executed.
Practical Program 9: Write a C++ 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

#include<iostream.h>
#include<conio.h>
void main( )
{
int units ;
float Billamount;
clrscr( );
cout<<”Enter the number of units consumed”<<endl;
cin>>units;
if(units < 30)
Billamount = units * 3.50 ;
else
if(units < 50)
Billamount = 29 * 3.50 + (units – 29) * 4.25 ;
else
if(units < 100)
Billamount = 29 * 3.50 + 20 * 4.25 + (units – 49) * 5.25 ;
else
Billamount = 29 * 3.50 + 20 * 4.25 + 50 * 5.25 + (units – 99) * 5.85 ;

cout<<”Total Units Consumed =”<<units<<endl;


cout<<”Toatl Amount = “<<Billamount<<endl;
getch( );
}
 The general form of if – else -if statement is: Ex: To find the greatest of three numbers a, b and c.
if (Test Condition 1) if ( a>b )
if (Test Condition 2) if ( a > c )
Statement 1; OUTPUT a
else else
Statement 2; OUTPUT c
else else
if (Test Condition 3) if ( b > c )
Statement 3; OUTPUT b
else else
Statement 4; OUTPUT c
 Switch Statement :
 C++ has built in multiple-branch selection statement i.e. switch.
 If there are more than two alternatives to be selected, multiple selection construct is used.
 The general form of Switch statement is:
Switch ( Expression )
{
Case Label-1: Statement 1;
Break;
Case Label-2: Statement 1;
Break;
…………..
Case Label-N: Statement N;
Break;
Default : Default- Statement;
}
 Ex: To find the name of the day given the day number
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;
}
 The switch statement is a bit peculiar within the C++ language because it uses labels instead of
blocks.
 This force up 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 also are
executed until the end of the switch selective block or a break statement is reached.

Practical Program 10: Write a C++ 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 “Fail”
using switch statement.
Class Range (%)
First Class Between 60% to 100%
Second Class Between 50% to 59%
Pass Class Between 40% to 49%
Fail Less than 40%
#include<iostream.h>
#include<conio.h>
void main( )
{
int m1, m2, m3, m4, total, choice;
float per;
clrscr( );
cout<<”Enter the First subject marks”<<endl;
cin>>m1;
cout<<”Enter the Second subject marks”<<endl;
cin>>m2;
cout<<”Enter the Third subject marks”<<endl;
cin>>m3;
cout<<”Enter the Fourth subject marks”<<endl;
cin>>m4;

total = m1 + m2 + m3 + m4;
per = (total / 400) * 100;
cout<<”Percentage = “<<per<<endl;

choice = (int) per/10;


cout<<”The result of the student is: “<<endl;
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;
default: cout<<”Fail”<<end;
}
getch( );
}
 Iterative Constructs or Looping
 Iterative statements are the statements that are used to repeatedly execute a sequence of statements
until some condition is satisfied or a given number of times.
 The process of repeated execution of a sequence of statements until some condition is satisfied is
called as iteration or repetition or loop.
 Iterative statements are also called as repetitive statement or looping statements.
 There are three types of looping structures in C++.
o while loop
o do while loop
o for loop
 while loop:
 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 of while structure is
while ( Test Condition)
{
Statement 1
Statement 2
……..
Statement N
}End of While
 Example:
n = 10;
While ( n > 0)
{
cout<<n<<”\t”;
- - n;
}
cout<<”End of while loop \n”;
Output: 10 9 8 7 6 5 4 3 2 1 End of while loop

Practical Program 11: Write a C++ program to find sum of all the digits of a number using while
statement.

#include<iostream.h>
#include<conio.h>
void main( )
{
int num, sum, rem;
clrscr( );
cout<<”Enter the Number”<<endl;
cin>>num;
sum = 0;
while(num!=0)
{
rem = num % 10;
sum = sum + rem;
num = num/10;
}
cout<<”Sum of the digits is “<<sum<<endl;
getch( );
}
Practical Program 12: Write a C++ program to input principal amount, rate of interest and time
period. Calculate compound interest using while statement.
(Hint: Amount = P * (1 + R/100)T, Compound Interest = Amount – P)

#include<iostream.h>
#include<conio.h>
void main( )
{
float pri, amt, priamt, rate, ci;
int time, year;
clrscr( );
cout<<”Enter the Principal amount, rate of interest and time”<<endl;
cin>>pri>>rate>>time;

year = 1;
priamt = pri;

while(year <= time)


{
amt = pri * (1 + rate/100);
year ++;
}
ci = amt – priamt;
cout<<”Compound Interest is “<<ci<<endl;
getch( );
}
Practical Program 13: Write a C++ program to check whether the given number is power of 2.

#include<iostream.h>
#include<conio.h>
void main( )
{
int num, m, flag;
clrscr( );
cout<<”Enter the Number”<<endl;
cin>>num;
m = num;
flag = 1;
while(num>2)
if(num % 2 ==1)
{
flag = 0;
break;
}
else
num = num/2;
if(flag)
cout<<m<<” is power of 2 “<<endl;
else
cout<<m<<” is not power of 2 “<<endl;
getch( );
}
 do while statements:
 This is 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 of while structure is
do
{
Statement 1
Statement 2
……..
Statement N
} while ( Test Condition);
 Example:
i = 2;
do
{
cout<<i<<”\t”;
i = i + 2;
}
while ( i < = 25);
Practical Program 14: Write a C++ program to check whether the given number is an Armstrong
Number using do-while statement. (Hint: 153 = 13 + 53 + 33)

#include<iostream.h>
#include<conio.h>
void main( )
{
int num, rem, sum, temp;
clrscr( );
cout<<”Enter the three digit number”<<endl;
cin>>num;
temp = num;
sum = 0;
do
{
rem = temp % 10;
sum = sum + rem * rem * rem;
temp = temp / 10;
}while(temp!=0);
if(sum == num)
cout<<num<<” is an Armstrong Number “<<endl;
else
cout<<num<<” is not an Armstrong Number “<<endl;
getch( );
}
 Difference between while and do while loop:
while do while
This is pre- tested looping structure This is post tested looping structure
It tests the given condition at initial point It tests the given condition at the last of
of looping structure looping structure.
Minimum execution of loop is zero Minimum execution of loop is once.
Syntax: Syntax:
while ( Test condition ) do
{ {
statement 1; statement 1;
statement 2; statement 2;
…………….; statement n;

statement n; }
} while ( Test condition);
Semi colon is not used. Semi colon is used.
 for statement:
 This structure is the fixed execution structure.
 This structure is usually used when we know in advance exactly how many times asset of
statements is to be repeatedly executed again and again.
 This structure can be used as increment looping or decrement looping structure.
 The general form of for structure is as follows:
for ( Expression 1; Expression 2; Expression 3)
{
Statement 1;
Statement 2;
Statement N;
}
Where, Expression 1 represents Initialization
Expression 2 represents Condition
Expression 3 represents Increment/Decrement
 Example:
sum = 0;
for ( i=1; i<=10; i++)
sum = sum + i;

 This looping structure works as follows:


o Initialization is executed. Generally it is an initial value setting for a counter variable and is
executed only one time.
o Condition is checked. if it is TRUE the loop continues, otherwise the loop ends and control
exists from structure.
o Statement is executed as usual, is can either a single statement or a block enclosed in curled
braces { and }.
o At last, whatever is specified in the increase field is executed and the loop gets back to
executed step 2.
o The initialization and increase fields are optional. They can remain empty, but in all cases the
semicolon sign between them must be written compulsorily.
o Optionally, using the comma operator we can specify more than one expression in any of the
fields included in a for loop.
Practical Program 15: Write a C++ program to find the factorial of a number using for statement.
(Hint: 5! = 5 * 4 * 3 * 2 * 1 = 120)

#include<iostream.h>
#include<conio.h>
void main( )
{
int num, fact, i;
clrscr( );
cout<<”Enter the number”<<endl;
cin>>num;

fact = 1;
for( i = 1; i<= num; i++)
fact = fact * i;
cout<<” The factorial of a ”<<num<<”! is: “<<fact<<endl;
getch( );
}
Practical Program 16: Write a C++ program to generate the Fibonacci sequence up to a limit using
for statement. (Hint: 5 = 0 1 1 2 3)

#include<iostream.h>
#include<conio.h>
void main( )
{
int num, first, second, count, third;
clrscr( );
cout<<”Enter the number limit for Fibonacci Series”<<endl;
cin>>num;
first = 0;
second = 1;
cout<<first<<”\t”<<second;
third = first + second;
for( count = 2; third<=num; count++)
{
cout<<”\t”<<third
first = second;
second = third;
third = first + second;
}
cout<<”\n Total terms = “<<count<<endl;
getch( );
}
 Jump statements or Transfer of control from within loop
 Transfer of control within looping are used to
o Terminate the execution of loop.
o Exiting a loop.
o Half way through to skip the loop.
 All these can be done by using break, exit and continue statements.

 break statement
 The break statement has two uses
o You can use it to terminate a case in the switch statement.
o You can also use it to force immediate termination of a loop like while, do-while and for, by
passing the normal loop conditional test.
 When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement.
 The general form of break statement is:
break;
 Example:
for (n=0; n<100; n++)
{
cout<<n;
if(n==10) break;
}
Program: To test whether a given number is prime or not using break statement.
#include<iostream.h>
#include,conio.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”<<endl;
getch( );
}
 exit( ) function:
 This function causes immediate termination of the entire program, forcing a return to the operating
system.
 In effect, exit( ) function acts as if it were breaking out of the entire program.
 The general form of the exit( ) function is:
exit( ); or void exit( int return_code);
 The return code is used by the operating system and may be used by calling programs.
 An exit code of 0 means that the program finished normally and any other value means that some
error or unexpected results happened.
Program: To test whether a given number is prime or not using exit( ) statement.
#include<iostream.h>
#include,conio.h>
void main( )
{
int n, i;
clrscr( );
cout<<”Enter the number”;
cin>>n;
for(i=2; i<=n/2; i++)
{
if(n % i ==0)
{
cout<<”It is not a prime”<<endl;
exit(0);
}
}
cout<<”It is a prime number”<<endl;
getch( );
}
 continue statement:
 The continue statement causes the program to skip the rest of the loop in the current iteration as if
end of the statement block has been reached, causing it to jump to start of the following iteration.
 The continue statement works somewhat like break statement.
 Instead of forcing termination, however continue forces the next iteration of the loop to take place,
skipping any code in between.
 The general form of the continue statement is:
continue;
 Example:
for (n=10; n<0; n--)
{
if(n==10) continue;
cout<<n;
}
 goto statement:
 The goto allows to makes an absolute jump to another point in the program.
 This statement execution causes an unconditional jump or transfer of control from one statement to
the other statement with in a program ignoring any type of nesting limitations.
 The destination is identified by a label, which is then used as an argument for the goto statement.
 A label is made of a valid identifier followed by a colon (:).
 The general form of goto statement is:
statement1;
statement2;
goto label_name;
statement 3;
statement4;
label_name: statement5;
statement6;
Program: To print from 10 to 1 using goto statements.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int n=10;
loop: cout<<”\t”<<n;
n--;
if(n>0) goto loop;
cout<<”End of loop”;
getch( );
}
Chapter-11
ARRAYS
 Introduction
 In everyday life we commonly group similar objects into units.
 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. Array in C++ are similar to those in other
languages and identical to those in C.

 Array Fundamentals:
 An array is collection of elements where all the elements are same data type under the same
name.
 The elements are numbered as 0, 1, 2….n-1.
 These numbers called as indices or subscripts.
 These numbers are used to locate the positions of elements within the array.
 If a is the name of the array, the elements can be directly accessed as a[0], a[1], a[2],……, a[n-1].
o a[0] is the name of the first element present at position 0.
o a[1] is the name of the second element present at position 1 and so on.
o In general, a[i] is the element present at position i.
 An array can be represented as
a 10 20 30 40 50
0 1 2 3 4
 In the above array, a is the name of the array,
o a[0] contains the element 10
o a[1] contains the element 20
o a[2] contains the element 30
o a[3] contains the element 40
o a[4] contains the element 50.
 The diagram represents a region of the memory, because the array elements are always stored in
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].
 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.

 Types of Arrays:
 There are 3 types of arrays.
i. One-dimensional array
ii. Two-dimensional array
iii. Multi-dimensional array

 One –dimensional array


 It is an array in which each element is accessed by using only one subscript.
 The only one subscript represents the position of the element in array.

 Two-dimensional array
 It is an array in which each element is accessed using 2-subscripts.
 The subscripts represent the position of the element in the array.

 Multi-dimensional array
 A multi-dimensional array is an array of n-dimensions.
 In other words, an array of arrays is called a multi dimensional array.
 A one dimensional array of one dimensional array is called a two dimensional array; a one
dimensional array to two dimensional array is called three dimensional array and so on.

 One-Dimensional Array:
 It is an array in which each element is accessed by using only one subscript.
 The only one subscript represents the position of the element in array.
 Like other variable, the array should also be defined before it is used to store elements.
 An array can be defined by specifying the data type of the elements followed by name of the array
and the number of elements that can be stored in the array.
 The number of elements that can be stored in the array is called the size of the array.
 The size of the array must be a constant or an expression that evaluates to a constant, and should
also be an integer.
 The size should be enclosed within square brackets.
 Declaration of One-dimensional array:
 Syntax: data_type array_name[size];
 Example: int regno[10];
 This example defines an array marks that can store 50 elements and all the elements are of int data
type.

 Initialization of one-dimensional arrays:


 You can give values to each array element when array is first defined.
 Example 1: int a[5] = { 9, -5, 6, 2, 8};
 In the above example, value 9 is stored in a[0], value -5 is stored in a[1], value 6 is stored in a[2],
value 2 is stored in a[3] and value 8 is store in a[4].
a 9 -5 6 2 8
0 1 2 3 4
 If there is less number of elements specified than the size of the array, the remaining elements are
filled with 0 by the compiler.
 Example 2: float w[5] = {1.5, 2.8, 2.5};
 In the above example, value 1.5 is stored in w[0], value 2.8 is stored in w[1], value 2.5 is stored in
w[2], The elements w[3] and w[4] are initialized with 0. Thus, the initialization, the default value
is 0.
w 1.5 2.8 2.5 0 0
0 1 2 3 4
 If the array does not include an initialization, then the array elements may contain the unexpected
values called “garbage values”.
 When an array has explicit initialization, its size can be omitted from the declaration.
 Example: int a[5] = { 9, -5, 6, 2, 8}; is equivalent to int a[ ] = { 9, -5, 6, 2, 8};

 Accessing the elements:


 Consider the declaration, int a[5];
 We can read 5 elements into the array through the input device by writing the following program
fragment.
cout<<”Enter the elements:”;
for(i=0; i<5; i++)
cin>>a[i];
 To print the 5 elements of the above array, we write the following program fragment.
cout<<”The elements are:”;
for(i=0; i<5; i++)
cout<<a[i]<<”\t”;
Sample Program 1: To read the elements into the array and printing the elements:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a[50], i, n;
clrscr( );
cout<<”Enter the size of the array:”; Output:
cin>>n; Enter the size of the array: 5
cout<<”Enter the elements:”;
for(i=0; i<n; i++) Enter the elements:
cin>>a[i]; 10 20 30 40 50
The elements are:
cout<<”The elements are:”;
10 20 30 40 50
for(i=0; i<5; i++)
cout<<a[i]<<”\t”;
getch( );
}

 Memory representation of one-dimensional arrays:


 The elements of one-dimensional arrays are stored in continuous memory locations.
 Example: Consider the declaration, char A[5];
 The element a[0] is allocated at a particular memory location, the element a[1] is allocated at next
memory location and so forth. Since the array is of the type char, each element requires 1-byte.
1000 1001 1002 1003 1004
A

A[0] A[1] A[2] A[3] A[4]


 Example: Consider the declaration, int a[3];
 The element a[0] is allocated at a particular memory location, the element a[1] is allocated at next
memory location and so forth. Since the array is of the type char, each element requires 2-byte.
1000 1001 1002 1003 1004 1005
A

A[0] A[1] A[2]


 The amount of storage space required to hold an array is directly related to its type and size of the
array. The total size can be calculated using the relation.
Total Size = sizeof(type) * size_of_array;
 Example:
o The total size of the char array required is 1 * 5 = 5 bytes.
o The total size of the int array required is 2 * 3 = 6 bytes.

Practical Program 17: To find the sum and average of n number of the array:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, n, sum;
float avg;
clrscr( );
cout<<"How many elements?"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0; i<n; i++) Output:
cin>>a[i]; How many elements? 5
sum = 0; Enter the elements:
for(i=0; i<n; i++)
sum = sum + a[i]; 10 20 30 40 50
avg=(float) sum / n; Sum = 150
cout<<"Sum = "<<sum<<endl; Average = 30
cout<<"Average = "<<avg<<endl;
getch( );
}
Practical Program 18: To find the second largest of n number in the array:
#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];
}
else
{
largest=a[1];
secondlar=a[0];
}
for(i=2; i<n; i++)
if(a[i] > largest)
{
secondlar = largest; Output:
largest = a[i]; How many elements? 5
} Enter the elements:
else
10 20 30 40 50
if(a[i] > secondlar)
secondlar = a[i]; Largest = 50
cout<<"Largest = "<<largest<<endl; Second Largest = 40
cout<<"Second Largest = "<<secondlar<<endl;
getch( );
}
Sorting: The process of arrangement of data items in ascending or descending order is called sorting.
Practical Program 19: To arrange a list of numbers in ascending order:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
int a[50], i, temp, j, n;
clrscr( );
cout<<"Enter the number of elements:"<<endl;
cin>>n;
cout<<"Enter the elements:"<<endl;
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])
{ Output:
temp = a[j]; Enter the number of elements: 5
a[j] = a[j+1]; Enter the elements:
a[j+1] = temp;
30 20 50 40 10
}
} The sorted elements are:
cout<<"The sorted elements are:"<<endl; 10 20 30 40 50
for(i=0; i<n; i++)
cout<<a[i]<<”\t”;
getch( );
}
Searching: The process of finding the position of a data item in the given collection of data items is
called searching.
We can search the position of an element in the array.
Practical Program 20: To find position of a given number in the array:
#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:"<<endl;
cin>>n;
cout<<"Enter the elements:"<<endl;
for(i=0; i<n; i++)
cin>>a[i];
cout<<"Enter the search element:"<<endl;
cin>>ele;
Output:
pos=-1;
Enter the number of elements: 5
for(i=0; i<n; i++)
if(ele == a[i]) Enter the elements:
{ 10 20 30 40 50
pos = i;
Enter the search element: 40
break;
} 40 is present at position 3
if(pos >= 0)
cout<<ele<<" is present at position "<<pos<<endl;
else
cout<<ele<<" is not present"<<endl;
getch( );
}

 Two -Dimensional arrays:


 It is an array in which each element is accessed using 2-subsripts.The subscripts represents
position of the elements in the array.
 The elements of two dimensional arrays are represented as rows and columns. To identify any
element, we should know its row-number and column-number.
Column-number
0 1 2 3 …. n-1
0

Row-Number
1 a[2] [3]
2 * 2  Row Number
3  Column Number
….
m-1

 Declaration of Two -Dimensional array:


 A Two-dimensional array can be defined by specifying the data type of the elements followed by
name of the array followed by the number of rows (i.e. row-size) and number of columns (i.e.
column-size)in the array.
 The rows-size and column-size of the array must be constant are expressions that evaluates to an
integer.
 The rows-size and column-size should be separately enclosed within square brackets.
 Syntax: data_type array_name[row size] [column_size];

 Initialization of Two-Dimensional arrays:


 Similar to the one-dimensional array, we can initialize a two-dimensional array either by
initializing it in its declaration or by using assignment statement.
 Example: int a[2][3] = { 1,2,3,4,5,6};
 Where a is a two-dimensional array which contains 2 rows and 3 columns and these assignments
would be Column - 3
a[0][0] = 1 a[0][1] = 2 a[0][2] = 3 0 1 2
Row- 2

a[1][0] = 4 a[1][1] = 5 a[1][2] = 6 0 1 2 3


 Note: If the values are missing in an initialize, they are 1 4 5 6
automatically set to 0.
 Example: int b[2][3] = { Column - 3
{ 1, 2 } 0 1 2
{3}
Row- 2

}; 0 1 2 0
 It will initialize the first two elements to the first row, the next 1 3 0 0
Element to the second row. The remaining elements are automatically set
0. b[0][0] = 1 b[0][1] = 2 b[0][2] = 0
b[1][0] = 3 b[1][1] = 0 a[1][2] = 0
 Accessing the elements:
 Consider the declaration int a[2][3];
 We can read 6 elements into the array, we need to use nested for loops.
 One loop processes the rows and another loop processes the columns.
 If outer loop is for rows and inner loop is for columns, then for each row index, all the columns are
processed and then the same process is repeated for next row index.
 To understand this, let us consider the following program fragment.
cout<<”enter the elements:”;
for (i=0; i<2; i++) //outer loop to control the rows
for (j=0; j<3; j++) //inner loop to the control columns
cin>>a[i][j];
 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<<a[i][j]<<”\t”; //each element is printed using 5-columns
cout<<endl;
}
Sample Program 2: To read the elements into the two-dimensional array and printing the
elements:
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a[5][5], i, j, m, n;
Output:
clrscr( );
Enter the order: 2 3
cout<<"Enter the order:"<<endl;
cin>>m>>n; Enter the elements:
cout<<"Enter the elements:"<<endl; 1 2 1
for(i=0; i<m; i++)
1 0 1
for(j=0; j<n; j++)
cin>>a[i][j]; The elements are:
cout<<”The array elements are:”<<endl; 1 2 1
for(i=0; i<m; i++)
1 0 1
{
for(j=0; j<n; j++)
cout<<a[i][j]<<”\t”;
cout<<endl;
}
getch( );
}
Practical Program 22: Write a program to sum of all the row and sum of all the column in
matrices separately:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a[5][5], r, c, i, j, rsum, csum;
clrscr( );
cout << "Enter the order of matrix: ";
cin >> r>>c;
// Storing elements of matrix entered by user.
cout << "Enter elements of the matrix: " << endl;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
cin >> a[i][j];

for(i = 0; i < r; i++)


{
rsum = 0;
for(j = 0; j < c; j++)
rsum = rsum + a[i][j];
cout<<”Sum of row no “<<i+1<<” = “<<rsum<<endl;
}
for(i = 0; i < c; i++)
{
csum = 0;
for(j = 0; j < r; j++)
csum = csum + a[j][i];
cout<<”Sum of column no “<<i+1<<” = “<<rsum<<endl;
}
getch( );
}
Practical Program 23: Write a program to find the sum of two matrices:
#include<iostream.h>
#include<conio.h>
void main( )
{
int a[5][5], b[5][5], sum[5][5], r1, c1, r2, c2, i, j;
clrscr( );
cout << "Enter the order of first matrix: ";
cin >> r1>>c1;
cout << "Enter the order of second matrix: ";
cin >> r2>>c2;

// Storing elements of first matrix entered by user.


cout << "Enter elements of 1st matrix: " << endl;
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
cin >> a[i][j];
// Storing elements of second matrix entered by user.
cout << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
cin >> b[i][j];
if ( (r1 == r2) && (c1==c2)
{
for(i = 0; i < r; i++)
for(j = 0; j < c; j++)
sum[i][j] = a[i][j] + b[i][j]; // Adding Two matrices
cout << "Sum of two matrix is: " << endl;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
cout << sum[i][j] << "\t"; // Displaying the resultant sum matrix.
cout << endl;
}
else
cout<<”Matrices are not compatible…”<<endl;
getch( );
}
Practical Program 24: Consider an array MARKS[20[5] which stores the marks obtained by 20
students in 5 subjects. Now write a program to:
o Find the average marks obtained in each subject.
o Find the average marks obtained by every student
o Find the number of students who have scored below 50 in their average.
#include<iostream.h>
#include<conio.h>
void main( )
{
int marks[20][5], n, s, total, count=0, i, j;
float average;
clrscr( );
cout << "Enter the number of students: ";
cin >> n;
cout << "Enter the number of subjects: ";
cin >> s;

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 Subjects”<<endl;
cout<<”Sub1\tSub2\tSub3\tSub4\tSub5”<<endl;
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<<”Average of students:”<<endl;
cout<<”Student\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<<”Number of students less than average is ”<<count<<endl;
getch( );
}
 Multi -Dimensional arrays:
 A Multi-Dimensional array is an array of n-dimensions.
 An array of arrays is called a multi-dimensional array.
 Syntax: Data_type Array_name[s1][s2][s3]…..[sn];
where s1 is the size of the ith dimension.
Chapter-12
FUNCTIONS
 Introduction
 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.

 Types of functions
 There are two types of functions:
1. Library functions
2. User-defined functions

 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.
 The header files should be written angled brackets and its functions are included into our programs
by #include directive.

 User-defined functions
 We can create our own functions or sub-programs to solve our problem. Such functions are
normally referred to as user defined functions.
 A user-defined function is a complete and independent program, which can be used (or
invoked) by the main program, or by the other sub-programs.
 The user-defined functions are written to perform definite calculations, after performing their task
they send back the result to the calling program or sub-program.

 Different header files


 iostream.h
 This header file contains C++ streams and i/o routines and are listed below.
 open, close, get, getline, read, write, put, seekg, seekp, tellg, tellp, eof etc.

 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.
 fopen, fclose, printf, scanf, fprintf, fscanf, fread, fwrite etc.

 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.
Function Meaning
strlen(s) It gives the no. of characters including spaces present in a string s.
It concatenates the string s2 onto the end of the string s1. The
strcat(s1, s2)
string s1 must have enough locations to hold s2.
It copies character string s2 to string s1. The s1 must have enough
strcpy(s1, s2)
storage locations to hold s2.
strcmp((s1,s2)==0)
strcmp((s1,s2)>0) It compares s1 and s2 and find out whether s1 equal s2, greater
than s2 or s1 less than s2.
strcmp((s1,s2)<0)
strcmpi((s1,s2)==0)
strcmpi((s1,s2)>0) It compares s1 and s2 ignoring case and find out whether s1 equal
s2, greater than s2 or s1 less than s2.
strcmpi((s1,s2)<0)
strrev(s) It converts a string into its reverse.
strupr(s) It converts a string s into upper case.
strlwr(s) It converts a string into lower case.

 stdlib.h
 This header file is used to declare conversion routines, search/sort routines and other
miscellaneous things. The functions are listed below.
 atoi, atol, atof, free, malloc, calloc, realloc etc.

 iomanip.h
 This header file contains functions and macros for I/O manipulators for creating parameterized
manipulations. The functions are listed.
 endl, setw, setfile, setprecision, hex, oct etc.

 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.
Function Meaning
sqrt(x) Square Root of X
pow(x, y) x raised to the power y
sin(x) Sine of an angle x (measured in radians)
cos(x) Cosine of an angle x (measured in radians)
tan(x) Tangent of an angle x (measured in radians)
asin(x) Sin-1(x) where x (measured in radians)
acos(x) Cos-1(x) where x (measured in radians)
exp(x) Exponential function of x (ex)
log(x) Logarithm of x
log 10(x) Logarithm of number x to base 10
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x

 Character functions
 A character is any single character enclosed within single quotes.
 Some functions accept a character as argument.
 The argument is processed as an int by using its ASCII code.
 To use these functions, the header file ctype.h should be included.
 Any character enclosed within single quotes is called as a single character constant or simply, a
character constant.
 These functions will be of the form : int function-name(int character)
 Any character enclosed within single quotes is called as a single character constant or simply, a
character constant.
 Some functions that perform operations on characters are given below.
Function Meaning
isalpha(c) It returns True if C is an uppercase letter and false if c is lowercase.
isdigit(c) It returns True if c is a digit (0 to 9) otherwise false
It returns True if c is digit from 0 through 9 or an alphabetic character
isalnum(c)
(either uppercase or lowercase) otherwise false
islower(c) It returns True if c is a lowercase letter otherwise False
isupper(c) It returns True if c is a uppercase letter otherwise False
toupper(c) It converts c to uppercase letter
tolower(c) It converts c to lowercase letter.

 Inputting single character


 We can input a character using the function get ( ).
 The general form is
char ch; or char ch;
cin =get(ch); ch=cin.get(ch);

 Outputting single character


 put ( ) function is used to display single character.
 The general form is cout.put (ch);
 Example: char ch;
ch=cin.get( );
cout.put (ch);

 String functions:
 A string is sequence of characters enclosed within double quotes.
 String are manipulated as one-dimensional array of characters and terminated by null („\0‟)
character.
 C++ provides many functions to manipulate strings.
 To use these functions, the header file string.h should be included.

 Declaring a string variable


 The general form to declare a string is:
char string _name[size];
 String_ name is the name of the string variable
 Size is the number of characters in the string. The size helps the compiler to allocate required
number of memory locations to store the string.
 Example: char st[50];
This declaration reserves 50-bytes to store the characters of the string variable st.

 Initializing a string
 Like other variables, strings can also be initialized when they are declared.
 Example: char s[10]=”Karnataka”;
 There are only 9 characters in the string. The null character („\0‟) is automatically appended
to the end of the string.
 Example: char s[ ]=”Bangalore”;
 The string st is initialized without specifying its size. The size is determined automatically
which is 9 in the above example.
 Example: char st[]={„E‟, „m‟, „p‟, „r‟, „e‟, „s‟, „s‟,‟\0‟};
 The string is initialized character –wise. In this case, we must specify the null character.
 Example: char st[10]=”Book”;
 The string is initialized with only 4-characters and the null characters and the null characters
are appended to the end f the string.
 If an entire string is initialized to a string-variable then the null character is
automatically appended to end-of-string.
 If string is initialized by giving the characters, then we must explicitly specify the string
terminator. i.e., null character.

 Inputting a string
 C++ provides the function getline ( ) to read a string.
 The general form is: cin.getline (string, size);
 Example :- cin.getline (st, 25);
 getline( ) the function terminates reading characters on reading a newline character or when
number of characters read is equal to size.
 The newline character is read, but replaced by null character.

 Outputting a string
 C++ provides the function write ( ) to output a string.
 The general form is: cout.write (string, size);
 Example:- cout.write (st, 25);
 write ( ) function displays the specified number of characters.
 This function does not stop displaying the characters when encountering the null character. As
a result, if the size specified is greater than the length of the string, it displays beyond the
bounds of the line.

Some string manipulation functions are given below:


 strlen( ) function
 This function returns the length of the string .i.e., the number of characters present in the
string, excluding the null character.
 The general form is variable=strlen(string);
 A string of length „0‟ is called a null string.
 Example:- l = strlen (“empress”); returns 7

 strcat( ) function
 This function is used to concatenate 2 strings. The process of combining 2 strings to form a
string is called as concatenation.
 The general form is strcat(string1, string2);
 Example:- char str1[ ]=”win”;
char str2[ ]=”dows8”;
strcat(str1,str2);
 str1 becomes “windows8”.

 strcpy( ) function
 A string cannot be copied to another string by using assignment statement. The function
strcpy() is used to copy a string into another string.
 The general form is strcpy (string1, string2);
 It copies all the characters to string2 to string1.
 Example:- char str1[ ]=”computer”;
char str2[ ]=”science”;
strcpy (str1,str2);
 str1 becomes ”science”

 strcmp( ) function
 This function is used to alphabetically compare a string with another string. This function is
case-sensitive. i.e., it treats the uppercase letters and lowercase letters as different.
 The general form is strcmp (string1, string2);
 It compares all the characters of str2 with str1. The function returns a positive value if
string1>string2, a negative vale if string 1<string2 or it string1 is same as string2.
 Example:- char str1[ ]=”There”;
char str2[ ]=”there”;
strcmp (str2,str1); //gives a positive value
But, strcmp (str1,str2); //gives a negative value
 strcmpi ( ) function
 This function is used to alphabetically compare a string with another string. This function is
not case-sensitive. i.e., it treats the uppercase letter and lowercase letter as same.
 The general form is strcmpi (string1,string2);
 It compares all the characters of str2 with str1. This function returns a positive value if
string1>string2, a negative value if string1<string2 or 0 it string1 is same as string2.
 Example:- char str1[ ]=”There”;
char str2[ ]=”there”;
strcmpi (str2,str1); //gives 0

 Other functions
 C++ provides some useful functions under the library stdlib.h. Some functions are rand( ),
srand( ), random( ) and randomized( ).
 These functions are used to generate pseudo-random numbers. i.e.,numbers that are uniformly
distributed within a given interval and for which there is no particular pattern.
 Computer will generate a number by itself!! Randomly, using this randomized ( ).
Function Meaning
randomize() It initialize/seeds the random number generator with a random number.
random(n) It generates a random number between 0 to n-1.
atoi(s) It converts string s into a numerical representation.
itoa(n) It converts a number to a string.
Chapter-13
USER DEFINED FUNCTIONS
 Definition:
 User-defined 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.

 Advantages of user-defined functions:


 If there is set of statements to be repeated several times in the program, these statements can be
replaced as a function and called whenever and whenever required.
 If a task in needed in more than one program or to a group of programmers, a function can be
developed and made available to other programs or other programmers.
 Programs can be modularized into functions. Each function can be developed independently,
debugged and tested.
 If a problem is divided into sub-problems, a team of programmers can be formed to solve each
sub-problem, rather solving by a single person.
 If functions are developed in a program, the number of line decreases.

 Function definition or structure of user-defined function:

 Return type-specifiers: is the data type of the value return by the function to another function
when it is called. It can be char, int, float or void. Data type void is used when the function return
no value to calling function.
 Function-name: is the name of the function. It is an identifier to identify the particular function in
a program.
 Argument-list with declaration: is the list of arguments or parameters or variables with their
declaration. Each argument should be declared separately. Each declaration should be separated by
comma. The list should be enclosed within parenthesis.
 The complete line is called the function header. Note that there is no semicolon at the end.
 Local-variable declaration: is the declaration of the variables that are used within the function.
Since these variables are local to the function, these variables are called as local variables.
 Executable statements: are the statements that perform the necessary operations to solve the
problem. If the function is returning a value, a return statement should be included. Otherwise
return statement is not necessary.
 Local declaration and executable statements are together called as body of the function. The body
of the function should be enclosed within the curled braces.
 Sample Program: To find the greatest of three numbers.
#include<iostream.h>
#include<conio.h>
void main( )
{
int biggest (int, int, int); //Function prototype
int a, b, c, big;
clrscr( );
Calling Function
cout<<”Enter the 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);
}

 Calling a function:
 The definition of the program can come either before the main( ) function or after the main( )
function.
 Calling function is a function that transfer control from it to another function by specifying the
name of that function and passing arguments.
 Called function is a function that receives the call and arguments from another calling function.
 Function call is the statement that is used to call or make another function execute.
 When a function call is made, the control jumps calling function to the called function.
 The general form of function call is:
General Form Example
variable = function_name (arugument list);
OR big = biggest(a, b, c);
variable = function_name( );

 main ( ) function:
 The main ( ) function returns a value of type int to the operating system. If the program runs
successfully, 0 is returned. Otherwise, a non-zero value is returned to the operating system,
indicating that the program contains errors.
 If the main ( ) function is not returning a value, the data type void can be used as return type
specifiers.
 The general form of main ( ) function is:
int main ( )
void main( )
{
{
Executable-Statements;
Executable-Statements;
return 0;
}
}

 Returning a value:
 When a function is called, the statements in the called function are executed.
 After executing the statements, the function returns value to the calling function. The return
statement is used to return a value.
 A function can return only one value or none to the calling function, for every function call.
 The general form of return statements is:
return (expression); OR return 0;
 Function Prototype:
 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.
 The general form of function prototype is:
General Form Example
return-type-specifier function-name ( type arg1, type arg2….) int biggest(int x, int y, int z);
OR OR
return-type-specifier function-name ( type, type ….) int biggest( int, int , int);
 Types of Arguments:
 A variable in a function header is called an argument. The arguments are used to pass information
from the calling function to the called function.

 Actual Arguments:
 The function call statement contains name of the function and the list of arguments to be passed.
These arguments or parameters are called as actual arguments.
 The arguments can be constants, variables, or expressions.
 Example: big = biggest (a, b, c);

 Formal Arguments:
 The function header contains return-type-specifier, function name and list of arguments with their
declaration.
 These arguments are called as formal arguments or dummy arguments. Formal arguments get their
values from the actual arguments.
 Example: int biggest (int x, int y, int z)

 Local Variables:
 The variables declared inside function or block is said belong to that block. These variables are
called as Local variables.
 Values of local variables are accessible only in that block.
 The function’s formal arguments are also considered as local variables.
 Example:
function-name (int a, int b)
{
int x, y; //x and y are local variables;
…………;
}

 Global Variables:
 The variables declared outside the function are called as global variables. These variables are
referred by the same data type and same name throughout the program in both calling function and
called function.
 Whenever if some variables are to treated as same value in both main( ) and in other functions, it is
advisable to use global variables.
 Example:
int a, b; // a and b are global variables
void main( )
{
int p, q; // p and q are local variables
……….
}
 Program: To find the LCM of two numbers:
#include<iostream.h>
#include<conio.h>
int a,b; // a and b are global variables
int gcd(int x, int y)
{
int r; // r is local variable
while(b!=0)
{
r = a%b;
a=b;
b=r;
}
return a;
}
void main( )
{
int gcd(int x, int y) //Function Prototype
int product, lcm, g;
clrscr( );
cout<<”enter two numbers:”;
cin>>a>>b;
produt= a *b;
g = gcd(a, b);
lcm = product/g;
cout<<”GCD=”<<g<<endl;
cout<<”LCM=”<<lcm<<endl;
getch();
}
 Scope of Variables:
 Scope of variables refers to the part of the program where the value of the variable can be used.
 The scope of the variables begins from where the variable declared.
 If the declaration is inside a function, the scope extends to the end of the innermost block that
contains the declaration.
 Example: To illustrate scope of variables
#include<iostream.h>
#include<conio.h>
void f( );
void g( );
int x=10;
void main( )
{
int x = 20;
{
int x = 30;
cout<<”In block inside main( ): x=”<<x<<endl;
}
cout<<”In main(): x=”<<x<<endl;
cout<<”In main(): ::x=””<<::x<<endl;
f( );
g( );
}
void f()
{
cout<<”In f(): x=”<<x<<endl;
}
void g()
{
int x=40;
cout<<”In g(): x=”<<x<<endl;
}
 Types of Function:
 There are different types of functions:
a. Function with no arguments and no return values.
b. Function with arguments and with no return values.
c. Function with no arguments and with return values.
d. Function with arguments and with return values.
e. Recursive function.
 Function with no arguments and no return values:
 In this method, the simply performs independent task. The function does not receive or send
any arguments.
General Form Example
void function-name( ) void natural( )
{ {
Statements; for(int i=1; i<=10; i++)
} cout<<”\t”<<I;
}
 Function with arguments and with no return values:
 In this method, the function receives some arguments and does not return any value.
General Form Example
void function-name(argument list) void sum(int x, int y, int z )
{ {
Statements; int sum;
} sum= x + y+ z;
cout<<”Sum =”<<sum;
}
 Function with no arguments and with return values:
 In this method, the function receives no arguments but return a value.
General Form Example
return-type function-name() int greatest( )
{ {
Statements; if(a>b);
return(value) return(a);
} else
return(b);
}
 Function with arguments and with return values:
 In this method, the function receives some arguments and returns a value.
General Form Example
return-type function-name(argument-list) float interest(float p, float t, float r)
{ {
Statements; si = (p * t * r)/100;
return(value) return(si);
} }
 Recursive function:
 Recursive function is a function that calls itself. The process of calling function by itself is
called as recursion.
General Form
return-type function-name(argument-list)
{
Statements;
return(function-name(argument-list))
}
 Passing default arguments to functions:
 In C++, to call a function we need not pass all the values for the arguments to a function from the
calling function.
 It allows us to assign default values to the formal arguments.
 Default values can be assigned to the argument which does not have a matching argument int the
function call.
 Default values are assigned in the function prototype.
 The default values are assigned to the arguments as we initialize variables.
 Example:
float interest(float amt, int time, float rate =0.15)
si = interest(5000,5) //third argument is missing
si=interest(5000, 5, 0.2) //No missing arguments

 Uses of default values:


 Default arguments are useful in situations where some arguments always have the same value.
 Default arguments provide flexibility to the programmer.
 Default arguments are used to add new arguments to the existing functions.
 Default arguments are used to combine similar functions into one.

 Passing Constant arguments:


 In C++, we can declare some arguments as constants. The compiler cannot modify the arguments
marked as constants.
 Example:
int strlen(const char *p);
int total(const int x, const int y);

 Pass by value or Call by Value:


 A function can be called by passing arguments from the calling function into the called function.
 Thus data is transferred through argument list.
 The calling function sends the data to the called function through actual parameters.
 The called function receives the data into its corresponding formal parameters.
 In pass by value, a copy of data sent by calling function stored in temporary locations,
 The called function uses these values as the initial values of the formal parameters.
 The formal parameters are processed or changed to generate the required result.
 However these changes are affected to the original values stored in the actual parameters.
 Example:
void main( )
{
void swap(int, int); //Function prototype
{
int a, b;
clrscr( );
cout<<”Enter two numbers”;
cin>>a>>b;
cout<<”Before calling the function: a=”<<a<<””and b=”<<b<<endl;
swap(a, b); //Actual Arguments
cout<<”After calling the function: a=”<<a<<””and b=”<<b<<endl;
getch();
}
void swap(int x, int y) //Formal Arguments
{
int temp;
temp = x;
Output:
x = y;
Enter two numbers 10 20
y= temp;
Before calling function: a=10 and b=20
}
After calling function: a=10 and b=20
 Pass by reference or call by reference:
 Sometimes we need to change the values of the actual arguments in the calling function. This is
not possible in the passing by value method.
 C++ allows us to pass arguments to the function by using reference variables.
 When we pass arguments by reference, the formal arguments int the called function become the
aliases to the actual arguments of the calling function i.e. the called function is actually uses the
original data with a different name.
 Example:
void main( )
{
void swap(int &, int &); //Function prototype
{
int a, b;
clrscr( );
cout<<”Enter two numbers”;
cin>>a>>b;
cout<<”Before calling the function: a=”<<a<<””and b=”<<b<<endl;
swap(a, b); //Actual Arguments
cout<<”After calling the function: a=”<<a<<””and b=”<<b<<endl;
getch();
}
void swap(int &x, int &y) //Formal Arguments
{
Output:
int temp;
Enter two numbers 10 20
temp = x;
Before calling function: a=10 and b=20
x = y;
After calling function: a=20 and b=10
y= temp;
}
Chapter-14
STRUCTURES
 Introduction:
 We 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 students into colleges 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 function

 Defining a structure
 The process of defining a structure includes giving the structure a name called the tag and telling
the compiler the name and the data type of each piece of data you want to be included in a
structure.
 Syntax:
Struct structure-name
{
datatype member-name-1;
datatype member-name-2;
……………………..
datatype member-name-n;
};
o The keyword struct introduces the structure definition.
o Next comes the structure name or tag, which is part.
o The declarations of the structures members are enclosed in braces.
o The list of all structure members is called template.
o A semicolon follows the closing braces, terminating the entire structure.

1|Page
 Example: A structure definition to hold employee information.
struct employee
{
int idno;
char name[15];
char designation[10];
float salary;
};
 This structure is named employee. It contains four members: an integer named idno, a character
array to hold 15 characters for a name, another character array to hold 10 characters for
designation and float named salary.
 The structure requires an area in memory, which is 31 bytes long.
 The figure given below shows the allocation of memory for the individual elements.
Idno Name Designation Float Total 31
2 bytes 15 bytes 10 bytes 4 bytes Bytes

 Declaring a structure or defining a structure variable:


 A structure can be declared (or a structure variable can be defined) as we defined a basic built-in
data type.
 The general form is
structure-name variable;
 Example 1: student old_student, new_student;
 old_student and new_student are the two structure variables declared as we declare built-in data
types.

 Example 2: employee emp1, emp2;


 emp1and 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.
 Example:
struct employee
{
int idno
char name[15];
char designation[10];
float salary;
} emp1, emp2;

2|Page
Manager  idno name designation salary



 Assistant  idno name designation salary

 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 be come either before the main function or before any
other variables are declared.
 The declaration of the structure variables always comes after the definition. The declaration of
the structure creates space to store the values for the variables.

 Accessing the elements of a structure


 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:
o The name of the structure variable (part1);
o The dot operator, which consists of a period (.)
o The member name (part3).
 Note: The real name of the dot operator is member access operator.
 Example 1: To access the name of the member emp1 of the tag employee, we write
emp1.name;
 Example 2: To access the salary of the member emp2 of the tag employee, we write
emp2.salary

3|Page
Sample Program: To input and display the information of a student

#include<iostream.h>
#include<iomanip.h>
#include<string.h>
void main ( )
{
struct student
{
int regno;
char name[15];
char comb[4];
float perc;
} st;
cout<<”Enter the register number of the student:”;
cin>>st.regno;
cout<<”Enter the name of the student:”;
cin>>st.name;
cout<<”Enter the combination of the student:”;
cin>>st.comb;
cout<<”Enter the percentage of the student:”;
cin>>st.perc;
cout<<”Register No:”<<st.regno<<endl;
cout<<”Name: ”<<st.name<<endl;
cout<<”Combination:”<<st.comb<<endl;
cout<<”Percentage:”<<st.perc<<endl;
getch();
}
Sample run:
Enter the register number of the student: 1234
Enter the name of the student: Nalina M A
Enter the combination of the student: CEBA
Enter the percentage of the student: 90.05

Register no: 1234


Name: Nalina M A
Combination: CEBA
Percentage:90.05

Example: Consider the assignments:


std.regno=12345
std.name[]=”empress college”;
std.perc=79.54;

4|Page
 Initializing a structure:
 Like any other data type, it is also possible to initialize the structure members of a structure
variable.
 Structures members are initialized when they are declared.
 Example: 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.

 A structure variable can be assigned to another structure variable.


 Example: std2 = std1;
 Here, std1 and std2 are the structure variables of the structure std.
 The value of each member of std1 is assigned to the corresponding member of std2.
 Since a large structure can have dozens of members, such an assignment statement can require the
computer to do a considerable amount of work.
 Note that one structure variable can be assigned to another only when they are of the same
structure type.
 If you try to assign a variable of one structure type to variable of another type, the compiler will
complain.

 Nested structures:
 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.
 During the declaration of nested structure, the definition of the embedded structure must appear
before the definition of outer structure.
 Example: consider the definition of the following structure.
struct distance struct room
{ {
int feet; distance length;
float inches; distance breadth;
}; };

5|Page
 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.
 Example: consider the definition of structure student.

struct date struct student


{ {
int dayno; int regno;
char month[10]; date doa, dob;
int year; int marks;
}; }std;
 To access the field regno of the structure std, we write std.regno.
 To access the day number of the date of admission of the structure std, we write std.doa.dayno.
 To access the year of date of birth of the student std, we write std.dob.year.

 Array of structures:
 A single variable that represents a structure creates memory space to store one set of information.
 If we want to create memory space for more instances then we may have to increases the number
of variables or use the facility called arrays.
 An array of structure 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.
 For example, let us consider that there are 10 students studying in a college. We have defined the
structure so that it could maintain information about students of the college. If we have to store
data of 10 students we need to use arrays rather than a single variable.
 When create an array of the structure, we are creating an array of the entire template. This can be
done as follows.
struct student
{
int regno;
char name [15];
char comb;
float fees;
} s [10];

6|Page
 In the declaration, s is an array of 10 elements. Each element of the array is a separate structure of
type of student.
 The expression:
o s[0].name will access the name of the 1st student, while
o s[9].fees access the fees paid by the last student
regno name comb fees
s[0] 
s[1] 

 ……………………….
s[9] 
Memory allocation for an array of structures
 An array of structures can be assigned initial values just like any other array.
 Remember that each element is a structure that must be assigned a corresponding set of initial
values. The process of initialization is illustrated below.
 Example:
struct info
{
int regno;
char name[15];
float fees;
};
info s[ ] = {
1, ”Lavanya”, 5500.00,
2, “Manasa”, 6250.00,
3, “Sajay”, 6000.00,
4, “Sahana”, 5900.00,
};

Practical Program 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.
#include<iostream.h>
#include<conio.h>
struct student
{
int regno;
char name[15];
char section[4];
};

7|Page
void main( )
{
student s[50];
int i, j, n;
clrscr( );
cout<<”How many students?”<<endl;
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<<”REG_NO \t NAME \t CLASS \t”<<endl;
for(i=0; i<n; i++)
cout<<s[i].regno<<”\t”<<s[i].name<<”\t”<< s[i].section<<endl;
getch( );
}

8|Page
Chapter-15
WORD PROCESSING
➢ One Mark Questions:
1. What is word processor?
• The word processor application is general purpose application software used in creating,
editing, letter documents, books, articles etc.
2. Name any two popularly used word processors.
• Microsoft Word Processor, StarOffice Writer, Kingsoft Writer
3. Give one important activity that is performed by a word processor.
• Used in creating, editing, letter documents, books, articles etc.
4. What does the title bar contain?
• The title bar contains the name of the file or application.
5. What information is present on the ruler bar?
• The ruler gives the status of the page with numeric values with the table.
6. What is menu?
• This bar displays the headings for each drop-down menu. Commands are grouped under each
of these menu headings according to function.
7. What is the extension of the word processor file?
• .doc or .docx
8. What happens when the left button of the mouse is clicked twice on a word?
• It will select the whole word.
9. How do we convert data to bold using formatting toolbar?
• Select the relevant portion of the text.
• Click the Bold button on the Formatting toolbar (Ctrl+B).
10. Which are the standard alignments used in word processor?
• Align Text Left , Center, Align Text Right , Justify
11. What is the use of the font dialog box?
• The Font dialog box lets the user choose attributes for a logical font, such as font family and
associated font style, point size, effects (underline, strikeout, text color), and a script
12. What are bullets?
• Bullets are symbols which can be used to arrange data in a sequence.
13. What is a header?
• A header is a text added to the top margin of every page such as a document title.
14. What is footer?
• Footer is a text added to the bottom margin of every page.
15. How do insert page number?
• On the Insert tab, click the Page Number icon, and then click Page Number.

➢ Two Mark Questions:


1. Give any two advantages of word processor?
• You can create documents fast, using built-in and custom templates.
• You can easily manage large documents using various features like the ability to create a table
of contents, index, and cross-references.
• You can work on multiple documents simultaneously
2. Give the steps involved to start word processor?
• Following steps show how to start Microsoft Office Word:
o Step 1: Click the Start Button - then Start Menu appears
o Step 2: Select All Programs
o Step 3: Go to Microsoft Office
o Step 4: Select Microsoft Office Word
3. Explain the usage of scroll bar and status bar.
• Scroll Bar: It is used to move the window viewing area like up, down, left and right.
Horizontal and Vertical Scrollbar are used to move the window.
• Status Bar: It appears at the left bottom corner of the window. It indicates current page,
section number and a total number of words in a document.
4. Give the steps for opening a new file in word processor.
• To open a new document, follow one of the following methods:
o Click the Office button
o Click the New option and then select Blank Document.
o Press CTRL+N keys on the keyboard.
5. Write the difference between save as and save?
• The save option allows us to save a new file or to save a file under the same name.
• The save as option allows us to save the existing file under a different name.
6. Give the steps for opening an existing document.
• If you have to open an existing document, then follow any one of the steps given below.
1. Click the Office button
2. Select the Open option
3. An open dialog box will be displayed.
4. Select the drive that contains the document. The list of folders and files are displayed.
5. In the list of files, select the document name.
6. Click on Open button. Then selected document will be opened.
7. Explain the different methods of selecting text in the mouse.
Selection Technique
Whole Word Double Click on the word
Whole Paragraph Triple-click within the Paragraph
Drag the mouse over the words or hold down Shift while
Several words or Lines
using the arrow keys.
Choose Select option followed by Select
Entire Document
All in menu bar Or Press Ctrl + A

8. Explain any two options of the formatting toolbar in detail.


• Formatting means changing the style and design of text and objects in the document in a
proper way and this can be achieved using the formatting toolbar.
 Font Face
1. Select the relevant text. This can be anything from a single character to the entire
document.
2. Select Font on the font group.
3. Click the Drop-Down on the Font Face.
4. Select the required Font face name.
 Font Size:
1. Select the relevant text.
2. Select Font Size on the Font clipboard.
3. Click the Drop-Down on the Font Size.
4. On the list, select Font Size and click it.
9. Explain the option copy in detail.
• Steps:
1. Select the relevant text or object.
2. Click the Copy button on the Home ribbon. OR
3. Press Ctrl+C to copy the text to the clipboard.
10. Explain the option copy and paste.
• Steps:
1. Select the relevant text or object.
2. Click the Copy button on the Home ribbon.
3. Place the cursor at the point where you would like to add the text.
4. Now click the Paste button.
11. How do we perform the undo operation?
• The UNDO features will keep a list of 100 actions that you have performed, and it allows for
taking “one step” backward in order to erase what you have just done.
• Click on the UNDO button to go back one step.
12. Give the commands for copy and paste?
• Copy: Ctrl + C, Paste: Ctrl+V
13. How to select the complete text?
• Choose Select option followed by SelectAll in menu bar Or Press Ctrl + A
14. What are tables in word processors?
• A table is used to display data as rows and columns.
• The different methods are inserting a table and drawing a table.
`

Chapter-16
SPREADSHEET
1. What is spread sheet?
 A spreadsheet is a software tool for entering, manipulating and analyzing sets of number.
2. What is Workbook?
 A workbook is a multipage Excel document.
3. Define Cell.
 The intersection of rows and columns is called a cell.
4. What is cell address?
 Every cell is identified by unique address called cell address, which includes the column
alphabet followed by the row number.
5. Why is the cell pointer used?
 A rectangular box which is used to identify the active cell is called cell pointer.
6. What is the extension with which a workbook is saved?
 A workbook is saved under the extension .xls or .xlsx.
7. How many rows and columns are there in the worksheet?
 65,536 (10, 48,576) rows and 256 (16,384) columns are there in the worksheet.
8. Explain any five features of Spreadsheet or ESS or Excel.
a) Tip wizard
 provides helpful tips and techniques based on what you are doing
 More efficient
b) External Data:
 Allows you retrieve or load data from external data source and use it in your worksheet.
c) Autosum:
 You can add a large range of data by simply selecting a tool button.
d) Autofill:
 Helps you to fill rows or columns with series of data
e) Financial Analysis:
 Used to make quick and easy financial analysis
 You can also analyses data and create presentation with charts. \
f) Drag and drop features
 Helps you to move the data and text from one place to another simply by dragging the data
with help of mouse
`

g) Windows Interface
 Microsoft Excel is windows based package, therefore the user interface is consistent.
h) Webpage
 Used to create web pages with ease and also run queries on data available on the net.
i) Shortcut menus
 Commands appropriate to the task that you are doing by clicking the right mouse button.

BUILT –IN FUNCTIONS

 DATE AND TIME FUNCTIONS


1. DAY( ) – Returns day from the date
 Syntax : =DAY(“MONTH-DAY-YEAR”)
 Example : =DAY(“01-26-2017”)
 Ans : 26
2. MONTH( ) – Returns month from the date
 Syntax : =MONTH(“MONTH-DAY-YEAR”)
 Example : =MONTH(“01-26-2017”)
 Ans : 01
3. YEAR( ) – Returns year from the date

Syntax: =YEAR(“MONTH-DAY-YEAR”)
 Example: =YEAR(“01-26-2017”)
 Ans : 2017
4. WEEKDAY ( ) – Returns Weekday from the date
 Syntax: =WEEKDAY(“MONTH-DAY-YEAR”)
 Example: =WEEKDAY(“01-26-2017”)
 Ans: 5
5. TODAY ( ) – Returns system date from the date
 Syntax: =TODAY( )
 Example: =TODAY( )
 Ans: 1/19/2017
6. NOW ( ) – Returns System date and time from the date
 Syntax: =NOW( )
 Example: =NOW( )
 Ans: 1/19/2017 10:08
`

7. DATE ( ) – Returns the serial number of the date or display the date in American format.
 Syntax: =DATE(YEAR,MONTH,DAY)
 Example: =DATE(2017,01,26)
 Ans: 1/26/2017

 ARITHMETIC FUNCTIONS
1. ABS ( )
 Returns the absolute value of the number.
 Number without a sign is called absolute number.
 Syntax : ABS(NUMBER)
 Example : =ABS(5 – 10)
 Answer : 5
2. SQRT ( )
 Returns the square root of the number.
 Syntax : SQRT(NUMBER)
 Example : =SQRT(100)
 Answer : 10
3. MOD ( )
 Returns the remainder after number is divided by divisor
 Syntax : MOD(NUMBER,DIVISOR)
 Example : =MOD(5,3)
 Answer : 2
4. PRODUCT ( )
 This function multiplies all the numbers given as arguments and returns the product
 Syntax : PRODUCT(NUMBER1,NUMBER2…..)
 Example : =PRODUCT(10,20)
 Answer : 200
5. SUM ( )
 Returns the sum of all the numbers in the list of A
1 10
arguments 2 20
 Syntax : SUM(NUMBER1,NUMBER2…..) 3 30
4 =SUM(A1:A3)
 Example : =SUM(A1:A3)
 Answer : 60
`

 STATISTICAL FUNCTIONS
A
1. MAX( ) – 1 10
 Returns the maximum value from the range of cells 2 20
3 30
 Syntax : MAX(RANGE) 4 =MAX(A1:A
 Example : =MAX(A1:A3) 3)

 Answer : 30
2. MIN( ) –
 Returns the minimum value from the range of cells A
1 10
 Syntax : MIN(RANGE) 2 20
 Example : =MIN(A1:A3) 3 30
4 =MIN(A1:A3)
 Answer : 10
3. AVERAGE( )
 Returns the Average value from the range of cells A
1 10
 Syntax : AVERAGE(RANGE)
2 20
 Example : =AVERAGE(A1:A3) 3 30
 Answer : 30 4 =AVERAGE(A1:
A3)
 LOGICAL FUNCTIONS:
1. AND( )
 This function returns TRUE if all its arguments are TRUE, returns FALSE, if one or more
arguments are FALSE.
 Syntax : AND(LOGICAL1,LOGICAL2…)
 LOGICAL1, LOGICAL2 are 1 to 30 conditions you want to test.
 Example : =AND(10 > 5,8 >7)
 Answer : TRUE
 Example : =AND(10 > 5,8 < 7)
 Answer : FALSE
2. OR( )
 This function returns TRUE if one or more arguments are TRUE, returns FALSE, if all
arguments are FALSE.
 Syntax : OR(LOGICAL1,LOGICAL2…)
 LOGICAL1, LOGICAL2 are 1 to 30 conditions you want to test.
 Example : =OR(10 > 5,8 >7)
 Answer : TRUE
`

 Example : =OR(10 > 5,8 < 7)


 Answer : TRUE
3. NOT( )
 This function returns the value of its argument.
 Syntax : NOT(LOGICAL)
 Example : =NOT(10 > 5)
 Answer : FALSE
 Example : =NOT(8 < 7)
 Answer : TRUE
4. IF( )
 When the logical_test is true, then it returns value-if-true otherwise value-if-false.
 Syntax: IF(LOGICAL_TEST,VALUE_IF_TRUE,VALUE_IF_FALSE)
 Example : =IF(A2>35,”PASS”,”FAIL”)
 Answer : FAIL
A B
1 PER CLASS
2 34 =IF(A2>35,”PASS”,”FAIL”)

 FINANCIAL FUNCTIONS:
1. RATE( )
 Returns the interest rate for an annuity.
 Syntax: 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.
 Type is Optional. It indicates when the payments are due.
2. PMT( )
 Returns the payment for a loan based on constant amount and a fixed interest.
 Syntax: PMT(RATE,NPER,PV,FV,TYPE)
 RATE – Is the interest rate per period.
 NPER - Is the total number of payments, periods in an annuity.
 PV – Is the loan amount
 Example: = PMT(B1/12,B2*12,B3,0,1)
`

 Ans : 3,288.55
A B
1 Rate of interest 12%
2 TERM 3
3 Loan amount 100000.00
4 payment = PMT(B1/12,B2*12,B3,0,1)
3. FV( )
 Returns the future value of an investment based on periodic, constant payments and a constant
interest.
 Syntax: FV(RATE,NPER,PMT,FV,TYPE)
 RATE – Is the interest rate per period.
 NPER - Is the total number of payments, periods in an annuity.
 PMT – Is the payment made each period, includes principal amount, interest amount.
 Example: = FV(B1/12,B2*12,B3,0,1)
 Ans : 43,507.65
A B
1 Rate of interest 12%
2 TERM 3
3 Monthly Deposit 1000
4 Future Value = FV(B1/12,B2*12,B3,0,1)

Logical Functions
AND Returns TRUE if all its arguments are TRUE
IF Specifies a logical test to perform
NOT Reverses the logic of its argument
OR Returns TRUE if any argument is TRUE
Date and Time Functions
DATE Returns the serial number of a particular date
DATEDIF Calculates the difference between two dates.
DAY Converts a serial number to a day of the month
HOUR Converts a serial number to an hour
MINUTE Converts a serial number to a minute
MONTH Converts a serial number to a month
NOW Returns the serial number of the current date and time
TIME Returns the serial number of a particular time
TODAY Returns the serial number of today's date
WEEKDAY Converts a serial number to a day of the week
YEAR Converts a serial number to a year
`

Mathematical Functions
EVEN Rounds a number up to the nearest even integer
FACT Returns the factorial of a number
GCD Returns the greatest common divisor
INT Rounds a number down to the nearest integer
LCM Returns the least common multiple
MMULT Returns the matrix product of two arrays
MOD Returns the remainder from division
ODD Rounds a number up to the nearest odd integer
PI Returns the value of Pi
POWER Returns the result of a number raised to a power
PRODUCT Multiplies its arguments
QUOTIENT Returns the integer portion of a division
ROUND Rounds a number to a specified number of digits
SUM Adds its arguments
Text Functions
CONCATENATE Joins several text items into one text item
EXACT Checks to see if two text values are identical
FIND Finds one text value within another (case-sensitive)
LEFT Returns the leftmost characters from a text value
LEN Returns the number of characters in a text string
LOWER Converts text to lowercase
REPLACE Replaces characters within text
RIGHT Returns the rightmost characters from a text value
TRIM Removes spaces from text
UPPER Converts text to uppercase

 What is Macro?
 Macro is a small program that carries out pre-defined and pre-recorded series of steps by
giving a few keyboard shortcuts or by running the macro name.
 Explain the steps for creating the macro.
 Select TOOLS->MACRO-> RECORD NEW MACRO
o This opens the Record Macro dialog box, specify the macro name and keyboard shortcut.
Then Click on OK. A very small “Stop Recording” toolbar will appear on the screen.
 You can now proceed on to record your macro. Just perform all the essential steps to complete
your particular task
 The click on “Stop Recording” button available on the “Stop Recording” toolbar.
`

 Run the macro by using keyboard shortcut, i.e.”ctrl + shift + key” or select TOOLS-
>MACRO->MACROS, Select macro name that you want to execute.

 How do you delete a Macro?


 Select TOOLS->MACRO->MACROS, select the macro name.
 Click on Delete.

 Mention the types of Databases


 Internal Database – Database created in the worksheet.
 External Database – Database which is created through other DBMS or RDBMS package like
MS-ACCESS, FOXPRO, dBASE, SQL SERVER, ORACLE etc.

 Creation of internal databases using built –in data form


 The Databases are entered and maintained by typing directly onto a worksheet.

 Functions of DATA->FORM
 Displays one record at a time
 Allow you to add new records and edit existing records
 Allow you to view records matching the specified criteria.

 What is Chart?
 Chart is a pictorial or graphical representation of numeric data.
 Write any five advantages of Chart.
 Data Effective
 Interesting and various formatting options are available
 Easy to understand
 Easy to Analyze
 Compare data
 Mention any types of Chart
 Line chart
 Bar Chart
 Column Chart
 Pie Chart
 Area Chart
 Explain the steps for creation of a chart.
 To create a chart
`

1. Select all the cells containing data including labels.


2. Click the Insert tab. Select any type of the Charts group. A
list of chart sub-types appears.
3. Click any Chart option.
4. The chart will be created depending upon your choice.
Chapter-17
WEB DESIGNING
 Introduction:
 A computer network is a set of computers connected together for the purpose of sharing
resources.
 The most common resource shared today is
a connection to the Internet.
 Other shared resources can include a printer
or a file server. The Internet itself can be
considered as a computer network.
 The term internet is derived from two words
Interconnection and Network.
 The Internet is a combined collection of many interconnected computer networks around the
world.
 Each network consists of multiple numbers of computers connected through cables, wireless or
any other media.
 Using these computers people can share and exchange information.
 A connection to the Internet is needed to access the Internet.

 Some terms related to Web:


 WWW:
 In September 1994, Berners-Lee founded the World Wide Web Consortium (W3C).
 The World Wide Web is also called as “WWW”, it allows computer users to locate and
access any information over the internet.
 The Web is a collection of millions of pages of information.
 The information can include text, pictures, animations, sound and video.
 We can usually find information about any topic on the Internet.

 Web page:
 The documents available on WWW are known as web pages.
 A web page is a file containing information in text, graphics, Audio and Video.

 Web site:
 The location where the information is available on the web is called a website.
 A website is a collection of web pages.
 The Web pages are organized on a website like the pages of a book.
 Each Website is owned and updated by an individual, company or organization.

 Web server:
 The WebPages on the internet are stored on the computers that are connected to the internet,
these computers are knownas web servers.
 Any computer that has a server software installed on it and is connected to the internet can act
as a web server.

 Browser:
 A web browser, or simply "browser," is an application used to access and view websites.
 It enables the user to view web pages, navigates websites, and move from one website to
another.
 Popular Web browsers are Internet explorer, Mozilla Firefox, Google Chrome, Netscape
navigator, Opera etc.

 HTTP:
 The term hyper text was coined by Ted Nelson.
 The internal structure of the World Wide Web is built on a set of rules called Hypertext
Transfer protocol (HTTP).
 HTTP is the protocol to exchange or transfer hypertext.
 DNS:
 The Domain Name System (DNS) is a hierarchical distributed naming system for computers,
services or any resources connected to the Internet or a private network.

 URL:
 A website is accessed by using the website address called the URL (Uniform resource locator).
 HTTP uses internet addresses in a URL format.
 URLs look like this: type://address/path/
 Example: http://www.karnataka.gov.in or http://www.kreis.kar.nic.in

 Hyperlink:
 A hyperlink is a connection that allows you to move easily from one web page to another
related web page.
 Text, images can be made into hyperlinks.
 A hyperlink is usually underlined.
 Clicking on the hyperlink takes you to a different page.

 Search Engine:
 A search engine is an information retrieval system designed to help find information stored on
a computer system in the system.
 The sear engine allows one to ask for content meeting specific word or phrase and retrieves a
list of items that matches those criteria.
 Search engines use regularly updated indexes to operate quickly and efficiently.
 There are many search engines available freely. Some of them are google.com, msn.com,
yahoo.com.

 Surfing on the internet:


 There are large numbers of servers on the internet, when the user is looking for some
information; it may necessary to look for such information from more than one server.
 WWW links the computers on the Internet like spider web, facilitating users to go from one
computer to another directly.
 The term “surfing” is generally used to describe an unidirectional type of web browsing in
which the user jumps from one page to another page, as opposed to searching for a specific
information.
We can browse the information on any subjects. For example, enter the URL www.wikipedia.org
in the address bar. This is a website where you can find the information on many subjects.

 Advantages/ Internet Services:


 In this world of information technology, there is no field which does not use the internet.
 In the field of Science and technology, Military, Engineering, Banking, Multimedia, Medicine,
Aviation, Education, Business, Entertainment and so on.
 Some important services on the internet are:

 World Wide Web:


 This is also called web or www or 3w.
 The collection of all web pages in all web sites on Internet is called www.
 These web pages provide us information in the form of text, pictures, audio and video formats
etc.
 E-MAIL:
 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 within seconds or minutes.

 NEWSGROUPS:
 Newsgroups are discussion groups on internet.
 They are used for free exchange of information.
 A user sends a message to the news group site.
 Other users read this message from this site and reply.
 Newsgroups are provided by special computers called news servers.
 E-COMMERCE:
 It stands for Electronic Commerce.
 E-commerce means to carry out business dealings by internet.
 Examples of Ecommerce include: Online Banking, Online shopping and online education etc.

 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.

 TELNET or Remote Login:


 Telnet is a computer based protocol which permits your computer to log onto another computer
at some location and use it as if you were there.
 This is an important service using which journalist can transfer their stories into their
organization server in a matter of seconds.

 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 Yahoo messenger or MSN messenger is used for chatting.

 GOPHER:
 A gopher on the Internet is a system for users to search for files via menus or directory
structures.
 It uses plain English names and is text based only.

 About E-Mail:
 Electronic mail (also known as email or e-mail) is one of the most commonly used services
on the Internet, allowing people to send messages to one or more recipients.
 The email was invented by V.A Shiva Ayyadurai in 1972.

 Why use E-Mail?


 The operating principle behind email is relatively simple, which has quickly made it the most
popular service used on the Internet.
 As with a traditional postal service, for your message to reach your recipient, all you need to
know is their address.
 Its two main advantages over "paper mail" are the speed at which the email is sent (practically
instantaneous) and the lower cost (included with the cost of an Internet connection).

 Email addresses:
 Email addresses (both for senders and recipients) are two strings separated by the character
"@" (" at sign"): user@domain
 The right-hand part describes the domain name involved, and the left-hand part refers to the
user who belongs to that domain.
 In practice, an email address often looks something like this:
firstname.lastname@provider.domain
 Advantages of E-mail:
1. Easy to Use 7. Environment friendly
2. Speed 8. Use of graphics
3. Easy to prioritize 9. Advertising tool
4. Reliable and secure 10. Cheap service
5. Easier for reference 11. Data Storage
6. Automated emails 12. Provision of attachment.

 Disadvantages of E-mail are:


1. Viruses:
 These are computer programs which have the potential to harm a computer system.
 Recipients need to scan the mails since; viruses are transmitted through them and have
the potential to harm the computer.
2. Spam:
 Emails when used to send unwanted advertisements are termed as spam.
 Checking and deleting the unwanted mails can unnecessarily consume a lot of time.
3. Hacking:
 The act of breaking into computer security is termed as hacking.
 Hackers access the important information and programs and may destroy it.
 Hackers try to get password of internet users and then access important information.

 Introduction to HTML:
 HTML stands for Hypertext Markup Language, and it is the most widely used Language to
write Web Pages.
 Hypertext refers to the way in which Web pages (HTML documents) are linked together.
 Thus the link available on a webpage is called Hypertext.
 HTML documents are also called web pages.
 Now, HTML is being widely used to format web pages with the help of different tags available in
HTML.

 HTML Document Structure:


 A typical HTML document will have following structure: Document declaration tag

<html>
<head>
Document header related tags
</head>
<body>
Document body related tags
</body>
</html>

 HTML Tags:
 HTML markup tags are usually called HTML tags.
 These tags are keywords (tag name) surrounded by angle braces like <Tag Name>.
 The first pair of tags is the start tag and the second tag is the end tag.
 End tag contains a forward slash before the tag name.
 Start tag and end tag are also called opening tags and closing tags.
 Except few tags, most of the tags have their corresponding closing tags.
 For example <html> has its closing tag </html> and <body> tag has its closing tag </body> tag.
Tags Description
This tag encloses the complete HTML document and mainly comprises
<html> of document header which is represented by <head>...</head> and
document body which is represented by <body>...</body> tags.
This tag represents the document's header which can keep other HTML
<head>
tags like <title>, <link> etc.
The <title> tag is used inside the <head> tag to mention the document
<title>
title.
This tag represents the document's body which keeps other HTML tags
<body>
like <h1>, <div>, <p> etc.

 Executing a HTML program:


 The first step in creating a HTML document is to write code in the text editor.
 The commonly used text editor is notepad. The notepad can be opened in the following sequence.
o Click on Start Button
o Type Notepad in search programs and files and press Enter.
o Notepad window will appear. Type your HTML program and save it with the
filename.htm (html) extension.
o Open the web browser, type the address of the HTML file in address bar press Enter.

 The <!DOCTYPE> Declaration:


 The <!DOCTYPE> declaration tag is used by the web browser to understand the version of the
HTML used in the document.
 Current version of HTML is 5 and it makes use of the following declaratio n
 Basic HTML Document <!DOCTYPE html>
 In its simplest form, following is an example of an HTML document:
<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document content goes here .... </p>
</body>
</html>

 Let's save it in an HTML file test.htm using your favorite text editor.
 Finally open it using a web browser like Internet Explorer, Google Chrome, or Firefox etc.
 It shows the following output:

 HTML Basic Tags:


 Heading Tags:
 Any document starts with a heading. You can use different sizes for your headings.
 HTML also has six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>,
and <h6>.
 While displaying any heading, browser adds one line before and one line after that heading.
 Example
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>

 This will produce following result:

 Paragraph Tag:
 The <p> tag offers a way to structure your text into different paragraphs.
 Each paragraph of text should go in between an opening <p> and a closing </p> tag as shown
below in the example:
 Example <body>
<p>Here is a first paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
<p>Here is a third paragraph of text.</p>
</body>

 This will produce following result:

 Line Break Tag:


 Whenever you use the <br /> element, anything following it starts from the next line.
 This tag is an example of an empty element, where you do not need opening and closing tags, as
there is nothing to go in between them.
 The <br /> tag has a space between the characters br and the forward slash.
 Example <body>
<p>Hello<br />
You delivered your assignment on time.<br /> Thanks<br />
Mahnaz</p>
</body>
 Horizontal Lines:
 Horizontal lines are used to visually break up sections of a document.
 The <hr> tag creates a line from the current position in the document to the right margin and
breaks the line accordingly.
 For example, you may want to give a line between two paragraphs as in the given example below:
<body>
 Example
<p>This is paragraph one and should be on top</p>
<hr />
<p>This is paragraph two and should be at bottom</p>
</body>

 This will produce following result:

 HTML Formatting:
 Bold Text:
 Anything that appears within <b>...</b> element is displayed in bold as shown below:
 Example
<body>
<p>The following word uses a <b>bold</b> typeface.</p>
</body>
 This will produce following result:

 Italic Text:
 Anything that appears within <i>...</i> element is displayed in italicized as shown below:
 Example
<body>
<p>The following word uses a <i>italicized</i> typeface.</p>
</body>
 Text Formatting Tags:
Tag Description Tag Description
<b> Defines bold text <i> Defines italic text
<em> Defines emphasized text <u> Underline
<strong> Defines strong text <small> Defines small text
<sub> Defines subscripted text <sup> Defines superscripted text
<ins> Defines inserted text <del> Defines deleted text

 HTML Images:
 Images are very important to beautify as well as to depict many complex concepts in simple way
on your web page.
 This will take you through simple steps to use images in your web pages.

 Insert Image:
 You can insert any image in your web page by using <img> tag.
 Following is the simple syntax to use this tag. <img src="Image URL" ... attributes-list/>

<body>
<p>Simple Image Insert</p>
<img src="test.png" alt="Test Image" />
</body>

 This will produce following result:

 You can use PNG, JPEG or GIF image file based on your comfort but make sure you specify
correct image file name in src attribute. Image name is always case sensitive.
 The alt attribute is a mandatory attribute which specifies an alternate text for an image, if the
image cannot be displayed.

 HTML Hyper Links:


 A webpage can contain various links that take you directly to other pages and even specific parts
of a given page. These links are known as hyperlinks.
 Hyperlinks allow visitors to navigate between Web sites by clicking on words, phrases, and
images. Thus you can create hyperlinks using text or images available on a webpage.
<A href=”filename.html” title=”Next page”> Next page</A>

 Anchor element allows you to link various WebPages or different sections on the same page. The
syntax of Anchor element is given below:
<A>………</A>

 The various attributes of the Anchor element are HREF, NAME, TITLE, TARGET and ALT
o Href: The href (hyperlink reference) attribute specifies the location of the file or resource
that you want to provide a link to.
o Name: The name attribute specifies a location within the current or the existing document.
o Title: The title attribute specifies a title for the file which you are providing a link.
o Target: The target attribute specifies a position in the webpage where the browser displays
a file.
o Alt: The alt attribute specifies the alternative text which is displayed when an image used
as a hyperlink is not displayed.

 HTML Lists:
 HTML offers web authors three ways for specifying lists of information.
 All lists must contain one or more list elements.
 Lists may contain:
1. <ul> - An unordered list. This will list items using plain bullets.
2. <ol> - An ordered list. This will use different schemes of numbers to list your items.
3. <dl> - A definition list. This arranges your items in the same way as they are arranged in a
dictionary.

 Unordered Lists:
 An unordered list is a collection of related items that have no special order or sequence. This
list is created by using HTML <ul> tag. Each item in the list is marked with a bullet.
 Example
<ul>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
 Ordered Lists:
 If you are required to put your items in a numbered list instead of bulleted list then HTML
ordered list will be used.
 This list is created by using <ol> tag.
 The numbering starts at one and is incremented by one for each successive ordered list element
tagged with <li>.
 Example <ol>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>

Practical Program 1: Create a web page to display your details using different tags.
<HTML>
<HEAD>
<TITLE> 1ST PUC CS STUDENTS </TITLE>
</HEAD>
<BODY BGCOLOR=ORANGE>
<FONT COLOR=RED>
<H1> <CENTER> FIRST PUC COMPUTER SCIENCE BOOK</CENTER> </H1>
</FONT>
<IMG SRC = "C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg" ALIGN=LEFT WIDTH=200
HEIGHT=300 BORDER=1>
<P> <I> COMPUTER SCIENCE </I> with C++ is a major subject at PUC level with an aim of
creating Computer-qualified graduates later on. This subject focuses on concepts of <B> computer
Fundamentals, Programming Methodology, and Programming in C++, OOP’s, Word Processor, Electronic
Spread Sheet, and Web Programming. </B> </P>
</P> This text book promises to guide you for the preparation of any exam on these topics. This book covers
the manual which are worked on with the samples. </P>
<FONT FACE= CAMBRIA COLOR=YELLOW>
<H2>SAILENT FEATURES</H2>
</FONT>
<OL>
<LI> Computer Fundamentals</LI>
<LI> Programming Methodology</LI>
<LI> Data Representation</LI>
<LI> Programming in C++</LI>
<LI> Word Processor</LI>
<LI> Electronic Spread Sheet</LI>
<LI> Web Programming</LI>
</OL>
</BODY>
</HTML>

Practical Program 2: Create a MODEL Web site for your college making using different tags.
Filename: Introduction.htm
<HTML>
<HEAD>
<TITLE> MDRPUC HASSAN </TITLE>
</HEAD>
<BODY BGCOLOR=ORANGE>
<FONT COLOR=RED>
<CENTER>
<H4> GOVERNMENT OF KARNATAKA </H4>
<H1> MORARJI DESAI RESIDENTIAL PU SCIENCE COLLEGE </H1>
<H3> GUDDENAHALLI, BELUR ROAD, HASSAN-573201 </H3>
</CENTER>
</FONT>
<IMG SRC = "C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg" ALIGN=LEFT WIDTH=200
HEIGHT=300 BORDER=1>
<FONT FACE=CAMBRIA SIZE=06 COLOR=CYAN>
<P> MDRPU COLLEGE, Hassan most prestigious institutions in Karnataka. <BR /> Has been a
pioneer in the field of education for many years, Excellency in imparting quality knowledge. </P>
<P> Click on one of the following to get additional information </P>
</FONT>
<A HREF=”D:\COURSE.HTM” TITLE=”COURSES”> COURSES OFFERED </A> <BR> <BR>
<Marquee Direction=”Right”> Admission for the Eligible Students </Marquee>
</BODY>
</HTML>
Filename: Course.htm
<HTML>
<HEAD>
<TITLE> MDRPUC HASSAN- COURSES INFORMATION</TITLE>
</HEAD>
<BODY >
<H1><CENTER> COURSES OFFERED </CENTER></H1>
<P>
<FONT FACE=VERDANA SIZE=4 COLOR=BLUE>
<B> Part-I is Compulsory for all Students </B> <BR>
<B> Language 1- Kannada </B> <BR>
<B> Language 2 – English </B> <BR> <BR>
</FONT>
<FONT FACE=TIMES NEW ROMAN SIZE=4 COLOR=RED>
<B>SCIENCE</B><BR>
<B> PCMB - </B> Physics, Chemistry, Mathematics, Biology <BR>
<B> PCMC - </B> Physics, Chemistry, Mathematics, Computer Science<BR>
<B> PCME - </B> Physics, Chemistry, Mathematics, Electronics <BR>
</FONT>
<Marquee Direction=”Left”> <B> Medium of Instruction - English </B> </Marquee>
</BODY>
</HTML>

You might also like