0% found this document useful (0 votes)
35 views121 pages

+1 Class Notes

The document outlines the evolution of number systems and computing machines, detailing various historical number systems such as Egyptian, Sumerian, and Hindu-Arabic, as well as computing devices from the abacus to modern computers. It describes the generations of computers from vacuum tube technology to artificial intelligence, and explains programming languages, the theory of computation, and the components of a computer system. Key figures in computer science, such as Alan Turing and Charles Babbage, are also highlighted, along with methods for representing integers and floating-point numbers.

Uploaded by

aswinpramod082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views121 pages

+1 Class Notes

The document outlines the evolution of number systems and computing machines, detailing various historical number systems such as Egyptian, Sumerian, and Hindu-Arabic, as well as computing devices from the abacus to modern computers. It describes the generations of computers from vacuum tube technology to artificial intelligence, and explains programming languages, the theory of computation, and the components of a computer system. Key figures in computer science, such as Alan Turing and Charles Babbage, are also highlighted, along with methods for representing integers and floating-point numbers.

Uploaded by

aswinpramod082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

+1

COMPUTER
SCIENCE

KALLADI HSS NOTES BY MUSTHAFA 9544885401


1.The Descipline of Computing
Evolution of Number System
1. Egyptian Number System
• It emerged around 3000 BC.
• It used 10 as Base/radix.
• They had different symbols for representing 1 to 9 , 10 to 90 , 100 to 900 and 1000 to 9000.
• They used to write from Right to left
2. Sumerian /Babylonian Number System
• It used 60 as Base . Also known as Sexa gecimal Number System.
• Number system with the largest base.
• They used blank space to represent zero.
3. Chinese Number System
• Chinese number system emerged around 2500 BC.
• It used 10 as Base.
• The Simplest and Most efficient number system.
• Used Numbers from 1 to 9.
4. Greek Number System
• Also known as Ionian Number System.
• It was a decimal number system.
• They did not used any symbol for Zero.
5. Roman Number System
• Romans used mathematics for practical purposes.
• They used 7 symbols of alphabet I, V , X, L, C, D and M for rep[resenting numbers.
6. Mayan Number System
• Mayans used 20 as its base . 20 is the sum of fingers and toes.
• They could produce accurate measurements.
7. Hindu Arabic Number System
• It originated in India before 1500 years.
• It is a positional number system.
• They introduced the symbol 0 to represent zero.

Evolution of Computing Machines


1.Abacus

• Abacus means ‘Calculating Board’ ;.


• Also known as Couting Frame.
• It was Discovered by Mesopotamians around 3000 BC.
• It was the first computer for performing basic arithmetic calculations.
• It consist of Beads on movable rods that is divided into two parts.
• Children uses Abacus now a days to learn counting.
• It works on the basis of place value system.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


2.Napier’s Bones

• It was developed by famous mathematician John Napier.


• It was used to multiply a large number with a single digit number.
• It consist of 10 Bones(rods) to represent numbers 0-9 and an eleventh bone to represent multiplier.

3. Pascaline

• It was Developed by Blaise Pascal.


• Pascaline was capable of Adding and Substracting two numbers Directly and could multiply and divide by
repetition.
• The device was operated by dialing a series of wheels , gears and cylinders.

4. Leibniz’s calculator

• It was developed by German mathematician Leibniz.


• Also known as Step Reckoner.
• It was capable of performing all the four basic Arithmetic Operations.
• He could successfully introduced this calculator to market.

5. Jacquad’s Loom

• Developed by Marie Jacqad to simplify the process of manufacturing textiles with complex patterns.
• The loom was controlledby punched cards .
• Multiple rows of holes were punched on each card, with one complete row corresponding to one row of
the design.
• Patterns stored on punched cards could be reused to create the same product.
• It was the First machine that could store information.

6. Difference Engine

• Developed by Charles babbage.


• It could perform Arithmetic operations and print results automatically.
• Babbage invented Difference Engine to produce/compile mathematical tables.

7. Analytical Engine

• Developed by Charles babbage.


• It was the real predecessor of modern computers.
• It could perform general purpose computation along with arithmetic calculations.
• It had a Store(memory) to store numbers and intermediate results and a mill (Processor) to perform
arithmetic processing.
• Its Input/Output devices were in the form of Punched cards containing instructions.

8. Hollerith’s Machine

• Developed by Herman Hollerith.


• It was the first electromechanical computer.
• It used punched cards for input , output and instructions.
• It used Electricity to read , count and sort punched cards whose holes represent data.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


9. Mark -1

• Developed by Howard Aiken with IBM Engineers.


• It was the First Automatic Electromechanical Computer,
• It could perform all four arithmetic operations and handled numbers upto 23 decimal places.
• It could add two numbers in 3-6 seconds.
• It was programmed to handle logarithms and trigonometric functions.
• It used paper-tape readers , card readers,punched cards and type writers for Input and Output.

Generations of Computers
Based on various stages of development computers can be divided into different generations:

1) First Generation Computers (1940 – 1956 )


• First generation computers were built using vaccum tube technology.
• Vaccum tube is a device controlling electric current through a vaccum in a sealed container.
• Implemented the stored program concept.
• Computers were very bulky, consumed high amount of electricity and emit large amount of heat.
• Machine/Binary Language was used.
• ENIAC , EDVAC , UNIVAC belongs to this generation.
• ENIAC (Electronic Numerical Integrator and Calculator) –First general purpose programmable Electronic
Computer .
• EDVAC – Electronic Discrete Variable Automatic Computer (Computer with stored program concept)
• UNIVAC – Universal Automatic Computer(First Commercially Successful computer).
2) Second Generation Computers (1956 – 1963 )
• Second generation computers were built using transistor technology.
• Computers becomes smaller , faster, inexpensive and powerful than first generation computers.
• The computers consumed less electricity and emitted less amount of heat.
• It used magnetic core for primary memory and magnetic disc for secondary memory.
• Assembly languages were used.
• IBM 1401 and IBM 1620 are popular computers.
3) Third Generation Computers (1964 – 1971 )
• Third generation computers were built using IC (Integrated Circuit) technology.
• IC Chips reduced the size and increased the speed and efficiency of computing.
• Computers had better processing speed , consumed less power and cost decreased.
• Input /Output devices like Keyboard and monitor were introduced.
• High level programming languages were developed.
• IBM 360 and IBM 370 belongs to this generation.
4) Fourth Generation Computers ( 1971 onwards )
• Fourth Generation computers were built on Microprocessor and VLSI technology.
• Microprocessor is a single chip to which electronic components like transistors, capacitors,resistors were
integrated.
• Computers becomes very smaller , very faster and have high data processing capacity.
• Computer networks and internet were introduced.
• IBM PC , Apple II were belongs to this generation.
5) Fifth Generation Computers ( Future)
• Fifth Generation computers are based on Artificial Intelligence (AI).
• AI is the branch of Computer Science that makes machines to behave like humans.
• It aims to develop machines that can process natural languages.
• LISP and Prolog are examples for AI programming languages.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Programming Languages
It is an Artificial Language designed to communicate Instructions to a computer . Three types of Programming languages are:

1. Machine Language
• It was the first programming language developed to use in computer.
• It consist of strings of binary digits ‘0’ and ‘1’.
• It improved the speed and efficiency of computers.
• It is difficulty to track and correct errors.
• It is highly machine dependable and programmer needs to have high knowledge about the computer
architecture.

2. Assembly Language.
• It used English like words to write a program.
• Writing programs becomes easy using Assembly language.
• It is machine dependant and programs written in one computer are not transferrable to other computers.
• EDSAC ( Electronic Delay Storage Automatic Calculator) was the first machine that used Assembly Language.
3. High Level Language (HLL).
• It used English like words and statements to write a program.
• It is very easy to write programs using High Level Language.
• It is a machine independant language and programs are transferrable to other computers.
• A-0 was the first High level language, developed by Grace Hooper for UNIVAC-1.

Theory Of Computation

The branch of Computer Science that deals with how efficiently problems can be solved based on computational models
and Algorithms.

Alan Turing

• He was a British Mathematician ,Logician , Cryptographer and Computational Scientist.


• He is considered as the father of Modern Computer Science and Artificial Intelligence.
• He made a lot of contributions to the field of Computer science.
• He proposed the ’ Turing Test ‘ which is considered to be the test for determining machine’s Intelligence.

Turing Machine

• It is a model of computer proposed by Alan Turing.


• Turing Machine is a computing device that could print symbols on a paper tape in a model that a person following a
series of logical instructions.
• It consist of a long tape which act like a memory in computer..
• It tape contains cells that can have symbols ‘0’ , ‘1’ and blank space.

Von Neumann Architecture

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• The von Neumann Architecture consist of Input Unit, Output Unit , Memory Unit and Central Processing Unit
(CPU).
• The Central Processing Unit (CPU) consist of Control Unit and Arithmetic Logic Unit (ALU).
• This model implements stored program concept in which data and instructions are stored in memory.

EXPAND

• ENIAC (Electronic Numerical Integrator and Calculator) –First general purpose programmable Electronic Computer .

• EDVAC – Electronic Discrete Variable Automatic Computer (Computer with stored program concept)

• UNIVAC – Universal Automatic Computer(First Commercially Successful computer).

• VLSI – Very Large Scale Integration

➢ Father of Computer – Charles Babbage


➢ Father of Computer Science – Alan Turing
➢ First Programmer – Agusta Ada lowelace
➢ First High Level Programming language- A-0 developed by Grace Hopper

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Representation of Integers-

The three methods for representing integer numbers are:

1. Sign and Magnitude Method - Steps for representing an integer number in sign and magnitude form are:

i. Find the binary equivalent of the integer number.

ii. Make it of 7 bits by adding 0’s to the left.

iii. Add sign bit – add ‘0’ if the number is positive and add ‘1’ if the number is negative , to the lft.

2. 1’S complement Method- Steps for representing an integer number in 1’s complement method/ form are:

i. Find the binary equivalent of the integer number.

ii. Make it of 8 bits by adding 0’s to the left. The 8 bit form is the 1’s complement of Positive Numbers.

iii. If the number is negative , Replace Every 0’s with 1’s and every 1’s with 0’s.

3. 2’S complement Method- Steps for representing an integer number in 2’s complement method are:

A. Find the binary equivalent of the integer number.

B. Make it of 8 bits by adding 0’s to the left. The 8 bit form is the 2’s complement of Positive Numbers.

C. If the number is negative – find its 1’s complement by Replacing Every 0’s with 1’s and every 1’s with 0’s.

D. Add ‘1’ with the obtained 1’s complement.

Representation of Floating Point Numbers

➔ A floating point number consist of integer part and decimal part.

➔ A floating point number is represented in floating point notation have two parts- Exponent and mantissa.

➔ In a 32 bit representation , 24 bits are used to represent Mantissa and 8 bits are used to represent exponent. The bits of mantissa
and exponent is to represent its sign.

Representaion of Characters

ASCII

➔ ASCII stands for American Standard Code for Information Inteerchange.

➔ ASCII uses 7 b its to represent a single character in memory.

➔ It can represent upto 128 characters.

➔ Another version of ASCII , ASCII-8 uses 8 bits and can represent 256 characters.

Unicode

➔ Unicode is the Universal character encoding system.

➔ Unicode can represent the all the characters in the written languages of the world

➔ Unicode uses more than 16 characters to represent a single character in memory.

➔ It can represent more than 216 (65536) characters.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 3

Components of the Computer System


Computer : Computer can be defined as a fast electronic device that accepts data , processes it as per stored
instructions and produce information as Output.

Data: Data denotes the raw facts and figures such as Numbers , words , amount , quantity etc.. that can be
processed as a single unit

Information: Meaningful and processed form of data is called Information

Data Processing :

Data processing refers to the operations or activities performed on data to generate information.

The six stages of data processing are:

1.Capturing data. → 2. Input of data. → 3.Storage of data. → 4. Processing of data. →5. Output of Information

→ 6.Distribution of Information.

1. Capturing Data

• It is the first stage of data processing.

• During this stage , a source document is designed to collect data in proper order and format , which is used
for data collection.

2. Input of Data

• During this stage , the input data collected through the source document is fed into the computer for
processing.

• Input data is stored.

3.Storage

• The input data before processing , The intermediate result while processing and the information after
processing are stored.

4. Process

• Here the input data is retrieved for processing.

• Various operations like calculations ,classification ,comparison ,sorting , filtering etc are carried out as part
of processing.

5. Output

• The processed data is obtained in the form of information.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• The output data is also stored .

6. Distribution of Information

• The information obtained from the output stage is distributed to the benificiaries for decision making and
problem solving.

Functional Units of a Computer

According the Von Neumann Architecture , The functional units of a computer consist of :- Input Unit ,Central
Processing Unit (CPU) ,Storage Unit and Output Unit.

The Central processing Unit consist of Control Unit , Arithmetic and logic unit (ALU) and Registers

• Input Unit :

• The collected data and instructions are entered into the computer through the input unit.

• The input data is stored.

• Functions performed by input unit are

1. Accept data and instructions from user.

2. Convert data and instructions into computer format.

3. Supply the converted data for processing.

• Central Processing Unit :

•It is the brain of computer. All major computations and calculation are made within the CPU.

•CPU is Responsible for controlling and activating all other units.

• CPU consist of ALU, Control Unit and Registers.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


➢ Arithmetic and Logic Unit (ALU) : ALU is responsible for performing arithmetic calculations and
logical operations . It communicate with the storage unit to store and retrieve data.

➢ Control unit : it is the central nervous system that control and coordinates all the operations of a
computer. It involkes all other units to perform the operations they are associated with.

➢ Registers :Registers are the temporary storage locations inside the CPU.

• Storage Unit

• The input instructions before processing , intermediate results while processing after the results after
processing are stored in the storage unit.

• The two types of storages are Primary Storage and Secondary Storage.

• Output Unit :

• The information obtained after data processing is supplied to the outside world through the output
unit.

• Functions performed by output unit are

1. Receive the output in coded form .

2. Convert the results in to human readable format.

3. Supply the result to the outside world.

Hardware
• The visible and tangible parts of a computer system that consist of some electrro mechanical component
are called Hardware.
• The physical devices that constitute a computer are collectively called Hardware.

Processor

• It is an Integrated Circuit package that contain millions of transistors and other components fabricated
into a single silicon chip.
• It co-ordinates all computing and decision making operations of a computer.
• Performance of a Processor determines the overall performance of the computer.
• Eg: Intel Core i3 , i5 ,i7 , AMD Quadcore , AMD Ryzen .

Registers

• Registers are the temporary storage locations inside the CPU to store data and instructions..
• Contents of Registers can be accessed more quickly by the CPU.
• Important Registers inside a CPU are :
▪ Accumulator – Accumulator Register is a Part of ALU and is also known as Register A . It is
used to store intermediate results of Arithmetic and logical operations.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


▪ Memory Address Register (MAR)- It stores the address of the memory location to which the
data is to be read or written by the processor.
▪ Memory Buffer Register (MBR)- It stores the data to be read or written by the processor.
▪ Instruction Register (IR) – Stores the instruction to be executed by the processor.
▪ Program Counter(PC) – Stores the address of the next instruction to be executed by the
processor.

Motherboard

Mother board is the large printed circuit board(PCB) to which major components of a computer are integrated.

Peripherals

Peripherals are devices which are attached to a computer system to improve (enhance) its capabilities. It includes
Input/output devices, Storage devices, Communication devices etc...

Ports

Ports are used to connect external devices such as to a computer. Ports on the motherboard are VGA , PS/2 ,
USB , Ethernet ,HDMI etc.

• VGA – Video graphic Array


• USB – Universal Seriel Bus
• HDMI – High Definition Multimedia Interface

Memory
Memory is a a collection of storage locations to store data and instructions temporarily or permananently.

Memory is Classified in to two:

❖ Primary Memory (Working Memory used for storing data temporarily).


❖ Secondary Memory (used for permanent storage of data for future usage).

The Measuring Units of Memory are:

Binary Digit –Bit 1 Nibble – 4 Bit 1 Byte – 8 Bits 1KB (Kilo Byte) =1024 Bytes 1MB(Mega Byte) =1024 KB

1GB (Giga Byte) = 1024 MB 1TB( Tera Byte) =1024 GB 1PB (Peta Byte) =1024 TB.

Primary memory

Primary memory is a high speed semiconductor memory that is directly accessed by the CPU. Primary memory
includes three types of memory – Random Access Memory(RAM) , Read Only Memory(ROM) and cache memory.

RAM (Random Access Memory)

• RAM refers to the main memory that processor can read from and write into.
• Data can be retrieved from any location within the RAM.
• Data or Instructions to be executed by CPU must be placed in the RAM.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• RAM is a Volatile Mobile – Contents of RAM is lost when power is switched off.
• It stores the Operating System , Application Programs and data when the computer is functioning.

ROM ( Read Only Memory)

• ROM is a permanent memory that can perform read operation only.


• ROM is a Non Volatile Memory – contents can be retained even after the power is switched off.
• It stores the program required to boot the computer initially – BIOS (Basic Input Output System).
• Different types of ROMs are:
→PROM – Programmable ROM – It can be programmed only once.
→EPROM – Erasable Programmable ROM – It can be rewritten using ultra violet radiation.
→EEPROM –Electrically Erasable Programmable ROM – It can be rewrite electrically.
• Difference Between RAM and ROM
RAM ROM
• Random Access Memory • Read Only Memory
• RAM is faster than ROM • ROM is a slower memory.
• It can perform Read and Write operations. • It can perform read operation only.
• It is a Volatile Memory- Contents are lost • It is a Non-Volatile Memory- Contents are
when device is powered off. retained when device is powered off.
• It stores the Operating System , Application • It stores the program required to boot the
Programs and data computer initially

Cache Memory
• Cache memory is a small and fast memory between the processor and RAM.
• It stores frequently accessed data , instructions , intermediate results etc..
• When processor needs data, it first searches in the cache.

Secondary or Auxilary Memory

• Secondary memory is used to store data and instructions permanently.


• It is a Non Volatile Memory.
• Secondary memory is much larger in size , but is slower memory
• Major Categories of Secondary Storage devices are: Magnetic Storage Devices , Optical Storage Devices
and Semiconductor Storage Devices.

1. Magnetic Storage Devices


• It uses plastic tape or metal disks coated with magnetic material to store data.
• Data is recorded magnetically in these devices.
• Read Write heads are used to access data.
• Eg: Hard Disk , Magnetic Tape. etc
2. Optical Storage Devices.
• It Uses low powered laser beam to read and write data.
• It consist of an aluminium foil sandwitched between two circular plates.
• Data is written as pits and lands which represents 0 and 1 when read using laser beam.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• Eg: CD,DVD,Blu-Ray
3. Semiconductor Storage Devices (Flash Memory)
• Flash Memory uses EEPROM for data storage.
• It is faster and durable type memory.
• Eg: USB flash memory and Flash Memory Cards

Memory Hierarchy : Registers →Cache → RAM → Hard Disk

INPUT / OUTPUT DEVICES

• Input / Output devices allows users to communicate with the computer


• These devices are connected to the computer through ports or wireless technologies

Input devices

• Input Devices are used to enter/feed data into the computer.

• Input devices provides communication between user and computer.

• Different Input Devices are :KEYBOARD, MOUSE,LIGHT PEN,TOUCH SCREEN,GRAPHIC TABLET,TOUCH


PAD,JOYSTICK,MICR, SCANNER,OMR,BARCODE/QR READER,BIO METRIC SENSOR,SMART CARD
READER,DIGITAL CAMERA etc

1. Keyboard

• It is the most commonly used input device.

• It allows user to input alphabets ,numbers, and other characters to the computer.

• Keyboard can be wired or wireless which can be connected to the computer through PS2/USB port or
Bluetooth,IR,Radio.

• Keyboard detects the key pressed and generates the corresponding ASCII number to store in memory.

