Professional Documents
Culture Documents
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.
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.
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 Operating System, TUX Paint, Office Packages, Nudi, Adobe Reader, Computer
Games etc.
. 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.
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.
1. Input Unit
2. Central Processing Unit(CPU)
Control Unit
Arithmetic and Logic Unit (ALU)
3. Memory Unit
4. Output Unit
Control Unit
CPU
Memory Unit
Primary Memory
Secondary Memory
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.
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.
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.
Generations of Computer
Depending on the development of the technology the generation of computer is classified into
five generations.
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:
UNIAC
Universal Automatic Computer was the first commercial computer produced in the United
States.
Some computers of this generation were IBM 1620, IBM 7094, CDC (Control Data
Corporation) 1604 and 3600, and UNIVAC 1108.
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.
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.
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
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.
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.
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
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
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:
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:
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 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.
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.
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:
Printer:
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.
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:
Computer Memory
Primary Memory
EDO RAM:
SRAM:
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.
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
DVD
Blu-Ray Disk
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.
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:
Bits 1 1 0 1 1 1 0 1
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.
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)
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
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
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
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
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:
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
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.
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
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.
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.
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
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.
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))
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;
STOP STOP
2. Write a program, design a flow chart and an algorithm to find given number is odd or even.
Step 1: Start
Advantage of Flowcharts
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 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.
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;
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);
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;
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.
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
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.
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
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 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
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)
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
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.
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.
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.
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;
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:
• 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.
• 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 – 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.
if (Test Condition)
Statement 1;
else
Statement 2;
if( n % 2 == 0 )
cout<<“Number is even”;
else
cout<<“Number is odd”;
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.
if (Test Condition 1)
Statement 1;
else
if (Test Condition 2)
Statement 2;
else ………..
else
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)
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) {
break;
break;
…………..
break;
The switch statement checks the values of the variable or expression given within the parenthesis
with a list of case constants.
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);
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.
Statement 1;
Statement 2;
Statement N;
Example:
sum = 0;
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.
• Exiting a loop.
All these can be done by using break, exit and continue statements.
break statement:
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.
Example:
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 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.
Example:
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 (:).
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.
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:
#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;
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.
#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 ;
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;
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;
#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;
#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
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.
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( );
}
Row-Number
1 a[2] [3]
2 * 2 Row Number
3 Column Number
….
m-1
}; 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];
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.
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.
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.
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.
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.
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
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
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.
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
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.
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.
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.
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.
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
`
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.
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
`
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.
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.
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.
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.
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>
<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.
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:
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>
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>
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.
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>