2. Mouse
• Mouse is used to control the movements of a cursor on the computer screen.
• Mouse has one more than one buttons and a scroll wheel.
Buttons are to make selections and scroll wheel is to scrolling on the screen.
• Wired mouses are connected through PS2/USB ports and wireless mouses are connected throuhgh
Radio waves.
• Different types of Mouse are : Ball Mouse , Optical Mouse and Laser Mouses.
3. Light Pen
• Light pen is a pointing device that Helps to draw directly on the screen
• Light Pen is used to draw pictures, design objects and also put digital signatures directly on the
screen.
• Used by engineers, Fasion Designers ,Artists etc.
4. Touch Screen
• Touch screen is Operated by touching on the display screen.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• It have touch sensitive display screens.
• Used in Smart phones, Laptops, ATMs etc
5. Graphic Tablet
• It consists of an electronic writing area.
• Special pen works on it which is pressure sensitive.
• It allows artists to create graphical images with motions and actions
6. Joystick
• It is a pointing device used to select and move objects on the screen.
• Mainly used to play games, and controls robots..
• It have a vertical movable stick and control button.
7. Microphone
• It is used to input sound to the computer.
• It accept sound which is analog and convert it into digital format .
8. Scanner
• scanners are used to scan images and texts and convert into digital format.
• Quality of image depends on the resolution of scanner, which is expressed in DPI.
• Different types of scanners are- Flat bed, Sheet feed,and hand held.
9. Optical Mark Reader (OMR)
• OMR is used to scan printed forms, read predefined positions and record marks on the form.
• It is used to evaluate objective type exam papers.
10. Barcode / QR code (Quick Response) code Readers
• Barcode is a set of vertical lines of different thickness and spacing that represent a number.
• Barcode readers are devices that are used to input data from barcodes.
• QR codes are two dimensional lines of different thickness and spaces.
• QR code reader is used to input data from QR codes.
• Bar codes are single dimensional where QR Codes are two dimensional.
11. MICR – Magnetic Ink Character Recognition
• MICR is used to read the characters printed using iron oxide particles below the cheques, drafts etc
• MICR is used to read MICR code that contains cheque number, branch code, bank codes etc..
12. Biometric Sensors
• Biometric sensor is a device that can identify unique human features such as fingerprints,retina ,
iris patterns ..
• It is used to verify and authenticate the identity of humans.
13. Smart Card Reader
• Smart card is a plastic card that contain memory or microprocessor which can store and transact
data.
• The smart card is used in banking, health care, telephone calling etc.
• Smart card reader is used to read data from smart cards.
14. Digital camera
• A digital camera can take pictures and videos and convert them into digital format.
• It have the facility to store captured images / videos.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Output Devices
Output devices are used to present some data from the computer to the users in human readable form.

Commonly used Output Devices are : Visual Display Unit, LCD Projector,Printer,Plotter, 3D Printer ,Audio Devices.

→ Visual Display Unit.(VDU)

▪ VDU is used to display the Information generated by the computer in pictorial form.
▪ Information displayed on Display devices are called Soft Copy.
▪ Size of monitor is measured diagonally across the screen.

→LCD Projector

▪ LCD projector is a type of Video projector that is used to display images, video or computer data on a large
screen.
▪ It uses a lens to focus the high intensity beam of light from the projector to a screen.

→Printers

▪ Printers are used to produce hard copy outputs on papers.


▪ Output printed on paper is called hard Copy.
▪ Printers classified to Impact Printers and NonImpact printers.
▪ Speed of printer is measured in number of characters printed in unit time. It is measured as cps(character
per second) , lpm (lines per minute) , ppm (pages per minute).
▪ Different types of printers are :
➢ Dot Matrix Printers
▪ It is an impact type printer.
▪ Dot Matrix printers are Slow and Noisy.
▪ The quality of print is poor.
▪ Printer is expensive , but cost of printing is very less.
➢ Inkjet Printers
▪ It is a non-impact type printer -There is no physical contact between print head and paper.
▪ Printing is done by spraying ink to the paper through a nozzle
▪ High quality printing and high printing cost.
➢ Laser Printers
▪ Non impact type printer.
▪ It uses ink powder for printing.
▪ Printing speed is high and Produce High quality printing.
▪ It can print 20 pages per minute.
➢ Thermal printer.
▪ It is a non impact type printer.
▪ Thermal paper is selectively heated when it is passed through a print head.
▪ The heated area turns black.
▪ Thermal printers are Portable , lighter, Quit and faster.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


→Plotter

• Plotter is used to print Hard copies of large format graphs ,maps , drawings , designs etc.
• Plotter can be Drum plotters or flatbed plotter.

→3D Printer

• It is an output device used to print 3D objects.


• It can produce different objects using different materials using the same printer.
• It It split the object into small slices and print from bottom to top .Then these slices are sticked together to
form the Object.

→Audio Output device

• Audio output devices are used to produce sound.


• Speakers are the output device that produce sound.
• Speakers are connected to the computer through audio port or through some wireless technology
(Bluetooth).

e-waste
• E-waste refers to the Electronic products nearing the end of their ‘useful life’.
• The e-waste includes discarded Televisions , Computers, Laptops , DVD players , Fax machines etc
• It is estimated that 50 million tons of e-Waste are produced each year

Why should we be concerned about e-Waste?

• It contains some very toxic substances, such as mercury, lead, cadmium, brominated flame retardants,
etc.
• The toxic materials can cause cancer, reproductive disorders and many other health problems, if not
properly managed.

E-Waste Disposal Methods

The e-waste disposal methods are: 1.ReUse 2.Incineration 3.Recycling of E-waste 4.Land filling

→ReUse

• It is the Second-hand use of electronic products or usage after it has been upgraded or modified.
• Old computers are passed on to relatives/friends or returned to retailers for exchange or for money.
• Computers can be passed to charitable institution or educational institutions.
• This method reduces the volume of e-Waste generation.

→Incineration

• It is a controlled and complete burning process.


KALLADI HSS NOTES BY MUSTHAFA 9544885401
• The waste is burned in specifically designed incinerators at a high temperature in the range of 900 to 1000
degree celsius.

→ Recycling of E-waste

• It is the process of making or manufacturing new products from a product that has originally served its
purpose.
• Monitors, Keyboards, Laptops, Modems, Telephone boards, Hard drives, Compact disc, Mobiles, Fax
machines, Printers, CPU, Memory Chips, Connective wires and cables can be recycled.

→ Land filling

• It is one of the widely used but not recommended method for the disposal of e-Waste.
• It is the process of dumping the e-waste in to the soil.

Role of students in e-Waste disposal

• Stop buying unnecessary electronic equipments.


• When electronic equipments get faulty try to repair it instead of buying a new one.
• Try to recycle electronic equipments by selling them or donating them to others
• If you really need to buy new electronics, choose items with less hazardous substances, greater recycled
content, higher energy efficiency, longer life span etc.
• Buy rechargeable batteries instead of disposable batteries.
• Buy products with good warranty and take back policies.

GREEN COMPUTING or GREEN IT

• The environmentally responsible and eco-friendly use of computer and their resources are called Green
computing.
• It is the designing , manufacturing, using and disposing of computers and associated components such as
monitors, printers, storage devices, etc., efficiently and effectively with minimal or no impact on the
environment.

How to make computers Green ?

To promote green computing the following four complementary approaches are employed.

1. Green Design- Design energy efficient and eco friendly devices.


2. Green Manufacturing- Minimize waste during the manufacturing process.
3. Green Use- Minimise power consumption during usage.
4. Green disposal – Re-use or Recycle

Some steps that can be taken for Green Computing / IT

• Turn off computer when not in use.


• Power-on the peripherals such as laser printers only when needed.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• Use power saver mode.
• Use laptop computers rather than desktop computers whenever possible.
• Take printouts only if necessary.
• Use LCD monitors rather than CRT monitors.
• Use H/W & S/W with Energy Star label.
• Dispose e-Waste according to central, state & local regulations.
• Employ alternative energy sources like solar energy.

Energy star

The labelling programme to promote energy efficiency in computers and their resources is called Energy star.

Software

• It is a set of instructions that enables the user to interact with a computer and perform operations.
• Software is a set of instructions/program to perform a specific task
• Softwares are classified in to two.
1) System Software
2) Application Software.

System Software

• System software is a set of programs designed to control the operations of a computer.


• It help ordinary users to make use of computer effectively and efficiently.
It is also known as system package.
• System Software are classified in to three.
1) Operating System
2) Language Processors.
3) Utilities.

Operating System

• It acts as an interface between the user and the hardware.

• It is a set of programs that control and co-ordinate the operations of a computer.

• It provides an environment to execute programs.

• OS is the most important software in the computer system.

• Example: MS Windows XP, Vista, Linux, DOS.

Functions of Operating System

KALLADI HSS NOTES BY MUSTHAFA 9544885401


•Process management -Resposible for allocating and deallocating resources to processes.

•Memory management- Keep track of free allocated memory locations.

•File management- Responsible for file related activities.

•Device Management- Responsible for managing the devices attached to the computer.

Computer Languages
• Low Level Language(LLL)

• Machine Language: It uses the binary digits 0 and 1 to write a program.It is the Only Language that
machines can understand.

• Assembly Langauge :It uses mnemonics codes like ADD,SUB,INC,etc to write a program. Mnemonics are
the symbolic name assigned to operations.

eg: ADD A,B.

• High Level Language(HLL) : HLL uses english language lijke words to write programs .

.eg if a>b print “a is big”.

Language processors

• Language processors are the programs that translate programs written in Assembly language or High
level language into its equivalent version in Machine language.
• They are classified in to three.

They are: Assembler , Compiler , Interpreter.

1. Assembler : Assembler is a program that converts programs written in assembly language into machine
language instructions

2. Interpreter: Interpreter is a program that converts programs written in High Level language into its
equivalent instructions in machine language , line by line.

3. Compiler: Compiler is a program that converts programs written in High Level language into machine
language instructions.

• Compiler converts the whole program in a single run.


• The Languages like C++ , java uses compiler.

Difference Between Compiler and Interpreter

Compiler Interpreter

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• It translate the whole program in a single run. • It translate the program line by line ; ie, It
execute a single statement at a time.
• Erros are listed only after the compilation. • Errors are listed in each line.
• Compiler Generates Object Code • Interpreter does not produce Object Code.

Utility Software

• Utilities are the set of programs for performing system maintanance tasks and for performing tasks of
routine nature.

• They are used to Analyze,Optimize and maintain the computer system.

• Utility softwares are:

1. Backup Utility. 2.Compression Tools. 3.Disk Defragmenter 4.Antivirus software etc.

1. Backup Utility : - Backup means duplicating the disk information and store it else where , so that it can be
used to restore the original after a data loss.

Eg : BackupPC, Barcula etc

2. Compression Tools: - Compression tools are used to compress and decompress data files.

• Compression of files is known as Zipping.

• Decompression of files is known as UnZipping.

• Eg : WinZip ,WinRAR, Zip Archiever.

3. Disk Defragmenter : Disk defragmenter is a program that is used to arrange the files on the Hard disk.

4. Antivirus software – Antivirus softwares are used to scan the computer for known viruses and removes
them.

Eg : AVG , Norton , Kasperskey ,McAfee etc..

Application Software
• Software developed for a specific application is called Application is called Application Software.

• Application software is a set of programs designed to solve a specified problem, or it is developed


according to the requirement of an individual or an organization.

• Application softwares are classified in to.

1) General Purpose Software Packages.

2) Specific Purpose Software

1. General Purpose Software packages

• General Purpose Softwares are used to perform tasks in a particular application area.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• Such softwares are developed according to the requirements of the expected users.

• General purpose Softwares are:

1.Word processors 2. Spreadsheet Software. 3.Presentation Software. 4.Multimedia Software

5.Database Software.

• Word processors : Word processing softwares are designed to create , modify and edit text documents.

Eg: Microsoft word , Open Office Writer , Apple iWork etc.

• Spreadsheet Software: Spreadsheet sofware allows users to store and organize data in tabular form and
to perform calculations.

Eg: Microsoft Excel , Open Office Calc , Apple iWork Numbers.

• Presentation Software: Presentation Softwares are used to display information in the form of slide show.

Eg:MS PowerPoint ,Open Office Impress, Apple iWork KeyNote.

• Multimedia Software:Multimedia softwares includes the softwares to play and edit Audio , Video ,Image
files.

Eg : VLC Player , Real Player , MX Player etc

• Database Software: Database is an organised collection of inter related data. Database Software is used to
create and manage databases.

Eg: MS Access , Oracle , MySQL etc..

2. Specific Purpose Software

• Specific purpose softwares are developed according to the requirements of an Organization or individuals.

• These are tailor made softwares designed to handle particular tasks.

• Example: Pay roll System , Air line reservation System , sales and inventory control System, Hospital
management System, Library management System, Supermarket management System etc…

Free and Open Source software

• Free and Open Source software provides freedom to Use ,Copy,Distribute,Examine ,Change and Improve
the software.

• The four freedoms for free and open source software are:

Freedom 0: Run Program for any purpose.

Freedom 1: Access to source code to study and adapt.

Freedom 2:Distribute copies.

Freedom 3:Improve and release versions.

• Example for Free and open source software

KALLADI HSS NOTES BY MUSTHAFA 9544885401


1. GNU/Linux :- Free and open source Operating System.

2. GIMP(GNU Image Manipulation Program) :- Free and open source image editing sofware.

3. Mozilla Firefox:- Free and open source web browser.

4. OpenOffice.org:- Free and open source office suite.

Freeware and Shareware


Freeware Shareware
• Software that anyone can download • Software that provide a chance to try
from the internet and use for free it before the purchase.
• All the features are available • All the features are not available
• It can be distributed free of cost. • It may or may not be distributed free
of cost.

Proprietary Softwares

• Softwares that are exclusive property of its developer ,which cannot be used,copied or distributed
without licensing agreements.

• Eg: Windows OS,MS Office,Adobe Photoshop etc

Humanware/Liveware

• Humanware is the term used to refer the humans who use computer system.
• Eg: Computer System Administrators, System Manager ,Database administrators, Computer
Engineers, Computer Operators , System Analyst

4.Principles of Programming and Problem Solving


Phases of Programming / Steps in Programming / Stages of Programming
Different phases of Programming are:
1. Problem Identification.
2. Preparing Algorithm and Flow chart.
3. Coding the Program.
4. Translation.
5. Debugging.
6. Execution and Testing.
7. Documentation.
1. Problem Identification.
• It is the first phase of programming.
• It is the stage of analysing the programming.
• During this stage , we have to identify:
→Datas involved in programming.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


→Type and Quantity of data.
→Formulas to be used.
→Activities Involved in processing.
→Expected Output.
2. Preparing Algorithm and Flow Chart
Algorithm: Step by step procedure to solve a problem or sequence of instructions to solve a problem is
called Algorithm.
FlowChart: Pictorial Representation of Algorithm is known as Flow chart.
3. Coding the Program
Writing the Instructions to solve the problem in a programming language is called Coding the program.
Source Code: Program code written in any High Level Language(HLL) is called Source Code.
4. Translation
The process of Converting the program written in any High Level Language into machine language is called
Translation.
Object Code: The Source code after Translation is called Object code.
Bugs: Errors in a program are called Bugs.
5. DeBugging
The process of detecting and correcting errors in a program is called Debugging.
6. Execution and Testing
Running the program to obtain the output is called Program Execution .
Testing is to check whether the obtained output is as Expected.
7. Documentation
Documentation is the information that describes the source code or the information that describes the
functionalities of the Software product.
two Types of Documentation are: Internal Documentation and External Documentation.
1. Internal Documentation : Writing comments within the source code as part of documentation
is called Internal Documentation.
2. External Documentation: The hard copy documentation that describes the features and
functionalities of the software product is called External Documentation.

Types of Errors in Programming


Three types of errors in programming are : 1. Syntax error 2.Logical Error 3.run Time error.

1. Syntax Errors : Syntax error occurs when the Rules or Syntax of a programming language are not followed.
Eg: Semi column ( ; ) missing in a statement.
2. Logical Error : Logical error occurs due to the incorrect logic used in the program.
Computer produces output as per the instruction given by the user . But the obtained output will be
incorrect . This type of errors are known as Logical error.
Eg: Use + symbol for Multiplication instead of *.
3. Run time Errors: Run time error occurs due the inappropriate input given by the user given by the user
during the run time. Eg: Dividing by Zero error.

Algorithm
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Step by procedure to solve a problem is called Agorithm.

Characteristics of Algorithm

1. An Algorithm should start with the instruction to accept Input.


2. Use Variables to refer input data.
3. Each instruction must be clear and Precise.
4. Each instruction must be completable in a finite time.
5. Expected output must be Obtained.

Types of Instructions in an Algorithm

• Use the words Input/Accept/ Read for Input instructions.


• Use the words Print/Display/Write for Output Instructions.
• Use = symbol to store a value in a variable.
• Use the words IF..THEN…ELSE for decision making statements.
• Use the words REPEAT..WHILE for repeating set of instructions.

Flow Chart

Pictorial representation of Algorithm is called Flow Chart.

Flow Chart Symbols

1. Terminal :
It is used to represent start and stop instructions. Its Symbol is Ellipse
2. Input /Output
It is used to represent input instructions and Output Instructions. Its symbol is Parallelogram.
3. Process
It is used to represent Assignment Instructions (=). Its symbol is Rectangle.
4. Decision
Decision is used to represent decision making instructions. Its symbol is Rhombus.
5. Flow Lines
Flow lines are used to represent flow of instructions . Its symbols are arrows with heads.
6. Connectors
Connectors are used to represent a single flow chart that spread on multiple pages.

Advantages of Flow Chart

1. Better for communication


2. Effective Analysis
3. Effective Synthesis
4. Efficient Coding.

DisAdvantages of Flow Chart

1. Flow chart is Time Consuming.


KALLADI HSS NOTES BY MUSTHAFA 9544885401
2. Modification within a flow chart is not easy.
3. Lack of standards regarding the content within a flow chart.

Performance Evaluation of Algorithm

• The performance of an algorithm is evaluated based on the concept of Time Complexity and Space
complexity.
• An algorithm which will be executed faster by using minimum memory space is considered as the efficient
algorithm.

Approaches in Problem solving


The two approaches to problem solving are:

1. Top Down Design approach : Here a large problem is divided into smaller sub problems. And some of the
sub problems are further sub divided. Then each sub problems are solved separately.
2. Bottom Up design approach: Here a large problem is divided into smaller sub problems. And each sub
problems are further sub divided until the lowest module . The problem is solved by integrating the
solutions to individual sub problems.

Advantages to problem Solving by Decomposition

• It helps to understand each part of the problem.


• Reduces the complexity of the Problem.
• ReUsability.
• More than one people to work on the problem at the same time.

Write the algorithm and Draw the flow chart to :


1. Write the algorithm and Draw the flow chart To add 2 numbers. (Sum of 2 Numbers)
2. Write the algorithm and Draw the flow chart To multiply 2 Numbers (Product of 2 Numbers).
3. Write the algorithm and Draw the flow chart To find sum and Product of 3 Numbers.
4. Write the algorithm and Draw the flow chart To find Sum and Average of 3 Numbers.
5. Write the algorithm and Draw the flow chart To find Area and perimeter of a rectangle.?
6. Write the algorithm and Draw the flow chart to find the area and perimeter of a square.?
7. Write the algorithm and Draw the flow chart to find the area and perimeter of a Circle.?
8. Write the algorithm and Draw the flow chart to calculate Simple Interest.?
KALLADI HSS NOTES BY MUSTHAFA 9544885401
9. Write the algorithm and Draw the flow chart to find the largest of 2 Numbners.?
10. Write the algorithm and Draw the flow chart to check the given number is even or odd.?
11. Write the algorithm and Draw the flow chart to check a student is passed or failed.?
12. Write the algorithm and Draw the flow chart to find the Largest of 3 Numbers.?
13. Write the algorithm and Draw the flow chart to check the given number is positive , Negative or
Zero.?
14. Write the algorithm and Draw the flow chart to print the day of a week corresponding the number
between 1-7.?
15. Write the algorithm and Draw the flow chart to print the given character is a vowel or not.?
16. Write the algorithm and Draw the flow chart to print the month of a year corresponding the
number between 1-12.?
17. Write the algorithm and Draw the flow chart to print the Natural Numbers upto 100.?
18. Write the algorithm and Draw the flow chart to print the Natural numbers upto a limit.?
19. Write the algorithm and Draw the flow chart to print the Even natural numbers upto 100.?
20. Write the algorithm and Draw the flow chart to print the Odd natural numbers upto a limit.?
21. Write the algorithm and Draw the flow chart to print 10 multiples of a Number.?
22. Write the algorithm and Draw the flow chart to print the Sum of Natural Numbers upto 100.
23. Write the algorithm and Draw the flow chart to print the Sum of Natural Numbers upto a limit.
24. Write the algorithm and Draw the flow chart to print the sum of even numbers upto a limit.?
25. Write the algorithm and Draw the flow chart to print the Factorial of a Number.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 5

Introduction to C++ Programming


Character Set

The set of valid characters that a language processor can recognize are called Character set. The c++ character set
is categorized into five:Letters,Digits,Special Characters,White spaces and All the 256 ASCII characters.

Tokens

Tokens are the fundamental building blocks of a program.They are also known as Lexical Units. The 5 types of
tokens in c++ are :

1. Keywords 2.Identifiers 3.Literals 4.Operators 5.Punctuators

(We can remember these 5 tokens using the keywords “P O L I K” or “K I L O P”)

Keywords

Keywords are the Reserved words that convey a specific meaning to the language compiler. Keywords should be
in lower case characters. Keywords in c++ are:

asm,auto,break,case,catch,char,class,const,continue,default,delete,do,double,extern,enum,else,float,for,friend,got
o,if,inline,int,long,new,operator,public,protected,private,register,return,short,signed,sizeof,static,struct,switch,tem
plate,this,throw,try,typedef,throw,union,unsigned,virtual,void,volatile,while.

Identifiers

The user defined names that are used to name different program elements such as memory locations ,statements
,functions ,class ,objects are called Identifiers.

• Identifiers assigned to memory locations are called Varibles.

• Identifiers assigned to statementrs are calle Labels.

• Identifiers assigned to a group of statements are called Function Names.

Rules for creating and validating Identifiers:

1. Identifier should contain only Letters(A-Z,a-z), Digits(0-9) ,and underscores(_).

2. Identifier should start with Letter or Underscore(_).

3. White spaces and special characters are not allowed.

4. Keywords cannot be used as Identifiers.

5. Uppercase and lowercase characters are treated differently.(c++ is case sensitive).

Example for Valid characters: Sum , Average_Height , kallan675 , _asdf ,FOR….

Example for Invalid Identifiers:

• Sum of Numbers –White spaces are not allowed.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• 7sum – Cannot start with numbers.

• for - keywords cannot be used as identifiers.

• Sum-of-Numbers - special characters are not allowed.

Literals / Constants

Tokens to represent data items that never change their value during the execution of the program(program run)
are called Literals/ Constants. Four types of Literals are:

1. Integer Literals.

2. Floating point Literals /Real Constants.

3. Character Literals.

4. String Literals.

Integer Literals

The whole numbers without decimal part that never change their value during the execution of the program are
called integer literals.

Characteristics / Rules for Integer Literals

1) Integer literals must have one digit and must not contain any decimal point.

2) The first character may be ‘+’ or ‘-‘ sign ; where + indicates positive number and – indicates negative
number.

3) Numbers without sign are treated as Positive.

4) No other characters are allowed.

Eg: 3453, -675 , +987 are Integer literals.

Floating Point Literals / Real Constants

The numbers having fractional part that never change their value during the program run are called Floating point
Literals or Real constants.

Floating point literals can be represented in two forms – Fractional form and Exponential form.

Floating point literals in Fractional Form :- It consist of signed or unsigned digits with a decimal point between
the digits. The rules for writing / characteristics of Real constants in fractional form are :

1. It must have a digit and a decimal point.

2. The first character may be ‘+’ or ‘-‘ sign ; where + indicates positive number and – indicates negative
number.

3. Numbers without sign are treated as Positive.

Floating point Literals in Exponential form :- It consist of Two parts. Exponent and mantissa.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


For eg: 31.4 can be written as 0.314*10^2 or 0.314E2 or 0.314e2.

The rules for writing / characteristics of Real constants in Exponential form are:

1. The floating point literal in exponential form have two parts – Exponent and mantissa.

2. Mantissa can be any integer of fractional number.

3. The mantissa is followed by ‘E’ or ‘e’ and Exponent.

4. Exponent must be an Integer.

Examples for Real constants/Floating point Literals :

3.14 , -345.678 , 0.98e3 ,7.89E-2

Character Literals

A single character enclosed in single quote that never changes its value during the program run are called
Character literals.

Eg: ‘a’ , ‘3’ , ‘K’ , ‘&’ .

Escape Sequences

Escape sequences are used to represent some non-graphic character constants which cannot be typed directly
from the keyboard. It consist of a black slash followed by one or more characters. Escape sequences are listed in
the following table:

Escape Character Constant Escape Character Constant


Sequence Sequence
\t Tab Space \’ Single Quote
\n New line \” Double Quote
\b Back Space \? Question Mark
\\ Back Slash \0 Null Character

String Literals

A sequence of one or more characters enclosed within a pair of double quotes is called String Literals.

Eg: “welcome” , “56” , “h76” , “(tyn)”.

Operators

The symbols that tells the compiler to perform some operation are called Operators. The participants in an
operation are called Operands.

Example for Operators :

• Arithmetic operator : +, - ,* , / ,%

• Relational Operators : < , > ,<= ,>=, == ,!=

• Logical Operators : && , || ,!

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Punctuators

Punctuators are Special symbols that have syntactic and semantic meaning to the compiler. Punctuators in c++ are

# ; ‘ ‘’ ( ) { } [ ].

Integrated Development Enviornment ( IDE )

IDE are used to develop programs . IDEs provide facilities to Type , Edit , Compile , Link and Execute c++ programs.

GCC (GNU compiler collection) ,Borland C++ , Turbo C++ are examples.

GCC (GNU Compiler Collection) with Geany Compiler

GCC compiler is a free software available with Linux Operating System. Geany is a platform independent IDE for
writing , compiling and Executing c++ programs.

The steps to create and Execute a C++ program in Geany are

• Opening Geany : Applications → Programming → Geany.

• Creating an new File : File → New or Press ‘Cntrl+N’.

• Saving a File : File → Save or press ‘Cntr + S’ →Give file name with .cpp extension.

• Compiling the program : Compile → Compile or Press F8.

• Linking the program : Compile → Build or Press F9.

• Executing the program : Compile → Execute or Press F5.

• Closing Geany : File → Quit or Press ‘Cntrl + Q’ .

Previous Questions
1. Classify the following into different Tokens:

Cout<<”The missile Man”;

Ans : cout - Identifier << - Operator “, ; - Punctuators. “The missile Man” – Literal

2. Identify whether the following are Valid or Invalid Identifier:

Break Number1 Simple.Interest 1stYear Summer

Ans : Break – Invalid Identifier (It is a keyword).

Number1 - Valid

Simple.Interest – Invalid ( Special characters are not allowed).

1stYear - Invalid ( Cannot start with Number)

Summer – Valid.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


3. Categorize the following into different Tokens:

Sum , 5 ,”welcome” , do , # , + , while , Digi , % .

Keywords Identifiers Literals Operators Punctuators

do Sum 5 + #

while Digi “welcome” %

KALLADI HSS NOTES BY MUSTHAFA 9544885401


CHAPTER 6

DATA TYPES AND OPERATORS


Data Types
• Data Types are the means to identify the nature of the data and the set of operations that can be
performed on the data.

• C++ Data types are classified into – Fundamental DataTypes , Derived data Types and User
defined Data Types.

User Defined Data Types


The data types that are defined by the programmer to use in his own program is called User Defined
DataType.
Eg: Structure , Enumeration , Class etc..

Derived Data Types


The Data Types that are constructed using Fundamental Data Types through some grouping or
alteration is size are called Derived Data Types.
Eg: Functions , Arrays etc.

Fundamental Data Types / Primitive data Types / Basic Data Types /Built-In Data
Types
Fundamental data types are the Built-in data types that defined in the c++ compiler. The fundamental
data types in c++ are int , char , float , double and void.
1. int Data type

• int data type is used to represent Integer Numbers.

• Integer numbers are the whole numbers without fractional part.

• ‘int’ keyword is used to represent integer numbers.

• The size of int data type is bytes.

• Range of values that int data type can represent is from -2147483648 to 2147483647.

• 256 , -2548 ,0 , 450000 are example for int type data items.
2. char data type

• char data type is used to represent characters defined in the c++ character set.

• It includes Letters , Digits , Symbols etc.

• ‘char’ keyword is used to represent char data type.

• The size of char data type is 1 one byte.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• The range of char data type is from -128 to 127.

• ’s’,’3’ , ‘+’ are examples for char data type.


3. Float Data type.

• Float data type is used to represent floating point numbers.

• Floating point numbers are the numbers having fractional part.

• ‘float’ keyword is used to represent floating point numbers.

• The size of float data type is 4 bytes.

• It support precision upto digits.

• 77.125 , -25.00 , 0.142 belongs to float data type.


4. Double Data type

• Double data type is used to represent double precision floating point numbers.

• It supports precision upto 15 digits.

• ‘double’ keyword is used to represent double data type.

• The size of double data type is 8 bytes.


5. void Data type

• void is a keyword to represent null or empty set of values.

• It does not require any memory space.

Type Modifiers
Type modifiers or Data Type Modifiers are used to alter the Size , Range or Precision of Fundamental
Data types. The Type modifiers are signed , unsigned , long and short.
Eg:

• Size of ‘int‘ data type is 4 Bytes . When it becomes ‘ short int’ size becomes 2 bytes.

• Range of int is from -2147483648 to 2147483647 . When it becomes ‘unsigned int’ , the
range becomes 0 to 4294967295.
Variables

• Variables are the names given to memory locations.

• These names are used to refer the memory location to store and access the data.

• The three aspects associated Variables are – Variable name , Memory Address and Content.

• Variable name – It is the symbolic name assigned to memory locations.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• Content – The value stored in the memory location is called content of the variable. It is also
called R-Value of a variable.

• Memory Address – The address of a variable is the starting address of the allocated memory
space.It is also called L-value of a variable.
Operators

• Operators are the predefined symbols that trigger(tell) the computer to perform some operation.

• The participants in an operation are called Operands.

• Based on the Number of operands in operation, operators are classified into – Unary , Binary
and Ternary.

• Unary operator – An operator that operates on a single operand is called Unary operator.
Eg : unary + , unary – , Increment operator (++) , Decrement operator (- -) etc.

• Binary operator - An operator that operates on two operands is called Binary operator.
Eg: Arithmetic operators (+,-,*,/ ,%) , Relational operators (<,<= ,>,>=, ==,!=) etc…

• Ternary operator - An operator that operates on three operands is called Ternary operator.
Eg :Conditional operator(? : ).
Classification of Operators
Based on the nature of operation , operators are classified into :
1. Arithmetic Numbers- + , - , * , / and %.
2. Relational Operators.- <, > , <= , >= , == ,!=
3. Logical Operators- && , || ,!
4. Assignment operator.- =
5. Arithmetic Assignment Operator- += , -= , *= , / = and %=.
6. Input / Output Operator.-<< , >>
7. Increment and Decrement Operator. ++ , --
8. Conditional Operator.- ? :
9. Sizeof Operator
Arithmetic Operators
Arithmetic operators are used to perform basic arithmetic operations such as Addition , Substraction ,
Division , Multiplication , and Modulus . Arithmetic operators are + , - , * , / and %.
Eg : x=10 , y=5.
Operator Operation Result

KALLADI HSS NOTES BY MUSTHAFA 9544885401


+ x+y 15

- x-y 5

* X*y 50

/ x/y 2

% X%y 0

Modulus Operator (%)


Modulus/ mod operator returns remainder of an arithmetic division. The sign of the result is the sign of
first operand .
Eg:
1) 10%3 =1 ( Remainder of 10/3)
2) 15%6 =3
3) 3%12 =3
4) -3%5 = -3 (sign of result is sign of first operand).
Relational Operators
Relational operators are used for comparing two numeric data and produce either ‘True’ or ‘False’ as
result.
Eg : x=10 , y=5
Operator Meaning Operation Result

< Less than X<Y False

<= Less than or Equal to X<=Y False

> Greater than X>Y True

>= Greater than or Equal to X>=Y True

== Equal to X==Y False

!= Not equal To X!=Y True

Logical Operators
Logical operators are used to combine two relational expressions and to compare them. Logical
operators produce either True or false as Result. The Logical Operators are &&(Logical AND ) , ||
(Logical OR) , ! (Logical NOT).

• && (Logical AND)


It compare two relational expressions and produce result as True (1) if and only if both the expressions
are true.It produce result as False(0) if any of the expression is false.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Expression1 Expression 2 Result

False False False

True False False

False True False Eg : x=10 , y-20

True True True (x<y) && (x!=y) → Tue


(x<y) && (x==y) →False

• || (Logical OR)

• || (Logical OR)
It compare two relational expressions and produce result as True (1) if any one of the expression is true
.It produce result as False(0) if both the expressions are false.

Expression1 Expression2 Result

False False False Eg : x=10 , y-20

True False True (x>y) || (x!=y) → Tue

False True True (x<y) && (x!=y) → True.

True True True


• ! (Logical NOT)
It is an unary operation that is used to negate the result of a relational expression. It produce result as
True (1) if the expression is False and viceversa.
Expression Result

True False

False True

Eg: x=10;
! (x>20) → True
Assignment Operator
Assignment Operator is used to assign a value to a variable.The Assignment operator is ‘=’. It is a binary
operator in which the first operand musrt be a Vriable . The second operand can be variable or any
constant.
Synatx: Variable = Value; eg: n=3;
Variable1 = Variable2 eg: x=n;
Arithmetic Assignment Operator
Arithmetic Assignment operator performs an arithmetic operation and assign the result to the first
operand. The Arithmetic assignment operators are += , -= , *= , /= , %= .

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Eg : x=10 , y=5
Operator Operation Meaning Result (value of x)

+= x+=y X=x+y X=15

-= x-=y X=x-y X=5

*= X*=y X=x*y X=50

/= x/=y x=x/y X=2

%= X%=y X=x%y X=0

Difference between ‘=’ and ‘==’


= ==

• It is an Assignment operator • It is a Relational Operator

• It is used to store a value in a • It is used for equality checking


variable

• a=3 → stores the value 3 in the • a==3 → Check whether the value
variable a stored in a is 3 or not.

Input / Output Operators


The Input operator is used to accept data through keyboard and store it in memory. The Input Operator
is << . It is also known as Extraction operator or get from operator.
The Output operator is used to transfer some data from the main memory to an output device. The
output operator is >> .It is also known as put to operator or insertion operator.
Increment / Decrement Operator
Increment Operator(++)
Increment operator ++ is used to increment content of an integer variable by one. Increment operator
can be written in two methods – pre increment (++x) and post increment (x++).
Prefix Increment method (++x)

• The operator is placed before the operand.

• The value of operand is incremented by one and the incremented value is used.

• Change then use method.


Eg : x=10;
Y= ++x; [ y becomes 11].

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Postfix Increment method (x++)

• The operator is placed after the operand.

• The current value of operand is used and then the value is incremented by one.

• Use then Change method.


Eg : x=10;
Y= x++; [ y becomes 10].
Decrement Operator(--)
Decrement operator -- is used to decrement the content of an integer variable by one. decrement
operator can be written in two methods – prefix method (--x) and postfix method (x--).
Prefix decrement method (--x)

• The operator is placed before the operand.

• The value of operand is decremented by one and the decremented value is used.

• Change then use method.


Eg : x=10;
Y= --x; [ y becomes 9].
Postfix Increment method (x--)

• The operator is placed after the operand.

• The current value of operand is used and then the value is decremented by one.

• Use then Change method.


Eg : x=10;
Y= x--; [ y becomes 10].
Conditional Operator ( ? : )

• It is a ternary operator that operates on three operands.

• The first operand will be a test expression and the remaining can be values or expressions.

• If the test expression is true the second operand will be selected and the third operand will be
selected if the test expression is false.
Syntax :- Expression1 ? Expression2 : Expression3 ;
Eg: 1) (mark>30) ? cout<<”passed” : cout<<“Failed”; or cout<<(mark>30) ? ”passed” :
“Failed”;
or x= ( mark>30) ? ”passed” : “Failed”;
2) (numbe%2==0) ? “Even” : “Odd” ;

KALLADI HSS NOTES BY MUSTHAFA 9544885401


sizeof operator

• It is an unary operator.

• Sizeof operator returns the amount of allocated memory space for the operand in bytes.

• Syntax:
✓ sizeof (datatype); eg: sizeof(int); → returns 4.
✓ Sizeof variableName; eg : char x;
sizeof x ; → returns 1.
✓ sizeof constant ; eg: sizeof 3.5; →returns 8 , since floating point values are treated
as double data type.

Precedence of Operators
Precedence of operators refers to the priority of operators for execution in an operation.
Priority Operators

1 Parenthesis ()

2 Unary operators ++ , -- , ! , Unary+ , Unary- , sizeof

3 Binary Operators

Arithmetic ioperators *, / , %, + , -

Relational Operators < , <= , > , >= , ==, !=

Logical operators && , ||

4 Conditional operator ?:

5 Assignment Operators =, *=, /= , %=, += , -=

6 Comma ,

Eg : 7+8-3*8
7+8-3*8 → 7 + 8 – 24 → 7 + 8 – 24 → 15-24 → -9.

Expressions
• An Expression is the combination of operators and operands.

• On the basis of type of operators used , expressions are classified into


8. Arithmetic expressions 2. Relational Expressions 3.Logical Expressions
KALLADI HSS NOTES BY MUSTHAFA 9544885401
1. Arithmetic Expressions

• An expression in which only Arithmetic operators are used is called Arithmetic Expression .

• The operands and result will be numeric value.

• Arithmetic Expressions are classified into :


→Integer Expressions →Floating Point Expressions →Constant Expressions.
→Integer Expressions
An arithmetic expression which contains only integer operands are called Integer Expression. The result
will also will be an Integer value.
Eg : int x=10 , y=20;
1) X+Y;
2) X-Y+10;
3) –X * 5;

→Floating Point Expressions ( Real Expressions )


An arithmetic expression which contains only floating point operands are called Floating point
expressions. The result will also will be a float value.
Eg : float x=10.5 , y=20.0 ;
1) X+Y;
2) X-Y+5.8;
3) –X * 3.14;
→Constant Expression
An arithmetic expression that conatins only constant values are called Constant Expression.
Eg : 8+6;
1 +6+9/2.0 ;
2.Relational expression

• An expression that contains any Relational operators is called Relational Expression.

• It Produce either True(1) or False(0) as Result.

• Eg : 1). (x>y) 2).(x==y) 3). X*y == y+20.


3.Logical Expression

• An Expression that contains any one of the Logical operator is called Logical Expression.

• It combines two or more relational expressions and produce either True or false as result.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• Eg:
1) (x > y) && (y!=20)
2) ! (x==0)

Statements
• Statements are the smallest executable unit of a programming language.

• Every statement end with ‘ ; ‘ . ; is the delimitter of a statement.

• Four types of statements are :


→Declaration Statements. →Assignment Statements. →Input Statements →Output Statements.
→Declaration Statements

• Declaration statements are used to declare variables.

• Every variable should be declared before it is used.

• Syntax of variable declaration is :


Datatype Variable1 , variable2 , variable 3……..variableN;

• Eg : int x; → Declaration of a single variable.


Int x,y,z; → Declaration of multiple Variables.
→Assignment Statemnent

• Assignment statement is used to assign a value to a variable using an assignment


operator(=).

• In an Assignment statement LHS must be a variable.

• Synatx :
1) Variable = Constant ; Eg : x=10;
2) Variable1= Variable2; Eg : y=x;
3) Variable =Expression ; Eg : z= x + y;
4) Variable = Function(); eg : x= sqrt (25);
→Input Statement

• Input statement is used to store data in memory during the program execution.

• The Extraction /get from operator - >> is used for for input operation along with the object

• Synatx: StreamObject >> Variable ;

• Since keyboard is the standard input device , cin is used as stream object.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• Eg : cin>>x; → This statement accept a value from keyboard and store it in ‘x’ named
memory location.

→Output Statement

• Output statement is used present some data /result to the user through an output device.

• The insertion / put to operator - << is used for output some data.

• Syntax :
StreamObject >> data :

• Since Monitor is the standard output device , cout is used as the stream object.

• Eg:
1) Cout<<”welcome ”; //prints welcome on screen
2) Cout<<”x” ; // prints x on screen
3) Int x;
X=10;
Cout<<x; // print the value of x on screen , ie, 10.

Cascading of Input / output(I/O) operators


The multiple use of input or output operators in a single statement is called cascading of I/O operators.
Eg:
Cout<<”Enter three numbers”;
Cin>>a>>b>>c;
Cout<<x<<y<<z;
X=10;
Cout<<”The Value of x is ”<<x; // Prints The value of x is 10.
Y=20;
Cout<<”x=”<<x<<”and y=”<<y; // Prints x=10 and y=20

Type Conversion
• The process of converting the data type of an operand into another data type is called Type
Conversion.

• The two types of type conversion are :


KALLADI HSS NOTES BY MUSTHAFA 9544885401
1) Implicite Type conversion (Type Promotion).
2) Explicite Type Conversion (Type Casting)
→Implicite type conversion (Type Promotion)

• The process of converting the data type of lower sized operand into higher sized operand is
called Implicite type conversion.

• It is done by the compiler automatically.

• Eg : 7 + 3.5 → 7.0 +3.5 → 10.5


→Explicite Type Conversion(Type Casting)

• The process of converting the data type of result into a desired data type by the programmer is
called Explicite type conversion.

• It is the explicit type conversion and is done by the programmer by specifying the data type
within parentheses to the left of the operand.
Variable Initialisation

• Supplying value to a variable at the time its declaration is called variable Initialisation.

• Syntax:
DataType variable = Value ;

• Eg: int num = 10; or int num(10);


float pi=3.14;
→ Dynamic Initialisation
Initialising a variable during the execution of the program is called Dynamic initialization.
Eg:
int x=a+b+c;
Si=p * n* r /100;
Const Access modifier

• ‘const’ access modifier is used to create symbolic constants whose value can never be
changed during the program execution.

• It changes the read/write accessibility of variable into ‘read only’.

• Eg : cons float pi=3.14; // the value of pi can never be changed .


Type Compatibility
During the execution of an Assignment statement , if the data type of RHS is different from the Datatype
of LHS, always convert RHS into the data type of LHS. Consider the Eg:
1) Int a=5 , b=2;
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Float p, q;
P=b; //type promotion ,p becomes 2.0
q=a/p; // q=5/2.0 → q= 5.0 /2.0 → q=2.5

2) Int a=5,b=2;
Float p;
P=a/b; // p =5/2 → p=2 → p=2.0 ( 2 is converted to the data type of RHS – p ,ie,float 2.0)
Structure of a c++ program
The structure of a c++ program is :
#include <iostream>

using namespace std;

int main ()

Statements ;

return 0;

Preprocessor Directive

• Preprocessor Directives are the compiler directive statements.

• It instructs the compiler to process the information provided before the actual compilation starts.

• Preprocessor Directives starts with # symbol. And no ; is needed at the end.

• #include is used to link the header files from c++ library to our program.

• Eg: #include ,#define , #undef etc


Header Files

• Header files contain Information about Predefined functions , objects ,data types etc.

• The header file < iostream> contains the information about the objects cin and cout.

• Eg : <cmath> , <cstring> etc


namespace

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• Namespace is the container of unique identifiers.

• It tells the compiler about a namespace where it should search for the elements used in the
program.

• The identifiers like cin , cout are defined in the standard namespace std.
main() function

• Every program execution starts from and end within main() function.

• Calls to other functions are also made from main function.


Comments

• Comments are the information that describes the source code.

• Two types of comments are – Single line comment and Multiline comment

• Single line comment - Single line comments are written after //.

• Multiline comments – Comments that take more than one line are written within /* and */.
Guidelines for Coding

• Use suitable names for Identifiers.

• Use clear simple Expressions.

• Use comments wherever needed.

• Write program in indented style.

Programs
1. Program to Print your Name and address
#include<iostream> //link the header file iostream with our program

Using namespace std; //makes available the identifiers cin, cout to our
program.

int main()

cout<<”My Name is Kamal \n”; \\ ‘\n’ is to break the line

cout<<”I am from Ottappalam”;

return 0;

KALLADI HSS NOTES BY MUSTHAFA 9544885401


2. Program to find the sum of Two Integer numbers
#include <iostream> Output

using namespace std;

int main() Enter Two numbers 10

{ 20

int num1, num2 , sum; Sum is 30

cout<<”Enter two Numbers”;

cin>>num1>>num2;

sum=num1+num2;

cout<<”sum is : “<<sum;

return 0;

3. Program to find the Area and perimeter of a rectangle.?


4. program to find area and perimeter of a Circle.?
5. Program to calculate area and perimeter of a square.?
6. Program to calculate simple interest.?
7. program to find calculate sum and average of 3 numbers.?
8. program to calculate sum and product of three numbers.?

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 7

Control Statements
The statements that change the sequential flow of execution of a program are called Control Statements.Control
statements are classified into :

1. Decision Making Statements / Selection Statements


• If statement. ( if , if –else , Nested if , else if ladder)
• Switch Statement.
2. Looping Statements / Iteration Statements
• While Loop.
• Do-while Loop
• For Loop

Decision Making Statements / Selection Statements


Decision Making Statements or Selection Statements are the statements that select or skip a block of
statements based on a particular condition.if and switch are the two types of selection statements.

if Statement

• If statement is used to select a block of statements for execution when a particular condition is true.
• The condition (Test Expression) will be a Relational or Logical Expression .

Syntax: Eg: Flow Chart:

if ( mark <=30)
if ( Test expression) {
{ cout<<”Passed”;
Statements ton be }
executed when the
Test Expression is true;
}

If….else Statement

• If statement is used to execute a block of statements when a particular condition is true and execute
another block of statement when the given condition is false.
• If .. else statement execute the first block of statements if the given test expression is true and skip the
else block.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• If .. else statement skip the first block of statements and execute the second block of statements if the
test expression is false.

Syntax: Eg: Flow Chart:

if ( mark <=30)
if ( Test expression) {
{ cout<<”Passed”;
Statements ton be }
executed when the else
Test Expression is true; {
} cout<<”Failed”;
else }
{
Statements ton be
executed when the
Test Expression is false;
}

Program to check whether the Program to find the largest among two Program to check whether the
student is passed or failed. Numbers/Heights/Marks given Number is Even or Odd.

#include <iostream> #include <iostream> #include <iostream>


using namespace std; using namespace std; using namespace std;
int main() int main() int main()
{ { {
int mark; int num1,num2; int Num;
cout<<”Enter Your mark :”; cout<<”Enter two Numbers :”; cout<<”Enter a number :”;
cin>>mark; cin>>num1>>num2; cin>>Num;
if ( mark <=30) if ( num1 > num2) if ( Num % 2 == 0)
{ { {
cout<<”Passed”; cout<<”Largest is : ”<<num1; cout<<”Even”;
} } }
else else else
{ { {
cout<<”Failed”; cout<<”Largest is : ”<<num2; cout<<”Odd”;
} } }
return 0; return 0; return 0;
} } }

Nested if Statement
An if statement placed within another if statement is called Nested if statement .Nested means one inside
another.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Syntax:
if ( Test expression 1)
{
if ( Test expression 2)
{
True_Case_Statements 2;
} True_Case_Statements_1
else
{
False _Case _Statements 2
}
}
else
{
False _Case _Statement 1;
}

Program to check whether the Given Number is Positive , Negative or Zero.

#include <iostream>
using namespace std;
int main()
{
int N;
cout<<”Enter a number :”;
cin>>N;
if ( N != 0)
{
if (N >0)
cout<<”It is a Positive Number”;
else
cout<<” It is a Negative Number”;
}
else
{
cout<<”it is a Zero”;
}
return 0;
}

if…else if…else statement


If-else if-else statement is used when multiple Test expressions are to be checked:

Syntax: Program To find the largest among Three Numbers.

if ( Test Expression1) #include <iostream>


{ using namespace std;
True_Case_Statemets_1; int main()
} {
else if (Test Expression2) int A,B,C;
KALLADI HSS NOTES BY MUSTHAFA 9544885401
{ cout<<”Enter Three Numbers :”;
True_Case_Statemets_2; cin>>A>>B>>C;
}
. if ( A>B && A>C)
. cout<<”Largest is : ”<<A;
else else if (B>C)
{ cout<<”Largest is : ”<<B;
false_Case_Statemets; else
} cout<<”Largest is : ”<<C;

return 0;
}

else if ladder
• The else if ladder consist of single if statement , multiple else-if statements and a single else statement.
• Different conditions will be given and each condition will decide which statement is to be executed.
• Syntax:
if ( Test expression)
True_case statements1;
else if (Test Expression2)
True_case statements2;
else if (Test Expression3)
True _case statements 3 ;
.
.
.
else
False_Case_Statements;

Program to find the grade of a student for a given score


Score Grade
80 or more A
From 60 to 79 B
From 40 to 59 C
From 30 to 39 D
Below 30 E
#include <iostream>
using namespace std;
int main()
{
int score;
cout<<”Enter Your Score: ”;
cin>>score;
if (score >=80)
cout<<”A Grade”;
else if (score>=60)
cout<<”B Grade”;
else if (score>=40)
cout<<”C Grade”;
else if (score>=30)
KALLADI HSS NOTES BY MUSTHAFA 9544885401
cout<<”D Grade”;
else
cout<<”Failed”;
return 0;
}

Program To print the day of the week Corresponding Program to Check whether the given Character is a Vowel
to the number between 1-7 or Not

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
int day; char ch;
cout<<”Enter a number between 1-7: ”; cout<<”Enter a Character: ”;
cin>>day; cin>>ch;
if (day ==1) if (ch==’a’)
cout<<”Sunday”; cout<<”it is a vowel”;
else if (day==2) else if (ch==’e’)
cout<<”Monday”; cout<<”it is a vowel”;
else if (day==3) else if (ch==’i’)
cout<<”Tuesday”; cout<<”it is a vowel”;
else if (day==4) else if (ch==’o’)
cout<<”Wednesday”; cout<<”it is a vowel”;
else if (day==5) if (ch==’u’)
cout<<”Thursday”; cout<<”it is a vowel”;
else if (day==6) else
cout<<”Friday”; cout<<”it is not a vowel”;
else if (day==7) return 0;
cout<<”Saturday”; }
else
cout<<”invalid”;
return 0;
}

Switch Statement
• Switch statement is used to successively tests the value of a variable or an expression against a list of
integer or character constants.
Syntax:
switch(Expression/Variable)
{
case constant_1 : statement_Block1 ; break ;
case constant_2 : statement_Block1 ; break ;
case constant_3 : statement_Block1 ; break ;
.
.
case constant_N : statement_Block1 ; break ;
default : Default_statement ;
}

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• switch , case , default , break are keyword.
• Constants can be any Integer Constant or character Constant.
• The Switch Variable is compared against the case constants . If any match is found , the corresponding
statement_block is executed .
• Break statement is used to stop the execution within the switch statement.

Program To print the day of the week Corresponding Program to Check whether the given Character is a
to the number between 1-7 Vowel or Not

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
int day; char ch;
cout<<”Enter a number between 1-7: ”; cout<<”Enter a Character: ”;
cin>>day; cin>>ch;
switch(day) switch(ch)
{ {
case 1: cout<< “Sunday”; break; case ‘a’: cout<< “It is a Vowel”; break;
case 2: cout<< “Monday”; break; case ‘e’: cout<< “It is a Vowel”; break;
case 3: cout<< “Tuesday”; break; case ‘i’: cout<< “It is a Vowel”; break;
case 4: cout<< “Wednesday”; break; case ‘o’: cout<< “It is a Vowel”; break;
case 5: cout<< “Thursday”; break; case ‘u’: cout<< “It is a Vowel”; break;
case 6: cout<< “Friday”; break; default : cout<<”It is not a Vowel”
case 7: cout<< “Saturday”; break; }
default : cout<<”Invalid Entry”; return 0;
} }
return 0; The switch statement can also be written as:
} switch(ch)
{
case ‘a’:
case ‘e’:
case ‘i’ :
case ‘o’ :
case ‘u’: cout<<”It is a Vowel”;
default : cout<<”It is not a Vowel”; }
Suitability and Requirement of Switch Statement

A switch statement is used when:

• Conditions Involve Only Equality Checking.


• First operand is a variable and is same in all Conditions.
• The second operand in all the expressions is a Character or Integer constant.

Difference Between switch Statement and Else if Ladder

switch statement else if ladder


• Evaluates expressions with Equality • Evaluates any relational Expression.
operator only.
• Case constants must be integer or character • Operands can be integer , character or
constants. floating point constants.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• When no match found , default statement is • When no expression evaluates True, else
executed. statement is executed.
• break statement is required to exit from • After execution of the True Case statements
switch statement. program control goes out automatically.
Conditional Operator (? :)
Conditional operator is a ternary operator that operates on three operands . It can be used as an alternative to if-
else statement.

The syntax is:

Test_Expression ? True_Case_Code : False_Case_Code ;

• Test expression can be any Relational expression or Logical expression.


• Other statements can be Constants,Expressions, Variables or Statements.
• It evaluates the Test Expression and If it is true then true case code is selected for execution and false case
code is executed if the test expression is false.
• Example:
If Statement Conditional Operator( ? :)
if ( Test expression)
True_Case_Code;
else Test_Expression ? True_Case_Code : False_Case_Code ;
False_Case_Code;
if ( A > B) • (A > B) ? cout<<A : cout<<B ; or
cout<<A; • cout<<(A > B) ? A : B ; or
else • Big = (A > B) ? A : B ;
cout<<B; cout<<Big;
if ( N%2 == 0) • ( N%2 == 0) ? cout<<”Even” : cout<<”Odd”; or
cout<<”Even”; • cout<<( N%2 == 0) ? ”Even” : ”Odd”; or
else • result= (N%2 == 0) ? ”Even” : ”Odd”;
cout<<”Odd”; cout<<result;

Iteration Statements / Looping Statements


• Iteration Statements are used to repeatedly execute a one or more statements when a condition is true.
• A ‘loop control variable’ is used to control the execution of the Loop.
• Every Iteration statement is connected with 4 Elements:

1. Initialization Statement: - It is the step of giving first value to the loop control Variable. It will
execute only once.
2. Test Expression : It is a Relational or Logical Expression which decides whether the body of loop is
to be executed or not.
3. Update Statement :- It is the step of changing the value of loop control variable before the next
iteration.
4. Body of Loop :- It is the one or more statements that is to be executed repeatedly

Different types of Looping statements are:


KALLADI HSS NOTES BY MUSTHAFA 9544885401
• while loop
• do – while loop]
• for loop

while statement
• It is an entry controlled loop that repeatedly execute a block of statements when a condition is true.
• The condition is checked first and the body of the loop will be executed only if the condition is True.

Syntax Example Data Flow diagram


Initialization Statement ; int i=1 ; 1
while ( Test_Expression) while (I <=10 )
{ { 2
cout<< i ;
Body of loop ..
i ++;
Updation Statement ; 3
}
}
4

Program Execution Flow : 1 ➔ 2 →True → 3 → 2→ True →3 …………

False →4 Flase →4

do – while loop
• It is an exit controlled loop that repeatedly execute a block of statements when a condition is true.
• The body of the loop will be executed first and then the condition is checked. iteration will continue only
when the condition is true.
Syntax Example Data Flow diagram
1

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Initialization Statement ; int i=1 ;
do do
{ {
cout<< i ; 2
Body of loop ..
i ++;
Updation Statement ;
} while (i <=10); 3
} while ( Test_Expression);
4

Program Execution Flow : 1 ➔ 2 →3 →True → 2→3→ True →2 →3 …………

False →4 Flase →4

for Loop
• It is an entry controlled loop that repeatedly execute a block of statements when a condition is true.
• The condition is checked first and the body of the loop will be executed only if the condition is True.
• In for loop the Initialization statement , Test Expression and Updation Expression are included in a single
statement.

Syntax: for ( Initialization Statement ; Test Expression ; Updation Statement )


{
Body of Loop ;
}
Example : for ( i =1; i <= 10 ; i ++ )
{
cout << i ;
}

Data flow diagram


Special Cases with for Loop

• Case 1: When semicolon is placed after the loop statement , the body of the loop will execute only when
the test expression becomes false.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Eg: for ( k=1 ; k<=5 ; k++ );
cout<<k; // It produce Output as 6
• Case 2: When the initialization expression is not given , the loop control variable will assign some random
value. Since the output cannot be Predicted.
• Case 3: When the updation expression is not given , the loop will never be terminated. it will work
infinitely.
• Case 4: When the Test expression is not given , it will treated as True and the loop will execute infinitely.

Difference Between for loop , while loop and do while loop’

for loop while loop do-while loop


• Entry Controlled loop. • Entry Controlled loop. • Exit Controlled loop.
• Initialization , test expression and • Initialization before the loop • Initialization before the
updation in a single statement. definition. loop definition.
• Body of loop may or may not be • Body of loop may or may not • Body of loop will execute
execute atleast once. be execute atleast once. atleast once.

Nesting of Loops
• Placing a loop inside the body of another loop is called Nesting of a loop.
• When we nest two loops , the outer loop counts the number of completed repetitions of inner loop.
• Loop control variables for each loop must be different.

Program to Display a Star Triangle

*
* *
***
* ** *
#include <iostream>
using namespace std;
int main()
{
int N,i,j,;
cout<<”Enter a number of Rows :”;
cin>>N;
for ( i =1 ; i <=n ; i ++)
{
for ( j=1 ; j <=i ; j ++)
{
cout<<” * ”;
}
cout<<”\n”;
}
return 0;
}

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Jump statements
The statements that is used to transfer the program control from one place to another are called jump statements. Jump
statements in C++ are return , goto ,break and continue.

• return statement is used to transfer the program control back to the calling function .
• exit() function is used to terminate a program. exit() function is defined in the header file <cstdlib>

1. goto Statement

goto statement is used to transfer the program control to a labeled location. labels are the identifiers given to statements.

Syntax of goto statement is: eg:

goto label; int i =1;


start:
............; cout<<i;
i ++;
label: ..........; goto start;
Output:

2. break Statement

break statement is used to takes the program control outside the looping or switch statement.

Eg: The output of this code segment will be → 1 2


for (int i=1 ; i<=10 ; i ++) When ‘i’ becomes three, the break statement takes the program control
{ out of the loop.
if ( i == 3)
break;
cout<<i ;
}

break statement Continue statement


• break statement Can be used with switch statement • continue statement can be used with loop statement
and loop statement only.
• break statement is used to transfer the program • continue statement is used to transfer the program
control outside the switch and loop. control to the beginning of loop
• Program control goes out even the test expression is • Program control goes out only when the test
true expression is false.

3. continue statement

continue statement is used to bring the program control to the beginning of the loop by skipping the rest of the statements
within the block. It stops current iteration and starts the next iteration.

Eg: The output of this code segment will be → 1 2 4 5 6 7 8 9 10


for (int i=1 ; i<=10 ; i ++)
KALLADI HSS NOTES BY MUSTHAFA 9544885401
{ When ‘i’ becomes three, the continue statement stops current iteration
if ( i == 3) and forces next iteration.
continue;
cout<<i ;
}

Program Gallery
while loop do-while loop for loop
Program to print Natural Program to print Natural Program to print Natural
Numbers upto 100 Numbers upto 100 Numbers upto 100

#include <iostream> #include <iostream> #include <iostream>


using namespace std; using namespace std; using namespace std;
int main() int main() int main()
{ { {
int i ; int i; int i;
i =1 ; i =1 ; for ( i =1; i<=100 ; i++)
while ( i <=100) do {
{ { cout<<i;
cout<< i ; cout<< i ; }
i ++; i ++;
return 0;
} } while ( i <=100);
}
return 0; return 0;
} }

while loop do-while loop for loop


Program to print Natural Program to print Natural Program to print Natural
Numbers upto a limit / N Numbers upto a limit / N Numbers upto a limit / N

#include <iostream> #include <iostream> #include <iostream>


using namespace std; using namespace std; using namespace std;
int main() int main() int main()
{ { {
int i ,N; int i ,N; int i ,N;
cout<<”Enter the limit :”; cout<<”Enter the limit :”; cout<<”Enter the limit :”;
cin>>N; cin>>N; cin>>N;
i =1 ; i =1 ; for ( i =1; i<=N ; i++)
while ( i <=N) do {
{ { cout<<i;
cout<< i ; cout<< i ; }
i ++; i ++;
return 0;
} } while ( i <=N);
} ___________________________
return 0; return 0;
} ____________________ } _____________________
Program to print “ Even”
Program to print “Even” Program to print “ Even”
Numbers upto a limit / N
Numbers upto a limit / N Numbers upto a limit / N

KALLADI HSS NOTES BY MUSTHAFA 9544885401


#include <iostream> #include <iostream> #include <iostream>
using namespace std; using namespace std; using namespace std;
int main() int main() int main()
{ { {
int i ,N; int i ,N; int i ,N;
cout<<”Enter the limit :”; cout<<”Enter the limit :”; cout<<”Enter the limit :”;
cin>>N; cin>>N; cin>>N;
i =2 ; i =2; for ( i =2; i<=N ; i+=2)
while ( i <=N) do {
{ { cout<<i;
cout<< i ; cout<< i ; }
i +=2; i +=2;
return 0;
} } while ( i <=N);
}
return 0; return 0;
}___________________ }__________________ ___________________
Program to print sum of Program to print sum of Program to print sum of Natural
Natural Numbers Upto N Natural Numbers Upto N Numbers Upto N
#include <iostream> #include <iostream> #include <iostream>
using namespace std; using namespace std; using namespace std;
int main() int main() int main()
{ { {
int i ,N,sum=0; int i ,N,sum=0; int i ,N,sum=0;
cout<<”Enter the limit :”; cout<<”Enter the limit :”; cout<<”Enter the limit :”;
cin>>N; cin>>N; cin>>N;
i =1 ; i =1 ; for ( i =1; i<=N ; i++)
while ( i <=N) do {
{ { sum=sum+i ;
sum=sum+i ; sum=sum+i ; }
i ++; i ++; cout<<”sum is :”<<sum;
} } while ( i <=N); return 0;
cout<<”sum is :”<<sum; cout<<”sum is :”<<sum; }
return 0; return 0;
} }

Program to find the factorial of a number using for Program to find the Sum and average score of N
loop. [ 5! = 1*2*3*4*5] students.

#include <iostream> #include <iostream>


using namespace std; using namespace std;
int main() int main()
{ {
int i ,N, fact=0; int i ,sum=0,N,score;
cout<<”Enter the Number :”; float avg;
cin>>N; cout<<”Enter the number of Students :”;
for ( i =1; i<=N ; i++) cin>>score;
{ for(i=1 ; i<N ; i++)
fact=fact * i ; {
} cout<<”Enter the mark of student :”<<i+1;
cout<<”Factorial is :”<<fact; cin>>score;
return 0; sum=sum+score;
} }
KALLADI HSS NOTES BY MUSTHAFA 9544885401
avg = sum/N;
cout<<”Sum of scores is:”<<sum;
cout<<”Average score is :”<<avg;
return 0;
}

Program to check whether the given number is Program to Print the N terms of the Fibonacci
prime or Not. series.
[ 0 1 1 2 3 5 8 13 21…..]
#include <iostream>
#include<cstdlib>
using namespace std; #include <iostream>
int main() using namespace std;
{ int main()
int i ,N; {
cout<<”Enter the Number :”; int i ,N, first = 0, second = 1 ,third;
cin>>N; cout<<”Enter the Number of terms:”;
for( i=2 ; i<N/2 ; i++) cin>>N;
{ cout<<first<<”\t”<<second;
if ( N% i ==0) for( i=2 ; i<=N ; i++)
{ {
cout<<”Not a prime Number .”; third = first +second;
exit(0); cout<<third;
} first = second;
} second = third;
cout<<”Prime Number”; }
return 0;
} return 0;
}

Program to find the sum of digits of a Number Program to check whether the given number is
Pallindrome or Not.
#include <iostream>
using namespace std; #include <iostream>
int main() using namespace std;
{ int main()
int num , digit , sum=0; {
cout<<”Enter a Number :”; int num , digit , rev=0;
cin>>num; cout<<”Enter a Number :”;
while ( num >0) cin>>num;
{ t=num;
digit = num%10; while ( num >0)
sum = sum+digit; {
num= num/10; digit = num%10;
} rev = rev*10+digit;
cout<<”Sum is:”<<sum; num= num/10;
}
KALLADI HSS NOTES BY MUSTHAFA 9544885401
return 0; if ( t == rev )
} cout<<”It is palindrome ”;
else
cout<<”It is Not Pallindrome”;
return 0;
}

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 8

ARRAYS
→Array

• An array is a collection of elements of the same type placed in continuous memory locations.
• Array is a single variable that can store multiple values of same type.
• Arrays are used to store same type of values under a single variable name.
• Each element in an array can be accessed using its position in the list, called index number or subscript.
• Each item in an array is called an element of the array.

→ Declaring arrays

The syntax for declaring an array is:

Data_type Array_name[size];

• Data_type can be any fundamental data type (int , char , float, double) , which determines the type of
data that array can store.
• Array_Name is the identifier for naming the Array.
• Size is any positive Number , which determines the maximum number of elements that array can store.

Eg: int num [20];

char Name[15];

float mark[60];

Consider an Array declaration:

int num[10];

The elements within the array arranged as follows:

➔ Elements within the array can be accessed by giving the array’s name and the element’s position. This
position is called the index or subscript value.The array index starts with zero.
➔ The First element within the array can be accessed as : Array_name[0];
➔ The 10th element within the array can be accessed as : Array_name[9];
➔ The 75th element within the array can be accessed as : Array_name[74];
➔ The Nth element within the array can be accessed as : Array_name[N-1];

→Memory allocation for arrays

The total Memory space allocated for an array can be calculated as:
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Total Memory allocated = sizeof (array_data_type) × size_of_array

Consider an array declaration :

int mark [60] ;

Memory allocation for the array mark = sizeof ( int ) x size of array

= 4 x 60 = 240 Bytes.

Q? Calculate the memory allocation for the array : char name [25];

Ans : Memory allocation for the array mark = sizeof ( char ) x size of array

= 1 x 25 = 25 Bytes.

Q? Calculate the memory allocation for the array : float weight [40];

Array initialization
An array can be initialized in different ways:

Syntax 1: Along with array declaration

Data_Type ArrayName [size] = { Value1, Value2 , Value3…………};

Eg: int mark [5] = { 34 , 60 ,56 ,21 ,43 };

char name[6]= { ‘k’ , ‘a’ , ’m’ , ‘a’ ,’l’ };

Syntax 2: By specifying the subscript:

ArrayName [index] = value;

Eg: int mark [5]; Eg : char name[6];


mark[0]= 34; name[0] = ‘k’;
mark[1]= 60; name[0] = ‘a’;
mark[2]= 56; name[0] = ‘m’;
mark[3]= 21; name[0] = ‘a’;
mark[4]=43; name[0] = ‘l’;
Syntax 3 : During declaration , without specifying size:

Data_Type ArrayName [ ] = { Value1, Value2 , Value3…………};

Eg: int mark [ ] = { 34 , 60 ,56 ,21 ,43,6,57,8,67 };

char name[ ]= { ‘k’ , ‘a’ , ’m’ , ‘a’ ,’l’ };

Accessing Elements of an Array

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Array elements are accessed by specifying the subscript along with the ArrayName.

The syntax is : ArrayName [index];

consider an array - Mark [5];

The first element within the array Mark is accessed as : Mark[0];

The first element within the array Mark is print as : cout<<Mark[0];

The first element within the array Mark is read as : cin>>Mark[0];

The second element within the array Mark is accessed as : Mark[1];

The second element within the array Mark is print as : cout<<Mark[1];

The second element within the array Mark is read as : cin>>Mark[1];

The sum of all the elements within the array can be calculated as :

Sum = Mark[0]+ Mark[1]+ Mark[2]+ Mark[3] Mark[4];

• Reading an Array
Consider an Array ‘Ar’ with N elements .It can be read as :

cout<<”Enter the Elements of the Array :”;

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

cin>>Ar[i];

• Printing the elements in an Array


Consider an Array ‘Ar’ with N elements .Its elements can be print as :

cout<<”The Elements of the Array are :”;

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

cout<<Ar[i];

• Sum of elements within an Array


for ( i=0; i<N ; i++)
sum = sum + Ar[ i ];
cout<<”Sum is :”<<sum;

• Doubling Each element within the Array Ar


for ( i=0; i<N ; i++)
Ar[ i ] = Ar[ i ] * 2;

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• Adding 5 with each element of the array
for ( i=0; i<N ; i++)
Ar[ i ] = Ar[ i ] + 5;

• To print elements within the array in reverse order


for ( i=N-1 ; i >=0 ; i--)
cout<<Ar[i];

PROGRAM TO READ AND PRINT THE ELEMENTS OF THE ARRAY:

#include <iostream>
using namespace std;
int main()
{
int i, ,N, Ar[50];
cout<<”Enter the number of elements:”;
cin>>N;

cout<<”Enter the Elements :”;


for(i=0; i<N; i++)
cin>>Ar[i];

cout<<”The Array Elements are:”


for(i=0; i<N; i++)
cout<<Ar[i] <<”\t”;

return 0;

Array Operations
Different operations that can be performed on Array are:

• Traversal.
• Insertion.
• Deletion.
• Searching.
• Sorting.
• merging.

Traversal

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Traversal is the operation of accessing each element of the array at least once. Printing the elements within the
array , Calculating sum of elements within the array , Doubling each elements within the array are examples for
traversal operation.

PROGRAM TO READ, DOUBLE AND PRINT THE ELEMENTS OF THE ARRAY:

#include <iostream>
using namespace std;
int main()
{
int i, ,N, Ar[50];
cout<<”Enter the number of elements:”;
cin>>N;

cout<<”Enter the Elements :”;


for(i=0; i<N; i++)
cin>>Ar[i];

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


Ar[ i ] = Ar[ i ] * 2;

cout<<”The Array Elements after doubling are:”


for(i=0; i<N; i++)
cout<<Ar[i] <<”\t”;

return 0;

Sorting
• Sorting is the process of arranging the elements of the array in some logical order.
• The logical order may be ascending or descending in case of numeric values or alphabetical order in case
of strings.
• Different sorting Algorithms are: - Bubble Sort and Selection Sort

Bubble sort

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Bubble sort is a sorting algorithm that works by repeatedly stepping through list that need to be sorted,
comparing each pair of adjacent items and swapping them if they are in the wrong order. This passing procedure
is repeated until the list is sorted.

Bubble Sort Illustration

Initial list

23 12 7 11 4

Pass 1

Pass 2

Pass 3
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Pass 4

• In bubble sort, to sort a list of ‘N’ elements,we require (N-1) passes. In each pass the size of the revised list
will be reduced by one.

Algorithm for bubble sort


Step 1: Start

Step 2: Accept a value in N as the number of elements of the array

Step 3: Accept N elements into the array AR

Step 4: Repeat Steps 5 to 7, (N - 1) times

Step 5: Repeat Step 6 until the second last element of the list

Step 6: Starting from the first position, compare two adjacent elements in thelist. If they are not in proper
order, swap the elements.

Step 7. Revise the list by excluding the last element in the current list.

Step 8. Print the sorted array AR

Step 9. Stop

PROGRAM FOR BUBBLE SORT

#include <iostream> for(i=1; i<N; i++)


using namespace std; for(J=0; J<N–i; J++)
int main() if(AR[J] > AR[J+1])
{ {
int AR[25],N; TEMP = AR[J];
int i, J, TEMP; AR[J] = AR[J+1];
KALLADI HSS NOTES BY MUSTHAFA 9544885401
cout<<"Enter the number of elements : "; AR[J+1] = TEMP;
cin>>N; }
cout<<"Enter the array elements: "; cout<<"Sorted array is: ";
for(i=0; i<N; i++) for(i=0; i<N; i++)
cin>>AR[i]; cout<<AR[ i]<<"\t";
return 0;
}

Q?: Predict the output of the above program.

Selection sort
• Selection sort algorithm starts by finding the minimum value in the array and moving it to the first position.
• At the same time, the element at the first position is shifted to the position of the smallest element.
• This step is then repeated for the second lowest value by moving it to the second position, and so on until the
array is sorted.
• The process of finding the smallest element and exchanging it with the element at the respective position is
known as a pass.
• For ‘n’ number of elements there will be ‘n – 1’ passes.

Bubble Sort Illustration

Initial list

32 23 10 2 30

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Algorithm for selection sort
Step 1: Start

Step 2: Accept a value in N as the number of elements of the array.

Step 3: Accept N elements into the array AR.

Step 4: Repeat Steps 5 to 9, (N – 1) times.

Step 5.: Assume the first element in the list as the smallest and store it in MIN and its position in POS

Step 6: Repeat Step 7 until the last element of the list

Step 7: Compare the next element in the list with the value of MIN. If it is found smaller, store it in MIN and its
position in POS

Step 8: If the first element in the list and the value in MIN are not the same, then swap the first element with the
element at position POS

Step 9: Revise the list by excluding the first element in the current list

Step 10: Print the sorted array AR

Step 11: Stop

Program for Selection Sort for(i=0; i < N-1; i++)

{
#include <iostream>
MIN=AR[i];
using namespace std;
POS=i ;
int main()
for(J = i+1; J < N; J++)
{
if(AR[J]<MIN)
int AR[25], N, i, J, MIN, POS;
{
cout<<"Enter the number of elements : ";
MIN=AR[J];
cin>>N;
POS=J;
cout<<"Enter the array elements: ";
}

KALLADI HSS NOTES BY MUSTHAFA 9544885401


for(i=0; i<N; i++) if (POS != i)

cin>>AR[i]; {

AR[POS]=AR[I];

AR[i]=MIN;

cout<<"Sorted array is: ";

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

cout<<AR[i]<<"\t";

return 0;

Searching
• Searching is the process of finding the location of the given element in the array.
• The search is said to be successful if the given element is found, that is the element exists in the array;
otherwise unsuccessful.
• There are basically two approaches to search operation: linear search and binary Search

Linear search

• Linear search or sequential search is a method for finding a particular value in a list.
• Linear search consists of checking each element in the list, one at a time in sequence, starting from the
first element, until the desired one is found or the end of the list is reached.
• Consider an Array ‘Ar’:

int Ar[6] = { 30 , 45, 23 , 56 , 98, 74 };

30 45 23 56 98 74

Ar[0] Ar[1] Ar[2] Ar[3] Ar[4] Ar[5]

Let the item to be searched be 56. Then Linear search works as follows:
Ar [0] == Item → 30 == 56 - false
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Ar [1] == Item → 45 == 56 - false
Ar [2] == Item → 23 == 56 - false
Ar [3] == Item → 56 == 56 - true. → it returns the Location 4.

Algorithm for Linear Search


Step 1: Start
Step 2: Accept a value in N as the number of elements of the array
Step 3: Accept N elements into the array AR.
Step 4: Accept the value to be searched in the variable ITEM
Step 5: Set LOC = -1
Step 6: Starting from the first position, repeat Step 7 until the last element
Step 7: Check whether the value in ITEM is found in the current position. If found then store the position in
LOC and Go to Step 8, else move to the next position.
Step 8: If the value of LOC is less than 0 then display "Not Found", else display the value of LOC + 1 as the
position of the search value.
Step 9. Stop

Program for Linear Search


#include <iostream>
using namespace std;
int main()
{
int AR[25], N;
int I, ITEM, LOC=-1;
cout<<"How many elements? ";
cin>>N;
cout<<"Enter the array elements: ";
for(I=0; I<n; I++)
cin>>AR[I];
cout<<"Enter the item you are searching for: ";
cin>>ITEM;
for(I=0; I<N; I++)
if(AR[I] == ITEM)
{
LOC=I;
break;
}
if(LOC!=-1)
cout<<"The item is found at position "<<LOC+1;
else
KALLADI HSS NOTES BY MUSTHAFA 9544885401
cout<<"The item is not found in the array";
return 0;
}

Binary search

• Binary search is an algorithm which uses minimum number of searches for locating the position of an element
in a sorted list.
• It performs searching by checking the middle element , eliminating half of the list from consideration, and
then performing the search on the remaining half.
• If the middle element is equal to the searched value, then the position has been found; otherwise the upper
half or lower half is chosen for search, based on whether the element is greater than or less than the middle
element.

Algorithm for binary search

Step 1: Start
Step 2: Accept a value in MAX as the number of elements of the array
Step 3: Accept MAX elements into the array AR.
Step 4: Accept the value to be searched in the variable ITEM
Step 5: Store the position of the first element of the list in FIRST and that of the last in LAST
Step 6: Repeat Steps 7 to 11 While (FIRST <= LAST)
Step 7: Set MID= (FIRST + LAST)/2 .
Step 8: IF ( AR [MID] == ITEM) THEN , display the position and go to Step 12.
Step 9: ELSE IF ( AR [MID] < ITEM) THEN set LAST = MID - 1
Step 10: ELSE IF ( AR [MID] > ITEM) THEN set FIRST = MIDDLE + 1
Step 11: Stop
Program for Binary search
#include <iostream>
using namespace std;
int main()
{
int AR[25],MAX;
int FIRST, LAST, MID, I, ITEM, LOC=-1;
cout<<"Enter the Number of Elements: ";
cin>>MAX;
cout<<"Enter array elements in ascending order: ";
for(I=0; I<MAX; I++)
cin>>AR[I];
cout<<"Enter the item to be searched: ";
cin>>ITEM;

FIRST=0;
LAST=MAX-1;
while(FIRST<=LAST)
{
MID=(FIRST+LAST)/2;
KALLADI HSS NOTES BY MUSTHAFA 9544885401
if(ITEM == LIST[MID])
{
LOC = MID;
break;
}
if(ITEM < AR[MID])
LAST = MID-1;
else
FIRST = MID+1;
}
if(LOC != -1)
cout<<"The item is found at position "<<LOC+1;
else
cout<<"The item is not found in the array";
return 0;
}

Difference Between Linear Search and Binary Search

Linear Search Binary Search


• The elements need not be • The elements should be in
in any order sorted order
• Takes more time for the • Takes very less time for the
process process
• May need to visit all the • All the elements are never
elements visited
• Suitable when the array is • Suitable when the array is
small. large

Two dimensional (2D) arrays


• A two dimensional array is an array in which each element itself is an array.
• For instance, an array AR[m][n] is a 2D array, which contains m single dimensional arrays, each of which
has n elements. Otherwise we can say that AR[m][n] is a table containing m rows and n columns.

Declaring 2D arrays

Syntax for declaring two dimensional array is :

data_type array_name[rows][columns];

The rows refers to the number of rows in the array and columns refers to the number of columns in the array.

Eg: int mark [60][6]; → Array with 60 rows and 6 columns.(Array to store the marks in 6 subjects
of 60 students.)

char name[20][50]; →Array to store 20 Names in which each name can contain maximum 50
characters.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Accessing elements of 2D Array

Elements within a two dimensional array can be accessed as :

ArraName [RowIndex] [ColumnIndex]; (Index starts from zero)

Consider a Two dimensional Array

int Arr [3][4];

0 1 2 3

0 Arr[0][0] Arr[0][1] Arr[0][2] Arr[0][3]

Arr[1][0] Arr[1][1] Arr[1][2] Arr[1][3]


1
Arr[2][0] Arr[2][1] Arr[2][2] Arr[2][3]
2

Memory Allocation for a 2D array

Total Memory Allocated for a 2D Array can be calculated as :

total_bytes = sizeof(data type) × number of rows × number of columns

For Eg:

Memory allocation for the array marks[5][4] is calculated as :

= sizeof(data type) × number of rows × number of columns

=4 x 5 x4 =80 Bytes.

Matrices as 2D arrays

Matrix is a two dimensional array with m rows and n columns.To represent a matrix using program , we use
nested loop. One loop to represent rows and other to represent columns.

Reading a matrix

cout<<”Enter the rows and columns:”;

cin>>m>>n;

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

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

cin>>matrix[i][j];

Printing a matrix

KALLADI HSS NOTES BY MUSTHAFA 9544885401


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

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

cout<<matrix[i][j];

PROGRAM TO CREATE MATRIX WITH m ROWS AND n COLUMNS


#include <iostream>
using namespace std;
int main()
{
int m, n, row, col, mat[10][10];
cout<< "Enter the order of matrix: ";
cin>> m >> n;
cout<<"Enter the elements of matrix\n";
for (row=0; row<m; row++)
for (col=0; col<n; col++)
cin>>mat[row][col];
cout<<"The given matrix is:";
for (row=0; row<m; row++)
{
for (col=0; col<n; col++)
cout<<mat[row][col]<<"\t";
cout<<”\n”;
}
return 0;
}

Transpose of a Matrix

Each matrix has a transpose. It is obtained by converting row elements into column elements or vice versa.

To find the transpose of a matrix


#include <iostream>
using namespace std;
int main()
{
int ar[10][10], m, n, row, col;
cout<<"Enter the order of matrix: ";
cin>>m>>n;
cout<<"Enter the elements\n";

for(row=0; row<m; row++)


for(col=0; col<n; col++)
cin>>ar[row][col];
cout<<"Original matrix is\n";
for(row=0; row<m; row++)
KALLADI HSS NOTES BY MUSTHAFA 9544885401
{
cout<<"\n";
for(col=0; col<n; col++)
cout<<ar[row][col]<<"\t";
}
cout<<"\nTranspose of the entered matrix is\n";
for(row=0; row<n; row++)
{
cout<<"\n";
for(col=0; col<m; col++)
cout<<ar[col][row]<<"\t";
}
return 0;
}

Multi-dimensional arrays
Each element of a 2D array may be another array. Such an array is called 3D (Three Dimensional) array. Its
declaration is as follows:

data_type array_name[size_1][size_2][size_3];

Eg: int mtc[2][3][2];

The elements of a 3D array are accessed using three subscripts.

For example consider a 3D array AR . Its first element is accessed as : AR[0][0][0].

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 9

String Handling and I/O Functions


• A string is a sequence of characters.
• ‘char’ data type can store a single character ; we use character array to represent strings.
• Consider an example:
char Name[10]; // A character array to store maximum of 25 characters.
This character array can be initialized as:
char Name[10]= { ‘s’ , ‘a’ , ‘c’ , ‘h’ ,’i’ , ’n’ };
This character array will be stored in memory as:

Name

s a c h I n \0

0 1 2 3 4 5 6 7 8 9

• A null character ‘\0’ is stored at the end of every string .


• This character is used as the string terminator and added at the end automatically.
• Thus, the memory required to store a string will be equal to the number of characters in the string plus one
byte for null character.
• ‘\0’ in memory represents the end of a string.
• The following statement Reads a string from the user and store in the character array Name.
cout<<”Enter your Name : ”;
cin>>Name;

Input/Output operations on strings

• Consider the following program to input a string and display the string

#include <iostream> Output:


using namespace std; Enter Your Name : Sachin
int main() Hello-Sachin
{
char Name[20];
cout << "Enter your name: ";
cin >> Name;
cout << "Hello-" << Name;
return 0;
}

• Let us execute the program with another input:


Enter Your Name : Sachin Tendulkar
Hello-Sachin

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Note the difference between the output in both the cases. Only one data item can be input using “cin” statement. A
white space is treated as a separator of data Thus, the input ‘Sachin Tendulkar’ is treated as two data items( Sachin and
Tendulkar separated by white space). Since ‘cin’ statement is used , only the first data (i.e., Sachin) is stored. The white
space after "Sachin" is treated as the delimiter

gets() function
The function gets() is a console input function used to accept a string of characters including white spaces from the standard
input device (keyboard) and store it in a character array. When using gets() function, we have to include <cstdio> header file
into our program.

Syntax: gets( character _ array);

Eg: gets(Name);

• Lets rewrite the above program using gets () function:


#include <iostream> Output:
#include<cstdio> Enter Your Name : Sachin Tendulakar
using namespace std; Hello-Sachin Tendulkar
int main()
(Note : Previously the output was only ‘Sachin ‘
{ when ‘cin‘ statement is used.)
char Name[20];
cout << "Enter your name: ";
gets(Name);
cout << "Hello-" << Name;
return 0;
}

Program to count number of vowels in a strings : for(int i=0; str[i]!='\0'; i++)

#include <iostream> switch(str[i])

#include <cstdio> {

using namespace std; case 'a':

int main() case 'e':

{ case 'i':

char str[20]; case 'o':

int vow=0; case 'u': vow++;

cout<<"Enter a string: "; }

gets(str); cout<<"No. of vowels in the string "<<str<<" is "<<vow;

return 0;

}
KALLADI HSS NOTES BY MUSTHAFA 9544885401
puts( ) function
puts() function is a console output function used to display a string data on the standard output device -monitor. puts() will
print a ‘\n’ after the string. Its syntax is:

puts(string_data);

Eg: puts(“computer ”); cout<<“computer ”;


puts(“science”); cout<<“science”;
Output Output
computer computer science
science

Console functions for character I/O


C++ provides some functions for performing input/ouput operations on characters. These functions require the
inclusion of header file <cstdio> into our program. The character functions are:

• getchar( )
• putchar( )
1. getchar()

getchar( ) function returns the character that is input through the keyboard. The character returned by the
getchar() function can be stored in a variable .

Example : char ch = getchar();

2. putchar()

This function displays the character given as the argument on the standard output unit (monitor). The argument
may be a character constant or a variable. If an integer value is given as the argument, it will be considered as an
ASCII value and the corresponding character will be displayed.

Eg: char ch = 'B'; //assigns 'B' to the variable ch

putchar(ch); //displays 'B' on the screen

putchar('c'); //displays 'c' on the screen

putchar(97); //displays 'a' on the screen (97 is the ASCII value of ‘a’).

Stream functions for I/O operations


• C++ provides some functions for performing input/ouput operations on character and strings.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• These functions require the inclusion of header file <iostream> into our program.
• These functions are generally called stream functions since they allow a stream of bytes (data) to flow
between memory and keyboard/monitor objects.
• Input stream functions are : get ( ) and getline( ) .
• Output stream functions are : put( ) and write( ).

Input functions

• Input functions allow the input of character and string data.


• The input functions such as get() and getline() allow a stream of bytes to flow from keyboard into the
memory.
• The object cin is used to refer to keyboard and hence whenever we input data using keyboard, these
functions are called or invoked using this object as cin.get() and cin.getline().

1. get( )
• get( ) function can accept a single character or multiple characters (string) through the keyboard.
• To accept a string, an array name and size are to be given as arguments.
Eg: char ch, str[10];

ch=cin.get(ch); //accepts a character and stores in ch

cin.get(ch); // equivalent to the above statement

cin.get(str,10); //accepts a string of maximum 10 characters.

2. getline()
• getline() function accepts a string through the keyboard.
• The delimiter will be Enter key, the number of characters or a specified character.
Eg : char ch, str[10];

int len;

cin.getline(str,len); // Accept a string of maximum ‘len’ number of characters.

cin.getline(str,len,ch); // Accept a string of maximum ‘len’ number of characters/upto


pressing the character ‘ch’.

Output Functions
Output functions allows a stream of bytes to flow from memory into monitor.

1. put( )

put( ) function is used to display a character constant or the content of a character variable given as argument.

char ch='c';
KALLADI HSS NOTES BY MUSTHAFA 9544885401
cout.put(ch); //character 'c' is displayed.

cout.put('B'); //character 'B' is printed.

cout.put(65); //character 'A' is printed.

2. write( )

write function displays the string contained in the argument.

char str[10]="hello";

cout.write(str,10); // Prints ‘hello’ followed by 5 white spaces.

Q: Read the following statements:

char name[20];

cin>>name;

cout<<name;

What will be the output if you input the string “virat kohli”. ? Justify your answer? Modify the code to get the
entered string as output.?

Ans: The output will be “Virat”. cin statement can read till a white space.

The following code prints “virat kohli”

char name[20];

gets(name);

puts(name);

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 10

Functions
Modular Programming
The process of breaking large programs into smaller sub programs is called modularization. These sub programs
are generally called Functions.

Merits/ Advantages of modular programming

The advantages of modular programming are:

• Reduces the size of the program: The repeating set of instructions in a program are grouped and a
name is assigned to this group. These repeating instructions can be involked by using that name. Thus
program size is reduced.
• Less chance for Errors: When the size of the program get reduced , the number of errors will also get
reduced.
• Reduces Programming Complexity: Since the size of the program and number of errors in program are
reduced , The complexity of the program will also get reduced.
Modularization reduces programming complexity by bringing down focus to a simplified task at a time.
• Improves Reusability: A function written once can be used later in many other programs.

Demerit of Modular Programming

Proper breaking down a large program into sub programs is a challenging task , since each program must be
independent of each other.

Functions
Function is a group of statements that together performs a specific task. Most of the functions give results after
performing the task. This result is known as value returned by the function.

Functions are classified into two:

• Predefined Functions or Built-in Functions.


• User defined Functions.

Parameters or Arguments:- Values that are passed to the function to perform the task assigned to it are called
Parameters or Arguments . Arguments are provided within brackets along with the function name, during function
call.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Predefined Functions or Built-in Functions
The ready to use functions whose definitions are already written , debugged , compiled and stored in header files
are called Predefined functions.

String Functions

• Several string functions are available in C++ for the manipulation of strings.
• String functions are available with the header file <cstring>.
• Different string functions in c++ are: 1.strlen( ) 2.strcpy( ) 3.strcat( ) 4.strcmp( ) 5.strcmpi( )
1. strlen( )

strlen( ) function is used to find the length of a string given as argument. Length of a string means the number of
characters in the string. Its syntax is:

int strlen( string );

This function takes a string as the argument and gives the length of the string as the result.

Eg: char str[ ] = "Welcome";

int n;

n = strlen(str);

cout << n; // Prints 7 (Number of characters in the string ‘welcome’)

Eg: n= strlen(“computer”);

cout<<n; // Prints 8.

2. strcpy( )

strcpy( ) function is used to copy one string into another. The syntax of the function is:

strcpy(string1, string2); // It will copy string2 into string1.

Eg: char str1[10] , str2[10] = "Welcome";

strcpy(str1,str2); // content in str2 (welcome) is copied into str1.

cout << str1; // prints welcome.

Eg: strcpy( str1, “computer”);

cout<<str1; // prints computer.

3. strcat( )

KALLADI HSS NOTES BY MUSTHAFA 9544885401


strcat( ) function is used to append/concatinate one string to another string.

The syntax of the functions is:

strcat(string1, string2); // string2 is concatenated with string1

Eg: char str1[20] = "Welcome", str2[10] = " To C++";

strcat(str1,str2);

cout << str1; // Prints WelcomeTo C++

4. strcmp( )

strcmp( ) function is used to compare two strings. In this comparison, the alphabetical order of characters in the
strings is considered.

The syntax of the function is:

strcmp(string1, string2)

The function returns any of the following values in three different situations.

• Returns 0 if string1 and string2 are same.

• Returns a –ve value if string1 is alphabetically lower than string2.

• Returns a +ve value if string1 is alphabetically higher than string2.

Eg: char str1[ ]="Computer", str2[ ]="Computer" , str3[ ]=”Calculator”;

int x,y;

x = strcmp(str1,str2);

cout<<x ; // prints 0.

y = strcmp( str2,str3);

cout<<y; //prints a random +ve value.

5. strcmpi( )

strcmpi( ) function is used to compare two strings ignoring cases. That is, the function will treat both the upper
case and lower case letters as the same for comparison. Thes syntax and results are same as strcmp() function.

Eg: : char str1[ ]="Computer", str2[ ]="COMPUTER"; int x,y;

x = strcmp(str1,str2);

cout<<x ; // prints 0.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Mathematical Functions

• Several mathematical functions are available in C++ to perform mathematical operations..


• Mathematical functions are available with the header file <cmath>.
• Different mathematical functions in c++ are: 1.abs( ) 2.fabs( ) 3.sqrt( ) 4.pow( ) 5.sin( ) 6.cos( )
1. abs( )

abs( ) function is used to find the absolute value of an integer. It takes an integer as the argument (+ve or –ve)
and returns its absolute value. Its syntax is:

int abs(int)

Eg: int n = -25;

cout << abs(n);// prints 25.

2. fabs( )

fabs( ) is used to find the absolute value of a floating point number . It takes a floating point number as the
argument and returns its absolute value. Its syntax is:

float fabs(float)

Eg: int n = -25.5;

cout << fabs(n);// prints 25.5 .

3. sqrt ( )

sqrt( ) function returns the square root of the integer or floating point number given as argument.

Syntax: int sqrt ( int );

Eg: x= sqrt(25);

cout<<x; // prints 5.

4. pow()

pow( ) function is used to find the power of a number. It takes two arguments x and y and returns the value of xy.
Its syntax is:

double pow(double, int)

Eg: int x = 2, y = 4, z;

z = pow(x, y); ( ➔ z=xy ➔ z=24 = 16)

cout << z; // prints 16.

5. sin( )
KALLADI HSS NOTES BY MUSTHAFA 9544885401
sin( ) is a trigonometric function and it finds the sine value of an angle.The angle must be given in radian measure.
Its syntax is:

double sin(double)

The sine value of 30° (angle 30 degree) can be found out by the following code.

float x = 30*3.14/180; //To convert angle into radians

cout << sin(x); // prints 0.4999770

6. cos()

The function is used to find the cosine value of an angle. In this case also, the angle must be given in radian
measure. The syntax is:

double cos(double)

The cosine value of 30° (angle 30 degree) can be found out by the following code.

double x = cos(30*3.14/180);

cout << x;// prints 0.866158.

Character Functions

• Character functions are used to perform various operations on characters.


• Character functions are available with the header file <cctype>
• Different character functions in C++ are: 1. isupper( ) 2.islower( ) 3.isalpha( )
4.isdigit( ) 5.isalnum( ) 6.toupper( ) 7.tolower( )
1. isupper( )

isupper( ) function is used to check whether a character is in the upper case or not. The syntax of the function is:

int isupper(char c)

The function returns 1 if the given character is in the uppercase, and 0 otherwise.

Eg 1: int n = isupper('M'); // function returns 1 and store it in n.

Eg 2: char c = ' j ';

int n = isupper(c); // function returns ‘0’ and store it in n.

2. islower( )

islower( ) function is used to check whether a character is in the lower case or not. The syntax of the function is:

int islower(char c)

The function returns 1 if the given character is in the lowercase, and 0 otherwise.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Eg 1: int n = islower('e'); // function returns 1 and store it in n.

Eg 2: char c = ' H ';

int n = islower(c); // function returns ‘0’ and store it in n.

3. isalpha( )

isalpha( ) function is used to check whether the given character is an alphabet or not. The syntax of the function
is: int isalpha(char c)

The function returns 1 if the given character is an alphabet, and 0 otherwise.

Eg: int n = isalpha('a'); //returns 1 and store it in n.

char c=’4’;

n= isalpha( c ); // returns 0 and store it in n.

4. isdigit( )

isdigit( ) function is used to check whether the given character is a digit or not. The syntax of the function is:

int isdigit(char c)

The function returns 1 if the given character is a digit, and 0 otherwise.

Eg: int n = isdigit(‘4’); // returns 1 and store it in n.

char c=’m’;

n= isdigit( c ); // returns 0 and store it in n.

5. isalnum( )

isalnum( ) function is used to check whether a character is an alphanumeric or not. The syntax of the function is:

int isalnum (char c)

The function returns 1 if the given character is an alphet or number , and 0 otherwise.

Eg: int n = isalnum(‘4’); // returns 1 and store it in n.

Eg: char c=’n’;

n= isalnum( c ); // returns 1 and store it in n.

6. toupper( )

KALLADI HSS NOTES BY MUSTHAFA 9544885401


toupper( ) function is used to convert the given character into its uppercase. The syntax of the function is:

char toupper(char c)

The function returns the upper case of the given character. If the given character is in the upper case, the output
will be the same.

Eg: char c=toupper(‘a’);

cout<<c; // Prints A.

7. tolower( )

tolower( ) function is used to convert the given character into its lower case. The syntax of the function is:

char tolower(char c)

The function returns the lower case of the given character. If the given character is in the lower case, the output
will be the same.

Eg: char c=tolower(‘A’);

cout<<c; // Prints a

Conversion Functions

• Conversion functions are used to convert a string to integer and an integer to string.
• Conversion functions are available with the header file <cstdlib>.
• Conversion functions are :
1. itoa( )
2. atoi( )
1. itoa( )

This function is used to convert an integer value to string type. The syntax of the function is:

itoa (int n, char c[ ], int len)

where : n - is the number to be converted.

c - is the character array where the converted string value is to be stored

len - is the size of the character array.

Eg: int n = 2345;

char c[10];

itoa(n, c, 10); //stores 2345 in the character array ‘c’ , of size 10.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


cout << c; // prints "2345"

2. atoi( )

This function is used to convert a string value to integer. The syntax of the function is:

int atoi(char c[ ]);

The function takes a string as argument returns the integer value of the string

Eg: int n;

char c[10] = "2345";

n = atoi(c); //string “2345” is converted into number and stored in n.

cout << n;// prints 2345.

If the string consists of characters other than digits, the output will be 0. But if the string begins with digits, only
that part will be converted into integer.

eg: (i) atoi("Computer") //returns 0

(ii) atoi("12.56") // returns 12

I/O Manipulating Functions

• I/O Manipulating Functions are used to manipulate the input and output operations in c++.
• I/O Manipulating functions are available with the header file <cstdlib>.
• I/O Manipulating function is setw( )

setw( )

setw( ) function is used to set the width for the subsequent string.

Eg: cout<<”welcome”<<setw(10)<<"to ooty"; // prints ‘ welcome to ooty’.

User-defined Functions
C++ provides the facility to create our own functions some specific tasks . These functions are known as user
defined functions.

Syntax of user defined function:

data_type function_name (argument_list) Function Header

{
Function
statements in the body; Function Body Definition

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• data_type is the data type of the value returned by the function. It can be any fundamental data type . If
the function doesn’t return any value , its type will be void.
• function_name is the identifier (user defined words) through the function is called.
• Function boby is the set of statements to do the specific task.

Eg: int add (int a , int b)

int c;

c= a+b;

return c;

Prototype of functions

• A function prototype is the declaration of a function by which compiler is provided with the information

about the function such as the name of the function, its return type, the number and type of arguments etc..

• The following is the format:

data_type function_name(argument_list);

In the prototype, the argument names need not be specified.

• Eg: int sum (int,int);


void area(float);

Parameters or Arguments of function

Values that are passed to the function to perform the task assigned to it are called Parameters or Arguments.
They are the means to pass values from the calling function to the called function

The two types Arguments or parameters are:

• Actual Arguments / Original Arguments: The constants, variables or expressions used in the
function call are known as actual (original) arguments
• Formal Arguments: The variables used in the function definition as arguments are known as formal
arguments.

Default Arguments

• Functions can be defined with arguments assigned with initial values.


• The initialized formal arguments are called default arguments.
• Default arguments allow the programmer to call a function with different number of arguments.
• Consider an example:
KALLADI HSS NOTES BY MUSTHAFA 9544885401
int add (int x, int y=10 , int z=20) Default arguments.
{
int sum= x+y+z;
return sum;
}

This function can be called in the following ways:

1. s = add(5); → x =5 ,y=10, z=20. Then sum becomes 35.


2. s = add(5,15); → x =5 ,y=15, z=20. Then sum becomes 40
3. s = add(5,15,25); → x =5 ,y=15, z=25. Then sum becomes 45.

Methods of calling functions


Based on the method of passing the arguments, the function calling methods can be classified as Call by

Value method and Call by Reference method.

Call by value (Pass by value) method

• In this method, the value contained in the actual argument is passed to the formal argument.
• Here a copy of the actual argument is passed to the function.
• If the formal argument is modified within the function, the change is not reflected in the actual argument
at the calling place.
• Exclusive memory allocation for actual arguments and formal arguments.
• Eg: void change(int n) // n gets the value of x, 20
{s
n = n + 1;
cout << "n = " << n ; //Prints n=21
}
int main()
{
int x = 20;
change(x); // the value of x will be passed to n.(ie, 20)
cout << "x = " << x; // prints x=20.
}

Call by reference (Pass by reference) method

• In this method ,the reference of the actual argument is passed to the function.
• The memory location allocated to the actual argument will be shared by the formal argument.
• If the formal argument is modified within the function, the change will be reflected in the actual argument
atthe calling place.
• In C++, to pass an argument by reference we use Reference variable as formal parameter. A reference
variable is an alias name of another variable. An ampersand symbol (&) is placed in between the data type
and the variable in the function header.
• Eg: void change(int &n) // n gets the value of x, 20
{
n = n + 1;
KALLADI HSS NOTES BY MUSTHAFA 9544885401
cout << "n = " << n ; //Prints n=21
}
int main()
{
int x = 20;
change(x); // the value of x will be passed to n.(ie, 20)
cout << "x = " << x; // prints x=21.
}

Call by Value Method Call by reference method


• Ordinary variables are used as formal Reference variables are used as
parameters. formal parameters
• Actual parameters may be constants, Actual parameters will be variables only.
variables or expressions.
• The changes made in the formal arguments The changes made in the formal arguments are
are not reflected in actual arguments. reflected in actual arguments.
• Separate memory locations for actual and Memory of actual arguments is shared by formal
formal argumrnts. arguments

Program To swap the values of two variables

#include <iostream> Output


using namespace std; Before swapping m=10 and n=20
void swap(int &, int &); After swapping m=20 and n=10
int main()
{
int m=10 , n=20;
cout<<"Before swapping m= "<< m <<" and n= "<<n;
swap(m, n);
cout<<"\n After swapping m= "<< m <<" and n= "<<n;
return 0;
}
void swap(int & x, int & y)
{
int t = x;
x = y;
y = t;
}
Scope and life of variables and functions
• The Availability and accessibility of variables and functions is termed as their scope and lifetime.
• Scope of a variable is that part of the program in which it is used.
• Scope of a variable can be Local scope or Global scope.
• A variable that is declared within a function and cannot be used outside the function is called Local scope.
• variables that are declared outside of all the functions and can be used throughout the program are Global
Scope.
• A function that is declared inside the body of another function is called Local Function.
• A function that is declared outside the body of all other functions is called Global Function.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Difference Between Local and Global varibales/Functions

Scope & Life Local Global


Declared within a function . Declared outside all the functions.
Variables Available only within that function Available to all the functions of
where it is declared. the program.
Memory is allocated when the function Memory is allocated just before the
is active and freed when the execution execution of the program and freed when
of the function completes. the program stops execution.
Declared within a function. Declared outside all other functions.
Functions Accessible only within that function Accessible by all the functions
where it is declared. in the program

Recursive function.

• The process of calling a function by itself is known as recursion.


• The function that call by itself is known as Recursive function.
• Consider the example program for finding the factorial of a number using Recursion.
#include<iostream>
using namespace std;
int main ( )
{
int n, f ;
cout<<”Enter a Number : ”;
cin>>n;
f= factorial (n);
cout<<”Factorial is :”<<n;
44444 return 0;
}
int factorial (int N)
{
int fact;
if (N==1)
return 1;
else
return factorial *factorial(N-1);
}

Creation of Header Files

• Header files can be created by saving the functions(definition only) with “filename.h” format .
• User created header files can be included in a program using the following format.
#include “filename.h” (note the change – its “ and “ instead of < and >)
Eg:
int factorial(int n)
{
int f=1;
for (int i=1; i<=n; i++)
KALLADI HSS NOTES BY MUSTHAFA 9544885401
f *= i;
return f;
}
Save this in a file with the name factorial.h and then create a C++ program as follows:
#include <iostream>
#include "factorial.h" //includes user-defined headerfile
using namespace std;
int main()
{
int n;
cout<<"Enter a number : ";
cin >> n;
cout<<"Factorial : " << factorial(n);
}

Questions from Previous Year’s Question Papers

1. Which one of the following is NOT equal to others?

a) pow(64, 0.5) b) pow(2,3) c) sqrt(64) d) pow(3,2)

2. Write a recursive C++ function that returns sum of the first n natural numbers.

3. List any three string functions in C++ and specify the value returned by them.

4. Name the built in function to check whether a character is alphanumeric or not.

5. Read the function definition given below. Predict the output, if the function is called as convert(7);

void convert(int n)

if (n>1)

convert(n/2);

cout<<n%2; }

6. Explain the difference between call-by-value method and call-by-reference method with the help of
examples.

7. Arguments used in call statement are formal arguments. State true or false.

8. Differentiate the string functions strcmp() and strcmpi().

9. Differentiate break and continue statements in C++.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


10. Explain recursive function with the help of a suitable example.

11. Explain Call by Value and Call by Reference methods of function calling with the help of

suitable examples.

12. Suggest most suitable built-in function in C++ to perform the following tasks:

(a) To find the answer for 53.

(b) To find the number of characters in the string “KERALA”.

(c) To get back the number 10 if the argument is 100.

13. A function can call itself for many times and return a result.

(a) What is the name given to such a function?

(b) Write a function definition of the above type to find the sum of natural numbers from 1 to N.

14. Construct the function prototype for the following functions:

(a) The function Display() accepts one argument of type double and does not return any value.

(b) Total() accepts two arguments of type int, float respectively and return a float type value.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 11

Computer networks
Computer network is a group of computers and other computing hardware devices connected to each other electronically
through a communication medium

Need for Network/Characteristics of Network/Advantages of Network

The advantages of computer Network are:

1. Resource Sharing : The sharing of available hardware and software resources in a computer network is called
resource sharing. Eg: Sharing of DVD Player, Printer, Scanner ,Softwares etc.
2. Price- Performance ratio:The cost of resources can be reduced by purchasing the network versions , which can
guarantee the same performance.
3. Communication :Computer network helps to communicate with each other instantly through its services like e-
mail,chat ,video conference etc.
4. Reliability :Computer Network can store the same data in multiple computers within the network. The data lost
from one computer can be retrieved from other computers within the network.
5. Scalability : The computing capacity and storage capacity can be increased or decreased by adding or removing
devices to the system.
Terms in Network

• Bandwidth :Bandwidth is the maximum data-transfer rate in a given amount of time between computers in a
network. Bandwidth is measured in bits per second (bps).
• Noise :The unwanted electrical or electromagnetic energy that lowers the quality of data signals are called Noise.
• Node :Any device connected to a network are called Node.

Data Communication system

The exchange of digital data between any two devices through a medium is known as Data Communication .

The 5 basic elements of a Communication system are :

• Message : It is the information to be communicated such as text, image, audio, video etc.
• Sender : The device that is used for sending message is called Sender or Source or Transmitter.
• Receiver : The computer or device that receives the messages is called the receiver.
• Medium : It is the physical path through which a message travels from the sender to the receiver.
• Protocol : it is the rules under which message transmission takes place between the sender and the receiver.

Communication medium

The medium for data transmission over a computer network is called communication channel or communication medium.
The communication medium are of two types:

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• Guided medium (Wired)
• Unguided medium (Wireless)

Guided medium (Wired)

Guided medium or wired medium uses physical wires or cables for data tramnsmission.The different types of cables used
for networking are:

• Twisted Pair Cables (Ethernet cables).


• Coaxial Cables.
• Optical fibre cables(OFC).

❖ Twisted pair cable or Ethernet cable


• Most widely used media in small networks.
• It consist of 4 pair colour coded cables , which are covered by an outer shield.
• They are of two types:
 Unshielde Twisted pair cables (UTP).
 Shielded Twisted Pair cables (STP).
 Unshielded Twisted pair cables
In UTP the individual pair cables are not shielded
Characteristics of UTP cable
• Low cost cable available for setting up small networks.
• Thin and flexible cable.
• Ease of installation.
• Carries data upto a length of 100 m at a stretch.
 Shilded Twisted Pair cables (STP)
In STP, each pair cables are shielded individually. An outer shield then covers all the pair of cables.
Characteristics of STP cable:
• Immunity against noise.
• It is more expensive than UTP.
• STP cable is difficult to install.
✓ An RJ-45 connecter is used to connect UTP/STP twisted pair cable to a computer.
❖ Coaxial cable
A coaxial cable consists of an inner conductor surrounded by a tubular insulating layer which is further covered by a
tubular conducting shield. It has an outer insulation to protect the cable too.

Characteristics of coaxial cable


• Carries data to longer distances.
• High bandwidth.
• Less electromagnetic interference.
• Thicker than twisted pair.
• Less flexible than twisted pair.
• Difficult to install than twisted pair cable.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
❖ Optical fibre cable
Optical fibres cable uses long thin glass fibres to transmitt data as light signals.Data travels as fast as light and can
be transmitted tolong distances.

Optical fibre has the following parts:


• Core - the thin glass rod at the centre through which the light travels.
• Cladding - the outer optical material surrounding the core that reflects the light back into the core.
• Coating - the plastic coating that protects the cable from damage and moisture.

Characteristics of optical fibre cable


• High bandwidth.
• Carries data over a very long distance.
• High immunity against noise.
• The most expensive and the most efficient communication media.
• Installation and maintenance are difficult and complex.

Unguided medium (Wireless)

Electromagnetic waves are used for wireless communication on computer networks. Based on their frequencies ,
electromagnetic waves are categorized into:
• Radio waves.
• Micro waves.
• Infrared Waves.
1. Radio waves.
• Radio waves have a frequency range of 3 KHz to 3 GHz.
• Radio waves can be used for short and long distance communication.
• These waves can penetrate solid objects.
• They are used in Cordless phones, AM and FM radio broadcast and mobile phones…
• Radio Waves can be transmitted in all directions.
• Relatively inexpensive than wired media.
• Transmission can be affected by motors or other electrical equipment(Not Secure).
• Legal permission is needed.

2. Micro waves
• Microwave have a frequency range of 300 MHz to 300 GHz.
• Microwaves travel in straight lines and cannot penetrate solid objects.
• Transmitting and receiving antennas need to be in a straight line.’
• Relatively inexpensive than wired media.
• Offers ease of communication over difficult terrain.

3. Infrared waves
• Infrared waves have a frequency range of 300 GHz to 400 THz.
• These waves are used for short range communication (approx. 5 m).
• Used in monitoring and control applications.
• A line of sight transmission is needed(Secure).
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• Only two devices can communicate at a time.
• The waves cannot cross solid objects.

Wireless communication technologies using radio waves


The wireless technologies using radio waves are
• Bluetooth.
• WiFi
• WiMAX
• Satellite link.

1. Bluetooth.

• Bluetooth technology uses radio waves in the frequency range of 2.402 GHz to 2.480 GHz.
• This technology is used for short range communication (approx. 10 m) .
• Used in Cell phones, laptops, mouse, keyboard, tablets, headsets, cameras, etc..
• Line of sight between communicating devices is not required.
• Bluetooth can connect upto eight devices simultaneously.
• Slow data transfer rate (upto 1 Mbps).

2. WiFi
• Wi-Fi network makes use of radio wave in the frequency range of 2.4 GHz to 5 GHz.
• The wireless adapter in a computer translates data into radio signal and transmits it using an antenna. A
wireless router receives the signal ,decodes it and send it.
• Wifi technology is widely used to share Internet connection.
• Line of sight between communicating devices is not required.
• Data transmission speed is upto 54 Mbps.
• Wi-Fi can connect more number of devices simultaneously.
• Used for communication upto 375 ft (114 m).

3. WiMAX
• Worldwide Interoperability for Microwave Access (Wi-MAX) has a frequency range of 2 GHz to 11 GHz.
• Wi-MAX can provide high-speed wireless Internet access over very long distances(45 km).
• Wi-MAX equipment exists in two basic forms - base stations, installed by service providers , and receivers,
installed by clients.
• Hundreds of users can connect to a single station.
• Provides higher speed connection upto 70 Mbps.
• Line of sight between communicating devices is not required.
• Weather conditions like rain, storm, etc. could interrupt the signal.
• Very high power consumption and high costs of installation.

4. Satellite Link
• Used for long distance wireless communication.
• Signal travels in a straight line and is not able to bend around the globe.
• Signals is sent to satellites and then redirected to another satellite or directly to a far away destination.
• Transmission of signals from the earth to a satellite is called uplink.
• Transmission of signals from satellite to the earth is called downlink.
• This system is expensive.
• Requires legal permission and authorization.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Data communication devices

A data communication device provides an interface between computer and the communication channel. Data
Communication devices are NIC , Hub , Switch , Bridge , Router , Gateway ….

1. Network Interface Card (NIC)


• Network Interface Card (NIC) provides hardware interface between a computer and a network.
• NIC can prepare, send, receive and control data on the network.
• It breaks up data into manageable units, translates protocols etc.
• NIC are of two types - NIC card and wireless NIC card.

2. Hub
• A hub is a device used to connect several computers of the same network .
• It is a small, simple, passive and inexpensive device
• When NIC of one computer sends data packets to hub, the hub transmits the packet to all other computers
connected to it.
• The intended computer accept it and others will discard.
• It increases the network traffic and reduces the effective bandwidth.

3. Switch
• A switch is an intelligent device that can connects several computers.
• It looks exactly like a hub.
• Switches are capable of determining the destination and redirect the data only to the intended node.
• Switch performs this by storing the addresses of all the devices connected to it using a table.

4. Repeater
• Repeater is a device that receives incoming data signals, amplifies the signals to their original
strength and retransmits them to the destination.

5. Bridge
• A bridge is a device used to segmentize a network.
• An existing network can be split into different segments and can be interconnected using a bridge.
• This reduces the amount of traffic on a network.
• When a data packet reaches the bridge, Only those packets addressed to other side, will be allowed to pass
the bridge. Others will be discarded. The packet that passes the bridge will be broadcast to all nodes on the
other side.

6. Router
• A router is a device that can interconnect two networks of the same type using the same protocol
• It can find the optimal path for data packets to travel and reduce the amount of traffic on network.
• The router check the device address and the network address ,and use algorithms to find the best path for
packets to reach the destination.

7. Gateway
• A gateway is a device that can interconnect two different networks having different protocols.
• It can translate one protocol to another protocol.
• It is a network point that acts as an entrance to another network

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Data terminal equipments

A data terminal equipment (DTE) is a device that controls data flowing to and from a computer. Most commonly used DTEs
are Modem and Multiplexer.

1. Modem
• A modem is an electronic device used for communication between computers through telephone lines.
• It converts digital signals received from a computer to analog signals (modulation) for telephone lines.
• It also converts the analog signals received back from telephone lines to digital signals (demodulation).
• The speed of modem is measured in bits per second (bps).

2. Multiplexer/Demultiplexer
• Multiplexing is sending multiple signals on a physical medium at the same time in the form of a single signal and
then recovering the separate signals at the receiving end.
• Multiplexer is a device that combines (multiplexes) the inputs from different sources and sends them through
different channels of a medium.
• At the destination, a demultiplexer separates (demultiplexes) the signals.

Network Topologies

The way in which the nodes are physically interconnected to form a network is called a Topology. Major topologies are bus,
star, ring and mesh.

1. Bus topology
• In bus topology all the nodes are connected to a main cable called bus.
• If a node has to send data to another node, it sends data to the bus. The signal travels through the bus. All nodes
check the bus, and only the node for which data is addressed accepts it.
• A small device called terminator is attached at each end of the bus. When the signal reaches the end of the bus, the
terminator removes the signal.
• Easy to install.
• Requires less cable length
• It is cost effective.
• Failure of a node does not affect the network
• Failure of cable (bus) or terminator leads to a break down of the entire network.
• Fault diagnosis is difficult.
• Only one node can transmit data at a time.

2. Star Topology
• In star topology each node is directly connected to a hub/switch.
• If any node has to send some information to any other node, it sends the signal to the hub/switch. This signal is
then broadcasted (in case of a hub) to all the nodes but is accepted only by the intended node. In the case of a
switch, the signal is sent only to the intended node.
• More efficient compared to bus topology.
• Easy to install.
• Easy to diagnose faults.
• Easy to expand depend.
• Failure of hub/switch leads to failure of entire network.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• Requires more cable length compared to bus topology.

3. Ring topology
• In ring topology, all nodes are connected using a cable in the form of ring or circle. A ring topology has no start and
no end.
• Data travels only in one direction in ring.
• While they are passed from one node to the next, each node regenerates the signal.
• The node for which the signal is intended reads the signal. After travelling through each node, the signal reaches
back to the sending node from where it is removed.
• Requires less cable length and hence is cost effective.
• If one node fails, entire network will fail.
• Addition of nodes to the network is difficult.

4. Mesh topology
• In mesh topology, every node is connected to other nodes. So there will be more than one path between two
nodes .
• If one path fails, the data will take another path and reach the destination.
• Network will not fail even if one path between the nodes fails.
• Expensive because of the extra cables needed.
• Very complex and difficult to manage.

Types of networks
On the basis of the area covered, computer networks are classified as:
• PAN - Personal Area Network
• LAN - Local Area Network
• MAN - Metropolitan Area Network
• WAN -Wide Area Network

Personal Area Network (PAN)


• PAN is a network of communicating devices in the proximity of an individual. It can cover an area of a radius with
few meters.
Local Area Network (LAN)
• LAN is a network of computing and communicating devices in a room, building, or campus. It can cover an area of
radius with a few meters to a few Kilometers. A networked office building, school lab etc are example for LAN.
• LAN can be set up using wired media or wireless media . If a LAN is setup using unguided media, it is known as
WLAN (Wireless LAN).
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Metropolitan Area Network (MAN)
• MAN is a network of computing and communicating devices within a city. It can cover an area of a few Kilometers
to a few hundred Kilometers radius. All types of communication media (guided and unguided) are used to set up a
MAN
Wide Area Network (WAN)
• WAN is a network of computing and communicating devices crossing the limits of a city, country or continent. It can
cover an area of over hundreds of Kilometers in radius.
• WAN usually contain a number of interconnected individual computers, LANs, MANs and maybe other WANs.
• Largest WAN is the Internet.
• A network of ATMs is another example.

Logical classification of networks


This classification is based on the role of computers in the network network are classified into :
• peer-to-peer
• client-server.
Peer-to-Peer
• A peer-to-peer network has no dedicated servers.Any computer can act as a client or as a server at any time.
This network is ideal for small networks.

Client-Server
• The client-server architecture consists of high configured computer (called server) serving lower configuration
machines called clients. A server provides clients with specific services when client requests.
• Client-server architecture is an example for centralized software management. When software is loaded on
the server and shared among the clients, changes made to the software in the server will reflect in the clients
also.

Classifications for servers are


a) File server - A computer that stores and manages files on a network.
b) Web server - A computer dedicated to responding to requests for web pages.
c) Print server - Redirects print jobs from clients to specific printers.
d) Database server - Allows clients to view, modify and delete data in a database.

Identification of computers over a network


MAC Address and IP address are used to identify computers on a network.

Media Access Control (MAC) address


• A Media Access Control (MAC) address is a universally unique 12 digit hexadecimal address assigned to each NIC
(Network Interface Card) by its manufacturer.
• MAC address of an NIC is permanent and never changes. MAC addresses are 12-digit hexadecimal (or 48 bit
binary) numbers.
• MAC addresses are usually written in one of the following two formats:
MM : MM : MM : SS : SS : SS or MM – MM – MM – SS – SS – SS
• The first half (MM:MM:MM) of a MAC address contains the ID number of manufacturer. The second half
(SS:SS:SS) represents the serial number assigned to the NIC.

Internet Protocol (IP) address


• An IP address is a unique 4 part numeric address assigned to each node on a network.
• IP address is assigned to each machine by the network administrator or the Internet Service Provider.
• An IP address is a group of four bytes (or 32 bits) each of which can be a number from 0 to 255. IP addresses are
normally expressed in decimal format .

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• There are two versions of IP addresses: version 4 (IPv4) and version 6 (IPv6). IPv4 uses 32 bits and IPv6 uses 128
bits for an IP address.

Network protocols
A network protocol is the set of rules to be followed in a network when devices in the network exchange data with
each other. Some commonly used protocols are TCP/IP, SPx/IPx, BGP etc.

TCP/IP
• TCP/IP, Transmission Control Protocol/Internet Protocol, is a container of communications protocols used to
interconnect network devices on the local networks and the Internet.
• TCP/IP defines rules for how electronic devices should be connected to the Internet and how data should be
transmitted between them.

Working of TCP/IP:
Step 1: TCP at the sender breaks the data into packets along with the address of the receipient and send the data.
Step 2: Routers Transport and route the data to their destination according to IP.
Step 3: TCP at the receiver’s side reassembles the packets to form original data

HTTP
• HTTP stands for Hypertext Transfer Protocol. It is a standard protocol for transferring requests from client-side and
to receive responses from the server side.
• The HTTP client (browser) sends a HTTP request to the HTTP server (web server) and server responds with a HTTP
response. This pair of request and response is called an HTTP session

The two important characteristics of HTTP are


1. HTTP is transmission medium independent.
2. HTTP is stateless (The server and client are aware of each other only during a request or response. Afterwards, each
forgets the other).

FTP
FTP ( File Transfer Protocol ) is a protocol for exchanging of data and program files across a network. FTP is the easiest
way to transfer files between computers via the Internet. FTP client softwares are Filezilla, Cute FTP,etc.

DNS
DNS stands for Domain Name System. DNS returns the IP address of the requested domain Name. DNS implements a
database to store domain names and IP address of all web sites on the Internet.

Uniform Resource Locator (URL)


URL stands for Uniform Resource Locator. URL is a formatted text string to identify network resources on the Internet.
Every resource on the Internet has a unique URL. URL string can be divided into three parts.
a) Network protocol
KALLADI HSS NOTES BY MUSTHAFA 9544885401
b) Domain name
c) File name
For example the URL http://www.dhsekerala.gov.in/index.html .

a) Protocol
It specifies what protocol is used to access the information specified in the domain.
b) Domain name
Domain name is the name assigned to a server through the Domain Name System (DNS). Domain names are used
in URLs to identify the particular web server.
A domain name usually has more than one part: Top level domain name or primary domain name and sub-
domain name(s).
There are only a limited number of top level domains and these are divided into two categories: Generic Domain
Names and Country-Specific

Generic Domain Names Country Specific Domain Names


.com Commercial business .in India
.edu Educational institutions .au Australia
.gov Government agencies .ca Canada
.mil Military .ch China
.net Network organizations .jp Japan
.org Organizations (nonprofit) .us United States of America

c) File name
It specifies the file to be opened. In the above example 'index.html' is the file that is to be accessed from the web
server specified by the domain name.

Previous Questions

1. Identify the name given to the physical arrangement of computers in a network? Explain two types with block
diagrams. (March 2015) Score 3
2. Write any two advantages of Network. (March 2015) Score 2
3. What are the advantages of Wi-Fi network? (March 2015) Score 2
4. In communication system the term source refers to …….. … (SAY 2016 June) Score 1
5. Explain the following terms in computer networking a). Node b). Bandwidth c). Noise (SAY 2016 June) Score 3
6. Match the following
A B
Unguided Media org
Generic Domain Name Coaxial cable
Guided Media microwave
Protocol http (March 2016) Score 2
7. Compare ring topology and mesh topology (March 2016) Score 3
8. "Client-server architecture is an example of centralized software management." Justify. (March 2016) Score 2
9. If all devices are connected to a central switch/hub, the topology is known as……..(SAY 2016 June) Score 1
10. List any four advantages of forming computer networks. (SAY 2016 June) Score 2
11. A device that regenarate the incomimg signal and retransmit them to their destination is called …….. (Imp 2015 )
12. Which of the following communication technology is the slowest a) Bluetooth b) Wi-Fi c) Wi Max d)Satelite Link
(Imp 2015 ) Score 1
KALLADI HSS NOTES BY MUSTHAFA 9544885401
13. Consider your teacher planning to connect the computers in the computer lab of your school to form a network. a).
He has a switch and a hub to connect these computers. Which will you prefer? Why? (Imp 2015 ) Score 2
b). Name the topology you will suggest for this network. Give reason for your suggestion. (Imp 2015 ) Score 3
14. Internet is an example of _____. a) MAN b) PAN c) WAN d) LAN (1) (July 2017)
15. Explain the advantages of forming networked computers than keeping them standalone computers. (3)

16. a) Different networks with different protocols are connected by a device called …………
(i) Router (ii) Bridge (iii) Switch (iv) Gateway (1) (March 2017) b) Define protocol. (1) (March 2017)
17. Compare any three types of networkbased on span of geographical area. (3) (March 2017)
18. Write notes on the following: a) IP address b) MAC address c) Modem (3) (Sept. 2016) 7. Define network topology.
Explain any four network topologies in detail. (3) (Sept. 2016)
19. Identify the type of LAN topology in which there are more than one path between nodes. (a) Star (b) Ring (c) Mesh
(d) Bus (1) (March 2016)
20. Any device which is directly connected to a network is generally known as _____. (1) (March 2015)

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Chapter 12

INTERNET AND MOBILE COMPUTING


History of INTERNET

▪ ARPANET-(Advanced Research Project Agency Network.) was a Project by American Defence Department,
which is considered as the first Wide Area Network that used TCP/IP protocol for communication.

▪ MILNET-Network separated from ARPANET exclusively for military defence department.

▪ ARPANET combined many other network to form a WAN, which becomes the Internet.

▪ Vint Cerf is considered as the father of Internet.

▪ TIM BERNERS LEE is considered as Founder of WWW , Founder of HTTP, founder of Web server and Web
browser technology and Founder of HTML.

Internet

▪ Internet is the largest public network in the world.


▪ Internet is an Interconnected system of computer networks that serves the users of all over the world.

Intranet

▪ Intranet is a private network within an organization , that uses TCP/IP protocol for communication.

Extranet

▪ The Intranet that is accessible to some computers that IS not part of a company’s private network is called
Extranet.

Connecting Computer to Internet


To connect a Computer to Internet we need the following hardware and software.
* Computer with NIC Card.

* Operating system that supports TCP/IP.


* Modem.
* Telephone Connection.
* An Internet account given by ISP.
* Software like Browsers,Client Applications etc.

Data Transfer Rate


It is the Average number of bits transferred between devices in Unit time.It is Calculated in “bps”.

1 kbps = 1000 bits per second.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


1 Mbps =1000 kbps
1 Gbps =1000 Mbps.

Types of Internet Connectivity


Internet connectivity is classified based on the speed of the connection and the technology used. They can be
broadly classified as dialup connectivity, wired broadband connectivity and wireless broadband connectivity.

▪ Dial-Up Connectivity.
▪ Wired Broadband.
*ISDN * Cable Internet
* DSL * Leased Line * FTTH
▪ Wireless Broadband Connectivity
*Mobile Broadband *WiMax
*Satellite broadband.
➢ Dial-Up Connectivity
▪ Uses Telephone line and Dialup modem to dial and connect to the server at the ISP.
▪ Connecting time is high.
▪ Uses 56kbps DialUp Modem
▪ Slow connection, speed upto 56 kbps.
▪ At a time Data or voice call is possible.
➢ Wired Broadband Connectivity
▪ Always-on Connection.
▪ Uses Broadband Modem- allows to use telephone and Internet(call and data at the same time)
▪ High speed conncetion (256 kb -100 Mb)
▪ Popular broadband technologies are:
*ISDN
*Cable Internet
*DSL
*FTTH
*Leased Line
Dial-Up Connection Wired broadband Connection
• Slow connection, speed upto • High speed connection,speed higher
56kbps than 256kbps.
• Always on connection.
• Requires dialing to connect to ISP • Simultaneous use of voice and
• Use telephone line exclusively. Internet.
• Use dial up modem. • Used broadband modem.

Integrated Service Digital Network (ISDN)


• Capable of transporting Voice and Data simultaneously.
• It Uses two lines- one for Data and One for Voice or both for data.
• Data transfer rate upto 2 mbps.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Cable Internet
• It provide Internet access through the coaxial cable laid for cable TV connection to our Homes.
• Requires Cable Modem.
• It provide data transfer rate between 1 mbps and 10 Mbps.

DSL- Digital Subscriber Line


• It provide Connection to Internet through Standard Telephone Lines .
• It Uses copper wire for data transmission.
• It is capable of transmitting Data and voice simultaneously.
• ADSL (Asymmetric DSL) is the most common from of DSL.
• It Require ADSL Modem.
• Provide data transfer rate between 256 kbps to 24 mbps

Leased Line
• It provide dedicated lines to provide Internet to ISPs,large organizations etc.
• It can provide data transfer rate upto 100 mbps.
• It is very expensive
FTTH-Fibre To The Home.
• It Uses optical fibre cable for data transmission.
• Provides high speed internet connection.
• It needs a NTU-Network Termination Unit which is to be connected to FTTH Modem that is
connected to the Computer.
• It can provide high speed internection to homes/institutions/organizations etc..

➢ Wireless Broadband Connectivity


• Capable of provide same speed as Wired broadband.
• Popular wireless Broadband are
* Mobile Broadband
* WiMax
* Satellite Broadband
Mobile Broadband
• It is the wireless internet accessing using mobile phones, tablets , USB wireless modem etc.. that
have inbuilt wireless modem.
• It allow the user to access internet from anywhere.

Wi-Max
• WiMax can provide internet connectivity to a distance around 50 Kms with a speed upto
70Mbps.
• Connectivity is provided using the devices like WiMax handsets,USB dongles etc.. that have
WiMAX modem.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


Satellite Broadband
• It provide internet connectivity through Satellite.
• A VSAT antenna and Tranceiver is required at the users location.
• High speed and highly expensive.

Internet Access Sharing Methods


The internet access sharing methods are 1.Using LAN 2.Using WiFi network 3.Using Lifi.

▪ Using LAN

Internet connected to a computer in Local Area Network(LAN) can be shared among other computers in
the network .This can be done using Proxy server or Router.

▪ Using Wi-Fi network

Provide Internet connectivity through a wifi router or a network access point called hotspot.Wifi is a short
distance data transmission technology .

▪ Using Li-fi Network

It uses visible light for data transmission.The main component is a LED that can transmit data and a photo
diode as the receiver. A data rate of 100mbps is possible Using LiFi technique.

Services on the Internet


Different services on the internet are:

1. WWW-World Wide Web 2. E-mail 3.Search Engines 4.Social Media

1. WWW-World Wide Web

▪ WWW is a system of interlinked hypertext documents that can be accessed via Internet.

▪ It is a Client-Server System where Server contains a collection of documents which can be accessed using
URL.

▪ The Documents may contain Text, image, Video,Audio etc.

▪ Documents are created using HTML.

▪ Client Access the Documents using Browsers.

→Web Browser

• It is a Software used to Retrieve/ Present Information to and from web pages in the www.
• It can display images ,videos,audios, hyperlinks etc.
KALLADI HSS NOTES BY MUSTHAFA 9544885401
• It allows user to navigate through web pages of www.
• Eg: Mozilla Firefox ,Google Chrome ,Opera ,Safari ,Internet Explorer….

→Web Browsing

Traversing through the web pages of World wide web is called Web Browsing.

▪ Step 1 : Browser send the Domain name to the DNS server .

▪ Step 2 :DNS server returns the IP corresponding to the requested Domain name.

▪ Step 4:Browser connects to the server and request a web page (HTTP Request)

▪ Step 6: Web server returns the requested web page in HTML format.

▪ Step 7:Browser Format and displays the web page to the user.

1. Search Engines

▪ A web search engine is a software system that is designed to search for information on the World Wide
Web.

▪ They search web pages for the given keyword and return a list of URL of web pages matching the keyword.

▪ Web Crawlers or Spiders are Programs search web pages and find possible keywords.

▪ Working

1. Web crawler contineosly searches through the web and collect possible keywords to build a search
index.
2. When user searches a keyword, Search engine searches in the Search index are returs the list of URLs
that contains the keyword.

3. Electronic Mail or “e-mail”

▪ E-mail is the exchange of digital message between computers over the Internet.

▪ We can also include images ,videos , audio, documents etc in our mail along with texts.

▪ Founder of e-mail—Ray Tomilson

▪ Structure of an e-mail address is : [email protected] eg: [email protected]


KALLADI HSS NOTES BY MUSTHAFA 9544885401
▪ Username can be any available name that didn’t used yet,

▪ Domain name can be gmail.com, yahoo.com, reddiff.com,hotmail.com etc

Protocols used in e-mail

▪ POP- Post Office Protocol -Protocol used to receive e-mails(POP3 is used).

▪ IMAP-Internet Message Access Protocol -Protocol used to receive e-mails.

▪ SMTP-Simple Mail Transfer Protocol -e-mail transmission protocol across internet.

Sections of an e-mail

To - To specify the email address of the primary receipient.

Cc (carbon copy)- specifies the secondary recipient.

Bcc (Blind Carbon Copy)-specifies the email address of tertiary recipient.

Subject- To provide a Meaningful subject for your Conversation.

Content – The matter to be sent id typed here.

Attachment- Allows you to send image, audio,video,documents along with text.

Send/Compose -Button used to send the message.

Forward- To send the received message.

Reply –To give reply back to the received message.

Working of e-Mail

1. Sender composes the message using email client and Uploads to the SMTP server.
2. Message travels through the internet.
3. Recipients email client checks for new messages and download new message.
4. Message is placed at the recipient’s inbox.
5. Recipient opens and reads the message using email client.

Advantages of email

1. Speed -Instant Delivery of Messages.

2. Easy to Use -Send,Receive,Save,Organize messages

3. Provision for Attachment.

4. Environment friendly- No need of paper.

5. Easy to Reply using Reply button.


KALLADI HSS NOTES BY MUSTHAFA 9544885401
6. Cost Effective.

7. Available Anywhere Anytime

DisAdvantages of e-mail

▪ E-mail may carry viruses

▪ Junk mails-Deleting junk mail is time consuming

4. Social Media
Social media refers to the use of mobiles and web based technologies through which individuals can
create,share ,discuss and modify contents.

Classiification of Social media

1. Internet Forums
An Internet forum is an online discussion web site where people can engage in conversations in the form of
posted messages
Eg for internet forums : Ubuntu forum , Mi Forum etc.
2. Social blogs
A blog (web log) is a discussion or informational website consisting of entries or posts displayed in the
reverse chronological order.
Eg: Blogger.com ,Wordpress.com .

3. Microblogs
Microblogs allow users to exchange short sentences, images or video links. People use microblogs to share
what they observe in their surroundings.
Eg: Twitter.com
4. Wikis
Wikis allow people to add content or edit existing information in a web page, to form a community
document.
Eg : wikipedia.org
5. Social networks
Social networking sites allow people to build personal web pages and then connect with friends to
communicate and share content. We can share text, pictures, videos, etc. and comment to the posts.
Eg : Facebook.com , LinkedIn , Instagram
6. Content communities
Content communities are websites that organise and share contents like photos,videos, etc.
Eg : Youtube.com ,Flickr.com

Advantages of social media

KALLADI HSS NOTES BY MUSTHAFA 9544885401


1. Bring people together: Social networking allows people to find long-lost childhood friends and make new
ones.
2. Plan and organise events: These sites help users to organise and participate in events.
3. Business promotion
4. Social skills: These sites allow people to express their views over a particular issue.

Limitations in use of social media

1. Intrusion to privacy:
2. Addiction
3. Spread rumours

Social media interaction – Best practices


1. Avoid unnecessary uploading of personal data
2. Setting time schedule for using social medias
3. Set privacy level to private or friends.
4. Avoid posting content you may regret later.

Cyber Security
Cyber security refers to the security of computer systems and computer networks against cyber attacks.

Cyber Attacks

1. Computer virus
• A computer virus is a program that attaches itself to another program or file.
• Virus can spread from one computer to another without our knowledge and interferes the normal
operation of a computer.
• A virus might corrupt or delete data on our computer, replicate itself and spread to other computers.
2. Worm
• A computer worm is a stand alone malicious software that can replicate itself and spread to other
computers.
• Worms can spread from one computer to canother on its own.
• A worm can send a copy of itself to every address in an e-mail address book.
• Worms mainly do attack on Networks.
3. Trojan horse
• A Trojan horse is a program that appear to be a useful software and do damage once run on the
computer.
• Trojans cannot reproduce by itself.
• When a Trojan is activated on a computer, they can cause serious damage to our computer system.
4. Spam

KALLADI HSS NOTES BY MUSTHAFA 9544885401


• Spams or junk mails are unwanted e-mails sent contineously to persons to promote a product or
service.
• Spammers collect e-mail addresses from chat rooms, websites, customer lists,news groups, etc.
• Clicking on links in spams may send user details to websites that host certain viruses.
5. Hacking
• Hacking is a technical effort to manipulate the normal behavior of computer systems and computer
networks.
• Hacking is performed both by computer security experts and by computer criminals.
• Ethical hacking :Perform hacking to test the security and find the faults in computer networks and
computer system is refered to us Ethical hacking.
Types of Hackers
• The Computer experts who perform hacking to test the security of computer networks and
computer systems are Called White Hats.
• The Computer criminals who break the secure networks to destroy data or to make the network
unusable are called Black Hats.
• The Computer experts who access network illegally to identify its faults are refered to us Gray Hats.

6. Phishing
• Phishing is an attempt to acquire information such as usernames, passwords and credit card details
by posing as the original website.
• Phishing websites have URLs and home pages similar to their original ones.
• The act of creating such a misleading website is called spoofing
7. A Denial of Service(DoS)
• It is an attack on web server whose intension is to deny the service Provided by the Server to the
users.
• The attackers’ goal is to shut down the target server rather than stealing data.
• DoS and DDoS.
• The Hacked computers that are used for DoS attack are called Zoombies.
8. Man-in-the-Middle attacks
• It refers to the attack in which Attacker capture and modifies the transmitting messages between
the sender and receiver.
• To prevent this type of attack use encrypted connections such as HTTPS , SFTP etc..

Preventing network attacks

• Different Network attack defense and detection mechanisms are:


1. Firewall
2.Anti-Virus Software

Firewall

▪ A firewall is a system of computer hardware and software.

KALLADI HSS NOTES BY MUSTHAFA 9544885401


▪ A firewall controls the incoming and outgoing network traffic by analysing the data and determining
whether they should be allowed to enter or not.

Anti Virus Tools/Scanners

▪ Antivirus tools are the programs that are used to detect and remove malware programs.(Virus , Worm ,
Trojan).

▪ Anti-virus software scans files in the computer system for known viruses and removes them if found.

▪ Quarantine is a special area for storing files probably infected with viruses.(Sandboxing).

Cookies

▪ Cookies are small text files that are created within the browser when we visit a website.

▪ Cookies keep track of our movements within the website – remembers our user name, preferences, e-
mail address, etc.

▪ Browsers store cookies for an interval of time.

▪ Websites use cookies mainly because they save time and make browsing efficient.

Guidelines for using computers over Internet

▪ Open e-mails from trusted sender.

▪ Download files only from reputed sources.

▪ Avoid clicking on pop-up advertisements.

▪ Use USB drives with caution.

▪ Make sure the firewall is set and turned on.

▪ Use strong passwords.and Change it at regular intervals.

▪ Update AntiVirus programs periodically.

▪ Be careful about giving personal data online

▪ Make sure that bank web sites start with “https”

Internet of Things

▪ It refers to the Electronic Devises that reminds You.

▪ It includes automatic Call to Super Market when need some things , Call a Doctor when needs etc...

Mobile Computing
KALLADI HSS NOTES BY MUSTHAFA 9544885401
▪ Mobile computing is a technology that has computing capability and can transmit/receive data from
where ever they are.

▪ It Requires

1. Portable computing Devices like Laptops,Mobiles.

2. Wireless communication network.

3. Connectivity to Internet.

Mobile Communication

▪ Mobile communication devices does not require any physical connection for communication.

Generations in Mobile Communication

First Generation Networks-

▪ It was developed around 1980s.


▪ 1G mobile phones were based on analog system and provides voice facility only.

Second Generation Networks

▪ 2G Networks Follow Digital system for communication and improved audio quality in transmission.

▪ In 2G Networks ,Phone conversations are digitally encrypted.

▪ Supports both data and voice.

▪ Picture messages and MMS were introduced during this generation.

▪ Popular Standars in 2G are:

* GSM-Global system for Mobile

* Code division Multiple Access(CDMA).

GSM-Global system for Mobile

▪ Globally Accepted standard for digital commn.

▪ Uses Narrowband TDMA(Time Division Multiple Acces), provides simultaneous call on same radio
frequency.

▪ Network is identified using SIM(Subscriber Identity Module)

▪ Expanded with improved performance with data communication using GPRS(General Packet Radio Service)
and EDGE(Enhanced Data Rate for GSM Evolution ).

CDMA - Code Division Multiple Access

KALLADI HSS NOTES BY MUSTHAFA 9544885401


▪ Several transmitters can send information simultaneously over a single communication channel.

▪ It offers wider coverage and better quality even in low signal.

▪ CDMA Provide Better voice quality and security.

Third Generation Networks-3G

▪ 3G Networks Provides high data transfer rates.

▪ It oxcffers multimedia services combining voice and data.

▪ Access part in 3G network uses WCDMA(Wideband CDMA)

▪ It needs the mobile towers to be close to each other.

Fourth Generation Networks-4G

▪ 4G is also called L.T.E(Long Term Evolution ),Provides ultra broadband internet to mobiles.

▪ 4G Offers high speed internet and high quality video streaming applications

▪ The Access part uses OFDMA(Orthogonal Frequency Division Multiple Access).

Mobile Communication Services


Popular mobile communication technologies are:

▪ SMS – Short Message Service.

▪ MMS – Multimedia messaging Service.

▪ GPS- Global Positioning System.

▪ Smart Cards

1. Short Message Service(SMS)


• It is the Text messaging service in mobile communication.
• SMS can exchange only 160 characters per message.
• SMSC- Short Message Service Center Stores and Forward the message to the recipient..
• SMS messages are exchanged using SS7 protocol (Signalling System No.7)
2. MMS-Multimedia Messaging Service
• MMS is a standard way to exchange message that consist multimedia contents such as image
audio video etc...
• No limit on the multimedia message size.
• MMS Server is responsible for storing and handling incoming and outgoing messages

KALLADI HSS NOTES BY MUSTHAFA 9544885401


3. GPS –Global Positioning System
• Satellite based navigation system that is used to locate a geographical position anywhere on earth.
• The system behind GPS is a group of satellites that are continuously orbiting the earth.These
satellites transmit radio signals to GPS receivers.
4. Smart Card
• Smart card is a Plastic card embedded with a computer memory/chip that stores and transacts
information.The advantage of using smart cards are:
▪ Data is Secure
▪ Intelligent
▪ Easy to carry.
• Used in SIM,ATM cards,Health Cards, Identy cards etc.

Mobile Operating System

• A mobile operating System is the Operating system used in mobile devices such as smart phones , tablets
etc.
• A mobile Operating System manages the hardware , multimedia functions ,Internet connectivity etc in a
mobile device.
Eg:-
• Android From Google
• iOS From Apple
• BlackBerry OS from BlackBerry
• Windows Phone from Microsoft

Android Operating System.

▪ Android is a Linux based Operating system designed for touch screen mobile devices.
▪ Android was developed by Andy Rubin and later Google acquired Android.
▪ User interface of Android is based on touch inputs like swiping, tapping ,pinching etc.
▪ Android allows users to customize their home screen with shortcuts to applications and widgets.

Android Versions
KALLADI HSS NOTES BY MUSTHAFA 9544885401
Version Name Version Name
1.5 Cupcake 4.4 Kitkat
1.6 Donut 5.0 Lollipop
2.0 Éclair 6.0 Marshmallow
2.2 Froyo 7.0 Nougat
2.3 Gingerbread 8.0 Oreo
3.0 Honeycomb 9 Pie
4.0 Ice cream Sandwitch 10 Android 10
4.1 Jelly Bean 11,12,13,14…..

KALLADI HSS NOTES BY MUSTHAFA 9544885401

You might also like