0% found this document useful (0 votes)
38 views241 pages

Ca Merged Compressed 1650254421

The document provides lecture notes on computer organization, defining a computer and its evolution from early devices like the abacus to modern computers. It outlines the generations of computers from the first to the fifth, detailing their characteristics and advancements in technology. Additionally, it classifies computers based on function, operation, power, size, and purpose, highlighting different types such as analog, digital, and hybrid computers.

Uploaded by

delejee14
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)
38 views241 pages

Ca Merged Compressed 1650254421

The document provides lecture notes on computer organization, defining a computer and its evolution from early devices like the abacus to modern computers. It outlines the generations of computers from the first to the fifth, detailing their characteristics and advancements in technology. Additionally, it classifies computers based on function, operation, power, size, and purpose, highlighting different types such as analog, digital, and hybrid computers.

Uploaded by

delejee14
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/ 241

S.K.D.A.V.

GOVERNMENT POLYTECHNIC,
ROURKELA-12

LECTURE NOTES
ON
COMPUTER APPLICATION
SEM-1ST/2ND
BRANCH-COMMON TO ALL

PREPARED BY STELLA KUJUR


LECTURER IN CSE
UNIT-1
COMPUTER ORGANISATION

INTRODUCTION TO COMPUTER

Def1: “A computer is a machine that can be instructed to

carry out sequences of arithmetic or logical operations

automatically via computer programming.”

According to Wikipedia.

Def2: A computer is a machine or device that performs processes, calculations and operations based on
instructions provided by a software or hardware program. It is designed to execute applications and provides
a variety of solutions by combining integrated hardware and software components.

Def3: computer is an electronic device, which stores data and processes information based upon the
instructions provided by the user and generates the desired output. A computer is a device that computes or
calculates numbers, however, does more than that.

Def4: A computer is a programmable electronic device that accepts raw data as input and processes it with a
set of instructions (a program) to produce the result as output.

The term "computer" is derived from the Latin word "computare" which means to calculate.

A computer is designed to execute applications and provides a variety of solutions through integrated
hardware and software components. It works with the help of programs and represents the decimal numbers
through a string of binary digits.

EVOLUTION OF COMPUTERS
History of Computers

In 1640s, Computer term was first used as "one who calculates." From 1897, term changed and got a
new computer meaning "Calculating machine". From 1945 the term indicates as "programmable digital
electronic computer".

It is consider that Analytical Engine was the first computer which was invented by Charles Babbage in 1837. It
used punch cards as read-only memory. Charles Babbage is also known as the father of the computer.

The first counting device was used by the primitive people. They used sticks, stones and bones as counting
tools. As human mind and technology improved with time more computing devices were developed. Some of
the popular computing devices starting with the first to recent ones are described below;

Abacus

The history of computer begins with the birth of abacus which is believed to be the first computer. It is said
that Chinese invented Abacus around 4,000 years ago.
It was a wooden rack which has metal rods with beads mounted on them. The beads were moved by the
abacus operator according to some rules to perform arithmetic calculations. Abacus is still used in some
countries like China, Russia and Japan. An image of this tool is shown below;

Napier's Bones

It was a manually-operated calculating device which was invented by John Napier (1550-1617) of
Merchiston. In this calculating tool, he used 9 different ivory strips or bones marked with numbers to
multiply and divide. So, the tool became known as "Napier's Bones. It was also the first machine to use the
decimal point.

Pascaline

Pascaline is also known as Arithmetic Machine or Adding Machine. It was invented between 1642 and 1644
by a French mathematician-philosopher Blaise Pascal. It is believed that it was the first mechanical and
automatic calculator.

Pascal invented this machine to help his father, a tax accountant. It could only perform addition and
subtraction. It was a wooden box with a series of gears and wheels. When a wheel is rotated one
revolution, it rotates the neighboring wheel. A series of windows is given on the top of the wheels to read
the totals. An image of this tool is shown below;

Stepped Reckoner or Leibnitz wheel

It was developed by a German mathematician-philosopher Gottfried Wilhelm Leibnitz in 1673. He


improved Pascal's invention to develop this machine. It was a digital mechanical calculator which was called
the stepped reckoner as instead of gears it was made of fluted drums. See the following image;

Difference Engine

In the early 1820s, it was designed by Charles Babbage who is known as "Father of Modern Computer". It
was a mechanical computer which could perform simple calculations. It was a steam driven calculating
machine designed to solve tables of numbers like logarithm tables.
Analytical Engine

This calculating machine was also developed by Charles Babbage in 1830. It was a mechanical computer
that used punch-cards as input. It was capable of solving any mathematical problem and storing
information as a permanent memory.

Tabulating Machine

It was invented in 1890, by Herman Hollerith, an American statistician. It was a mechanical tabulator based
on punch cards. It could tabulate statistics and record or sort data or information. This machine was used in
the 1890 U.S. Census. Hollerith also started the Hollerith?s Tabulating Machine Company which later
became International Business Machine (IBM) in 1924.

Differential Analyzer

It was the first electronic computer introduced in the United States in 1930. It was an analog device
invented by Vannevar Bush. This machine has vacuum tubes to switch electrical signals to perform
calculations. It could do 25 calculations in few minutes.
Mark I

The next major changes in the history of computer began in 1937 when Howard Aiken planned to develop
a machine that could perform calculations involving large numbers. In 1944, Mark I computer was built as a
partnership between IBM and Harvard. It was the first programmable digital computer.

COMPUTER GENERATIONS

First Generation
 The period 1940 to 1956, roughly considered as the First Generation of Computer.
 The first generation computers were developed by using vacuum tube or thermionic valve machine.
 The input of this system was based on punched cards and paper tape; however, the output was
displayed on printouts.
 The first generation computers worked on binary-coded concept (i.e., language of 0-
1). Examples: ENIAC, EDVAC, etc.

Second Generation
 The period 1956 to 1963 is roughly considered as the period of Second Generation of Computers.
 The second generation computers were developed by using transistor technology.
 In comparison to the first generation, the size of second generation was smaller.
 In comparison to computers of the first generation, the computing time taken by the computers of the
second generation was lesser.
Third Generation
 The period 1963 to 1971 is roughly considered as the period of Third Generation of computers.
 The third generation computers were developed by using the Integrated Circuit (IC) technology.

 In comparison to the computers of the second generation, the size of the computers of the third
generation was smaller.
 In comparison to the computers of the second generation, the computing time taken by the
computers of the third generation was lesser.
 The third generation computer consumed less power and also generated less heat.
 The maintenance cost of the computers in the third generation was also low.
 The computer system of the computers of the third generation was easier for commercial use.

Fourth Generation
 The period 1972 to 2010 is roughly considered as the fourth generation of computers.
 The fourth generation computers were developed by using microprocessor technology.

 By coming to fourth generation, computer became very small in size, it became portable.
 The machine of fourth generation started generating very low amount of heat.
 It is much faster and accuracy became more reliable.
 The production cost reduced to very low in comparison to the previous generation.
 It became available for the common people as well.

Fifth Generation
 The period 2010 to till date and beyond, roughly considered as the period of fifth generation of
computers.
 By the time, the computer generation was being categorized on the basis of hardware only, but the
fifth generation technology also included software.
 The computers of the fifth generation had high capability and large memory capacity.
 Working with computers of this generation was fast and multiple tasks could be performed
simultaneously.
 Some of the popular advanced technologies of the fifth generation include Artificial intelligence,
Quantum computation, Nanotechnology, Parallel processing, etc.
CLASSIFICATION OF COMPUTERS
 As you know about the name of a computer but it is well to know about the different types of
computer. A computer is classified on the base of power, function, and purpose. A computer is an
electronic machine that accepts raw data as input, process it according to the instructions, and
calculate results/information to the user according to the given instruction. It is not a human but it is a
machine for doing some operational. A computer can store information and the user can retrieve it
again and again.
 Although a computer can help you to perform complex jobs and solve complicated problems,
therefore it is generally classified or categorized as follows.

Different Types of Computer Based on Function and Operation:

 Analog
 Digital
 Hybrid

Analog Computer:

 A computer which is used to measure analog / physical quantity data. Analog means variable and
physical quantity may always continue their changes.
 They work by measuring voltage and current. Rather than process of counting.
 They work on by supply of continuous electrical signal and display output continuously.
 They are not general purpose computer.
 Such types of computers accept input in analog form and provide results in analog form. It measures
physical quantities like distance, velocity, acceleration, and temperature, e.g. speedometer of care,
temperature, watch and voltmeter.
 Now a day analog computer is using for Engineering and Scientific works. In Oil Refinery it measures
flow and temperature of the oil. They are also used in Papermaking and the Chemical Industry.
 The output of the analog computer is generally in the form of reading. These computers are used
where data can be measured directly from the measuring device.
 Now Analog Computer has been updated to Digital Computers. For example, Analog watch to Digital
Watch, Analog weight Balance to Digital Balance and Analog Thermometer to Digital Thermometer,
etc.

Digital Computers:

 Those Computers which accepts data in a digital form and provide us information in the same format.
It measures digital quantity data and works based on binary digits i.e. 0&1.
 The result of a Digital Computer is more accurate, precise and reliable than Analog Computer. It can
process faster than the Analog Computer. Analog Computer has a small memory while Digital
Computer has high memory and storage power.
 Accounting machine and Calculator are common examples of a Digital Computer.

Hybrid Computers:

 Those Computers which accepts data in digital form and provide results/ information in analog form
and vice versa”.
 Hybrid Computers have the characteristics of both Analog & Digital Computers and measures both
analog and digital quantities. Hybrid Computer has a process with the speed of analog and precision of
a digital computer. They are used for a special purpose and are designed to perform special task e.g.
ECG machine.
 Hybrid Computers are also used in the Air Defense System, and in laboratories for the preparation of
medicines.
 Different Types of Computer Based on Power and Size:
 Supercomputer
 Mainframe
 Minicomputer
 Personal Computer or Microcomputer

Supercomputer:

 A supercomputer is the most powerful multi-user and fastest computer in the world. It calculates
trillion million instructions per second up to 14 accurate decimal places. Therefore, it is called
“Number Cruncher”. Multi CPUs are working together on this computer.
 It work on the principle of parallel processing technique which implement multiple processor to work
in parallel way.
 It is designed to maximize the processing of floating point instruction.
 Speed is measured in GFLOPS (Giga Floating Point Operation Per Second).
 It is very expensive with normal costs of several million dollars. It is made for general purpose to solve
the problems of Scientists & Engineers and is referred to as “FORTRAN ENGINES” means FORmula
TRANslation because FORTRAN language is commonly used by scientists and engineers.
 A supercomputer is considered to be the main tool for the reproduction of nuclear weapons
denotation, aerodynamic flows, and global weather patterns.
 Examples: JAGUAR, NEBULAE, IBM’s ROADRUNNER, KRAKEN, JUGENE, PLEIADES, TIANHE-1, Cray-I,
Cray-II, CYBER205.

Advantages:
• Solve bigger problems
• Run more problems in shorter time
• May save money
• Allows for virtual testing
• Can be used for R&D
Disadvantages:
• Can be expensive
• Takes up a lot of space
• May only be good for specific applications
• Does not replace physical testing
• Requires trained staff
Mainframe Computer:

 Mainframe Computer is an expensive and a multi-user / multiprocessing computer capable of


supporting more than hundreds or thousands of users at the same time. These computers have large
size and memory and more powerful than Minicomputer. These computers have high-speed data
processing power and can process over millions of arithmetic expressions per second.
 A mainframe computer is expensive and is used by large organizations or industries for significant jobs
and data processing. For computerization of a huge business, Universities, Banks, Scientific
Laboratories, National & International Markets, etc. it is usually filled with a large room because many
peripheral, input, output devices can be attached to it.
 The Mainframe Operation System can support multiprogramming, time-sharing and virtual memory;
therefore it is used as Server in a network with many workstations. Many of the terminals can be
attached to a Mainframe computer to run different programs.

Advantages -

 Fast I/O operations


 Highly reliable and stable
 High integrity and fault tolerance
 Long uptime (some up to a decade)
 Less error-prone than other computers
 Hot-swap system capacity without system disruption
 Better virtualization than other computers
 Best computer for transaction processing
 Can store and manage large volumes of data
 Supports files in the terabyte range

Disadvantages -

 More expensive than other computers


 Require a cool environment
 Consumes large amounts of energy, but less than supercomputers
 Less processing speed than a supercomputer

Uses -

 Processing large quantities of data


 Transaction processing
 Bulk data processing
 Applications that must not experience down-time
 Database storage and processing

Minicomputer:

 A Minicomputer is a multi-user / multiprocessing computer capable to handle 10 to 200 users


simultaneously. These types of computers have a medium size, small memory and more powerful and
expensive than Microcomputer. Minicomputer contains one or more processors, support
multiprocessing and tasking. They are smaller than Supercomputer and Mainframe computer, but
more powerful than personal computers and workstations. Multiple Input & Output devices can be
attached to them and used in Networking.
 It is used for computerized the data, scientific research, data collection, industrial process control, and
small business application. Time-sharing, batch processing, and online processing are available on it.
Example: PRIME9755, VAX8650, IBM SYSTEM36
Advantages -
 Faster than microcomputers
 Less expensive than mainframes
Disadvantages -
 More expensive than microcomputers
 Not as powerful as a mainframe
 Uses -
 Obsolete

Personal Computer or Microcomputer:

 It is a single-user computer based on microprocessor/microchip inside. It is designed for one person,


therefore, it is called a personal computer. These Computers are small in size, small in memory, and
less expensive. Many input and output devices can be attached to it. The microcomputer can also
attach with Mainframe Computer through a network. It is generally used in home, offices or any
working place for web surfing, sending an email, type documents, database, photo editing and
entertainment like playing music or games. It is further classified into the following categories.

Advantages -

 Publicly accessible to individuals/citizens


 Relatively inexpensive
 Small and typically easily portable

Disadvantages -

 Less powerful than other computer types


 Less reliable than other computers
 More error-prone than other computers
 Uses -
 Education
 Gaming
 General networking
 General residential and commercial computing

Different Types of Computer Based on Purposes and+ Uses:

 Special Purpose
 General Purpose
 Special Purpose Computers:
 Types of computer which has been manufactured for specific tasks are called Special Purpose
Computer. These computers are also known as “Dedicated Computers” because these are designed for
special jobs. In other words, they are designed to handle specific problems, e.g. control of traffic lights
and in Defense System. A set of instruction or programs is fed to them. As they perform only one type
of job so they are very fast.

 General Purpose Computers:


 Types of computers that can perform all types of jobs and can run multiple programs are called
General Purpose Computers.
 These computers can perform a variety of jobs, e.g. documentation, accounting, playing of games,
making of graphics and doing of arithmetical operations. General Purpose Computers are versatile, but
they are slow in processing and less efficient as compared to Dedicated Computers.
BASIC ORGANISATION OF COMPUTERS
Block diagram of Computer

What is the main concept for building block diagram of a computer:

A computer mainly does the below things, the block diagram of a computer is created by conceding the
things.
 Firstly, the input units of a computer accepts the data and information
 Secondly, the computer follows the instruction and fulfil the desires of the users
 Thirdly, after justifying the needs of the users, it shows the results
 Fourthly, The results are displayed on the output devices
 Finally, If the users want it can save the data for future purposes
Von-Neumann Model

Von-Neumann proposed his computer architecture design in 1945 which was later known as Von-Neumann
Architecture. It consisted of a Control Unit, Arithmetic, and Logical Memory Unit (ALU), Registers and
Inputs/Outputs.

Von Neumann architecture is based on the stored-program computer concept, where instruction data and
program data are stored in the same memory. This design is still used in most computers produced today.

A Von Neumann-based computer:


o Uses a single processor
o Uses one memory for both instructions and data.
o Executes programs following the fetch-decode-execute cycle

Components of Von-Neumann Model:

o Central Processing Unit


o Buses
o Memory Unit

Central Processing Unit

The part of the Computer that performs the bulk of data processing operations is called the Central Processing
Unit and is referred to as the CPU.
The Central Processing Unit can also be defined as an electric circuit responsible for executing the instructions
of a computer program.

The CPU performs a variety of functions dictated by the type of instructions that are incorporated in the
computer.

The major components of CPU are Arithmetic and Logic Unit (ALU), Control Unit (CU) and a variety of
registers.

Arithmetic and Logic Unit (ALU)

The Arithmetic and Logic Unit (ALU) performs the required micro-operations for executing the instructions. In
simple words, ALU allows arithmetic (add, subtract, etc.) and logic (AND, OR, NOT, etc.) operations to be
carried out.

Control Unit

The Control Unit of a computer system controls the operations of components like ALU, memory and
input/output devices.

The Control Unit consists of a program counter that contains the address of the instructions to be fetched and
an instruction register into which instructions are fetched from memory for execution.

Registers

Registers refer to high-speed storage areas in the CPU. The data processed by the CPU are fetched from the
registers.

Following is the list of registers that plays a crucial role in data processing.

Registers Description

MAR (Memory Address Register) This register holds the memory location of the data that needs to
be accessed.

MDR (Memory Data Register) This register holds the data that is being transferred to or from
memory.

AC (Accumulator) This register holds the intermediate arithmetic and logic results.

PC (Program Counter) This register contains the address of the next instruction to be
executed.

CIR (Current Instruction Register) This register contains the current instruction during processing.

Buses

Buses are the means by which information is shared between the registers in a multiple-register configuration
system.
A bus structure consists of a set of common lines, one for each bit of a register, through which binary
information is transferred one at a time. Control signals determine which register is selected by the bus during
each particular register transfer.

Von-Neumann Architecture comprised of three major bus systems for data transfer.

Bus Description

Address Bus Address Bus carries the address of data (but not the data) between the processor and
the memory.

Data Bus Data Bus carries data between the processor, the memory unit and the input/output
devices.

Control Bus Control Bus carries signals/commands from the CPU.

Memory Unit

A memory unit is a collection of storage cells together with associated circuits needed to transfer information
in and out of the storage. The memory stores binary information in groups of bits called words. The internal
structure of a memory unit is specified by the number of words it contains and the number of bits in each
word.

Two major types of memories are used in computer systems:

1. RAM (Random Access Memory)


2. ROM (Read-Only Memory)

Being a modern-day kid you must have used, seen, or read about computers. This is because they are an
integral part of our everyday existence. Be it school, banks, shops, railway stations, hospital or your own
home, computers are present everywhere, making our work easier and faster for us. As they are such
integral parts of our lives, we must know what they are and how they function. Let us start with defining the
term computer formally.
The literal meaning of computer is a device that can calculate. However, modern computers can do a lot
more than calculate. Computer is an electronic device that receives input, stores or processes the input as
per user instructions and provides output in desired format.

INPUT-PROCESS-OUTPUT MODEL

Computer input is called data and the output obtained after processing it, based on user’s instructions is
called information. Raw facts and figures which can be processed using arithmetic and logical operations to
obtain information are called data.
The processes that can be applied to data are of two types −
 Arithmetic operations − Examples include calculations like addition, subtraction, differentials, square
root, etc.
 Logical operations − Examples include comparison operations like greater than, less than, equal to,
opposite, etc.
The corresponding figure for an actual computer looks something like this −

The basic parts of a computer are as follows −


01: Input Unit

Input: This is the process of entering data and programs in to the computer system. You should know that
computer is an electronic machine like any other machine which takes as inputs raw data and performs
some processing giving out processed data. Therefore, the input unit takes data from us to the computer in
an organized manner for processing.

02: Processing Unit

The CPU consists of two main unit including Control Unit and Arithmetic and Logic Unit..

(a) Control Unit:


In the CPU, Control Unit works for receiving the data from the input unit. At the same time, it performs to
store the data in the selected place. It finishes the work by following the instructions of Arithmetic logic
unit (ALU). On the other hand, it can control the flows of the data.
In general, Control Unit can’t do actual functional work, it takes simple instructions and performs to do it
from the input unit.
(b) Arithmetic and Logic Unit:
The name tells itself it works to perform the arithmetic and logical work in the computer. That means if you
want to calculate any terms, it will be performed on the Arithmetic logic unit (ALU). Arithmetic and logic
unit do the work of addition, subtraction, multiplication, division, AND, OR, NOT, Exclusive OR etc.
Simply, all the actual execution of a computer are performed here according to the instructions. On the
other hand, all types of simple or complicated calculations and comparisons are done in the Arithmetic
logic unit (ALU).
03: Storage Unit
The primary purposes of the storage unit are storing the data on the computer. It has no other works.There
are mostly two types of the popular storage unit on the computer including primary storage and secondary
storage.

(a) Primary Storage (Main Memory):

This type of memories is not long lasting. That means, when you will switch off the computer, it will lose all
the memory.Generally, RAM (Random Access Memory) is the types of primary memory. It saves the
instructions or data on the main memory chip’s circuitry which helps to work fastly of the CPU. In all the
computer you will find limited memory for primary storage because it is very costly.

(b) Secondary Storage (Auxiliary Memory):

It is the supportive memory of the main memory. That means, it stores all the software, data or OS of the
computer, but can’t function directly. Secondary memory helps to perform the work of main memory. The
data on the secondary memory is non-volatile. That means it will not be lost after switching off the
computer.

04: Output Unit

This is the process of producing results from the data for getting useful information. Similarly the output
produced by the computer after processing must also be kept somewhere inside the computer before
being given to you in human readable form. Again the output is also stored inside the computer for further
processing.

Control unit, arithmetic logic unit and memory are together called the central processing unit or CPU.
Computer devices like keyboard, mouse, printer, etc. that we can see and touch are
the hardware components of a computer. The set of instructions or programs that make the computer
function using these hardware parts are called software. We cannot see or touch software. Both hardware
and software are necessary for working of a computer.

Von Neumann bottleneck –


Whatever we do to enhance performance, we cannot get away from the fact that instructions can only be
done one at a time and can only be carried out sequentially. Both of these factors hold back the competence
of the CPU. This is commonly referred to as the ‘Von Neumann bottleneck’. We can provide a Von Neumann
processor with more cache, more RAM, or faster components but if original gains are to be made in CPU
performance then an influential inspection needs to take place of CPU configuration.
This architecture is very important and is used in our PCs and even in Super Computers.

CHARACTERISTICS OF COMPUTER
To understand why computers are such an important part of our lives, let us look at some of its characteristics

No IQ

Speed − Computer can work very fast. It takes only few seconds for calculations that we take hours to
complete.

Computer can perform 3-4 millions (1,000,000) of instructions and even more per second. Therefore, we
determine the speed of the computer in terms of microsecond(10^6 part of a second) or nanosecond(10^9
part of A Second).

2 gigahertz to 4 gigahertz is the speed range of computer device.

Accuracy − Computers exhibit a very high degree of accuracy. Errors that may occur are usually due to
inaccurate data, wrong instructions or bug in chips – all human errors.

The Errors we received while using personal computer are generally called as “Human Errors” or the errors of
programmers who writes program for better computer functions.

GIGO (Garbage In Garbage Out) is a well-known term used for computer accuracy, if the input is wrong the
output will also be wrong .

Reliability − Computers can carry out same type of work repeatedly without throwing up errors due to
tiredness or boredom, which are very common among humans.

Versatility − The computer system is very versatile machine. The most wonderful feature of the activities of
different types from simple calculation to the complex scientific operations and computations and is also
capable of preparing the examination marks sheets, bills, letters, documents, and also the design and
modelling of navigating missiles and satellites.

Storage Capacity − The Computer has an in-built memory where it can store a large amount of data. Also,
data is safe from normal wear and tear associated with paper. We can also store data in secondary storage
devices such as floppies, which can be kept outside your computer and can be carried to other computers.

Memory:-This is also one of the most essential characteristics of computer these days they can store or save
almost any volume of data due to its high storage capabilities.

Once the data or instruction saved to the computer memory it remains in the memory, until and unless
someone deletes.

Users can recall or retrieve the data anytime, at any location they require, as the human being tends to forget
small information given to them, but these machines stores all the information was given to them
permanently.

These machines can store the data as long as user’s desire. The measurement of memory are MEGABYTES
(MB), GIGABYTES (GB) And TERABYTES (TB).Hard disk and pen drives are examples of memory.
Diligence: - A computer is free from tiredness, lack of concentration, fatigue, etc. It can work for hours
without creating any error.

If millions of calculations are to be performed, a computer will perform every calculation with the same
accuracy. Due to this capability it overpowers human being in routine type of work.

No IQ: - Computer is a dumb machine and it cannot do any work without instruction from the user. It
performs the instructions at tremendous speed and with accuracy.

It is we to decide what we want to do and in what sequence. So a computer cannot take its own decision as
we can.

PC has errors only when an input is wrong or incorrect, the Computer scientists are working on AI (Artificial
Intelligence) which will make them so powerful and accurate that they will make their own decision, and logic
when giving some instruction.

This type of computer will have unbelievable characteristics which will change the entire Generations of
computer systems.

Automation:-The word automation is conjoint with the computer for a particular task, the computer does not
fully depend on the user, but it precedes the task in forward direction automatically till its completion.

Computers can be easily programmed to perform a series of task according to the requirements. The
computer automatically executes these instructions sequentially, if any error occurs, it produces the
appropriate error message.

COMPUTER MEMORY AND CLASSIFICATION OF MEMORY


The computer memory holds the data and instructions needed to process raw data and produce output. The
computer memory is divided into large number of small parts known as cells. Each cell has a unique address
which varies from 0 to memory size minus one.

Computer memory is classified in the below hierarchy.

1 . Internal register is for holding the temporary results and variables. Accessing data from these registers is the
fastest way of accessing memory.

2. Cache is used by the CPU for memory which is being accessed over and over again. Instead of pulling it every
time from the main memory, it is put in cache for fast access. It is also a smaller memory, however, larger than
internal register.
Cache is further classified to L1, L2 and L3:

a) L1 cache: It is accessed without any delay.

b) L2 cache: It takes more clock cycles to access than L1 cache.

c) L3 cache: It takes more clock cycles to access than L2 cache.

3) Main memory or RAM (Random Access Memory): It is a type of the computer memory and is a hardware
component. It can be increased provided the operating system can handle it.

4) Hard disk: A hard disk is a hardware component in a computer. Data is kept permanently in this memory.
Memory from hard disk is not directly accessed by the CPU, hence it is slower. As compared with RAM, hard disk is
cheaper per bit.

5) Magnetic tape: Magnetic tape memory is usually used for backing up large data. When the system needs to
access a tape, it is first mounted to access the data. When the data is accessed, it is then unmounted. The memory
access time is slower in magnetic tape and it usually takes few minutes to access a tape.

Computer memory is of two types: Volatile (RAM) and Non-volatile (ROM). The secondary memory (hard disk)
is referred as storage not memory.

But, if we categorize memory on behalf of space or location, it is of four types:

o Register memory
o Cache memory
o Primary memory
o Secondary memory

REGISTER MEMORY
Register memory is the smallest and fastest memory in a computer. It is not a part of the main memory and is
located in the CPU in the form of registers, which are the smallest data holding elements. A register
temporarily holds frequently used data, instructions, and memory address that are to be used by CPU. They
hold instructions that are currently processed by the CPU. All data is required to pass through registers before
it can be processed. So, they are used by CPU to process the data entered by the users.

Registers hold a small amount of data around 32 bits to 64 bits. The speed of a CPU depends on the number
and size (no. of bits) of registers that are built into the CPU. Registers can be of different types based on their
uses. Some of the widely used Registers include Accumulator or AC, Data Register or DR, the Address Register
or AR, Program Counter (PC), I/O Address Register, and more.

Types and Functions of Computer Registers:

o Data Register: It is a 16-bit register, which is used to store operands (variables) to be operated by the
processor. It temporarily stores data, which is being transmitted to or received from a peripheral
device.
o Program Counter (PC): It holds the address of the memory location of the next instruction, which is to
be fetched after the current instruction is completed. So, it is used to maintain the path of execution of
the different programs and thus executes the programs one by one, when the previous instruction
gets completed.
o Instructor Register: It is a 16-bit register. It stores the instruction which is fetched from the main
memory. So, it is used to hold instruction codes, which are to be executed. The Control Unit takes
instruction from Instructor Register, then decodes and executes it.
o Accumulator Register: It is a 16-bit register, which is used to store the results produced by the system.
For example, the results generated by CPU after the processing are stored in the AC register.
o Address Register: It is a 12-bit register that stores the address of a memory location where
instructions or data is stored in the memory.
o I/O Address Register: Its job is to specify the address of a particular I/O device.
o I/O Buffer Register: Its job is to exchange the data between an I/O module and the CPU.

CACHE MEMORY
Cache memory is a high-speed memory, which is small in size but faster than the main memory (RAM). The
CPU can access it more quickly than the primary memory. So, it is used to synchronize with high-speed CPU
and to improve its performance.

Cache memory can only be accessed by CPU. It can be a reserved part of the main memory or a storage device
outside the CPU. It holds the data and programs which are frequently used by the CPU. So, it makes sure that
the data is instantly available for CPU whenever the CPU needs this data. In other words, if the CPU finds the
required data or instructions in the cache memory, it doesn't need to access the primary memory (RAM).
Thus, by acting as a buffer between RAM and CPU, it speeds up the system performance.

Types of Cache Memory:

L1: It is the first level of cache memory, which is called Level 1 cache or L1 cache. In this type of cache
memory, a small amount of memory is present inside the CPU itself. If a CPU has four cores (quad core cpu),
then each core will have its own level 1 cache. As this memory is present in the CPU, it can work at the same
speed as of the CPU. The size of this memory ranges from 2KB to 64 KB. The L1 cache further has two types of
caches: Instruction cache, which stores instructions required by the CPU, and the data cache that stores the
data required by the CPU.

L2: This cache is known as Level 2 cache or L2 cache. This level 2 cache may be inside the CPU or outside the
CPU. All the cores of a CPU can have their own separate level 2 cache, or they can share one L2 cache among
themselves. In case it is outside the CPU, it is connected with the CPU with a very high-speed bus. The
memory size of this cache is in the range of 256 KB to the 512 KB. In terms of speed, they are slower than the
L1 cache.

L3: It is known as Level 3 cache or L3 cache. This cache is not present in all the processors; some high-end
processors may have this type of cache. This cache is used to enhance the performance of Level 1 and Level 2
cache. It is located outside the CPU and is shared by all the cores of a CPU. Its memory size ranges from 1 MB
to 8 MB. Although it is slower than L1 and L2 cache, it is faster than Random Access Memory (RAM).

How does cache memory work with CPU?


When CPU needs the data, first of all, it looks inside the L1 cache. If it does not find anything in L1, it looks
inside the L2 cache. If again, it does not find the data in L2 cache, it looks into the L3 cache. If data is found in
the cache memory, then it is known as a cache hit. On the contrary, if data is not found inside the cache, it is
called a cache miss.

If data is not available in any of the cache memories, it looks inside the Random Access Memory (RAM). If
RAM also does not have the data, then it will get that data from the Hard Disk Drive.

So, when a computer is started for the first time, or an application is opened for the first time, data is not
available in cache memory or in RAM. In this case, the CPU gets the data directly from the hard disk drive.
Thereafter, when you start your computer or open an application, CPU can get that data from cache memory
or RAM.

PRIMARY MEMORY
Primary Memory is of two types: RAM and ROM.

RAM (Volatile Memory)

It is a volatile memory. It means it does not store data or instructions permanently. When you switch on the
computer the data and instructions from the hard disk are stored in RAM.

CPU utilizes this data to perform the required tasks. As soon as you shut down the computer the RAM loses all
the data.

ROM (Non-volatile Memory)

It is a non-volatile memory. It means it does not lose its data or programs that are written on it at the time of
manufacture. So it is a permanent memory that contains all important data and instructions needed to
perform important tasks like the boot process.

1. Random Access Memory (RAM) –

 It is also called as read write memory or the main memory or the primary memory.
 The programs and data that the CPU requires during execution of a program are stored in this memory.
 It is a volatile memory as the data loses when the power is turned off.
 RAM is further classified into two types- SRAM (Static Random Access Memory) and DRAM (Dynamic
Random Access Memory).
2. Read Only Memory (ROM) –
 Stores crucial information essential to operate the system, like the program essential to boot the
computer.
 It is not volatile.
 Always retains its data.
 Used in embedded systems or where the programming needs no change.
 Used in calculators and peripheral devices.
 ROM is further classified into 4 types- ROM, PROM, EPROM, and EEPROM.

Types of Read Only Memory (ROM) –


1. PROM (Programmable read-only memory) – It can be programmed by user. Once programmed, the data
and instructions in it cannot be changed.
2. EPROM (Erasable Programmable read only memory) – It can be reprogrammed. To erase data from it,
expose it to ultra violet light. To reprogram it, erase all the previous data.
3. EEPROM (Electrically erasable programmable read only memory) – The data can be erased by applying
electric field, no need of ultra violet light. We can erase only portions of the chip.
SECONDARY MEMORY
The secondary storage devices which are built into the computer or connected to the computer are known as
a secondary memory of the computer. It is also known as external memory or auxiliary storage.

The secondary memory is accessed indirectly via input/output operations. It is non-volatile, so permanently
stores the data even when the computer is turned off or until this data is overwritten or deleted. The CPU
can't directly access the secondary memory. First, the secondary memory data is transferred to primary
memory then the CPU can access it.

Some of the secondary memory or storage devices are described below:

1) Hard Disk:
It is a rigid magnetic disc that is used to store data. It permanently stores data and is located within a drive
unit.

The hard disk is also known as a hard drive. It is a rigid magnetic disc that stores data permanently, as it is a
non-volatile storage device. The hard disk is located within a drive unit on the computer's motherboard and
comprises one or more platters packed in an air-sealed casing. The data is written on the platters by moving a
magnetic head over the platters as they spin. The data stored on a computer's hard drive generally includes
the operating system, installed software, and the user's files and programs, including pictures, music, videos,
text documents, etc.

Components of Hard Drive:

The main components of a hard drive include a head actuator, read/write actuator arm, read/write head,
platter, and spindle. A circuit board, which is called the disk controller or interface board, is present on the
back of a hard drive. It allows the hard drive to communicate with the computer.

2) Solid-state Drive:

SSD (Solid State Drive) is also a non-volatile storage medium that is used to hold and access data. Unlike a
hard drive, it does not have moving components, so it offers many advantages over SSD, such as faster access
time, noiseless operation, less power consumption, and more.

As the cost of SSD has come down, it has become an ideal replacement for a standard hard drive in desktop
and laptop computers. It is also suitable for notebooks, and tablets that don't require lots of storage.

3) Pen drive:

Pen drive is a compact secondary storage device. It is also known as a USB flash drive, thumb drive or a jump
drive. It connects to a computer via a USB port. It is commonly used to store and transfer data between
computers. For example, you can write a report using a computer and then copy or transfer it in the pen
drive. Later, you can connect this pen drive to a computer to see or edit your report. You can also store your
important documents and pictures, music, videos in the pen drive and keep it at a safe place.

Pen drive does not have movable parts; it comprises an integrated circuit memory chip that stores the data.
This chip is housed inside a plastic or aluminium casing. The data storage capacity of the pen drive generally
ranges from 2 GB to 128 GB. Furthermore, it is a plug and play device as you don't need additional drives,
software, or hardware to use it.

4) SD Card:

SD Card stands for Secure Digital Card. It is most often used in portable and mobile devices such as
smartphones and digital cameras. You can remove it from your device and see the things stored in it using a
computer with a card reader.

There are many memory chips inside the SD card that store the data; it does not have moving parts. SD cards
are not created equal, so they may differ from each other in terms of speed, physical sizes, and capacity. For
example, standard SD cards, mini SD cards, and micro SD cards.

5) Compact Disk (CD):

Compact Disk is a portable secondary storage device in the shape of a round medium disk. It is made of
polycarbonate plastic. The concept of CD was co-developed by Philips and Sony in 1982. The first CD was
created on 17 August 1982 at the workshop of Philips in Germany.

In the beginning, it was used for storing and playing sound recordings, later it was used for various purposes
such as for storing documents, audio files, videos, and other data like software programs in a CD.

Physical characteristics of a CD/ Structure of CD:

A standard CD is around 5 inches in diameter and 0.05 inches in thickness. It is made of a clear polycarbonate
plastic substrate, a reflective metallic layer, and a clear coating of acrylic plastic. These thin circular layers are
attached one on top of another as described below:
o A polycarbonate disc layer at the bottom has the data encoded by creating lands and pits.
o The polycarbonate disc layer is coated with a thin aluminium layer that reflects the laser.
o The reflective aluminium layer is coated with a lacquer layer to prevent oxidation in order to protect
the below layers. It is generally spin coated directly on the top of the reflective layer.
o The label print is applied on the lacquer layer, or artwork is screen printed on the top of the disc on the
lacquer layer by offset printing or screen printing.

How Does a CD Work?

The data or information is stored or recorded or encoded in CD digitally using a laser beam that etches tiny
indentations or bumps on its surface. The bump is called a pit, which represents the number 0. Space, where
the bump is not created, is called land, and it represents the number 1. Thus, the data is encoded into a
compact disc by creating pits (0) and lands (1). The CD players use laser technology to read the optically
recorded data.

6) DVD:

DVD is short for digital versatile disc or digital video disc. It is a type of optical media used for storing optical
data. Although it has the same size as a CD, its storage capacity is much more than a CD. So, it is widely used
for storing and viewing movies and to distribute software programs as they are too large to fit on a CD. DVD
was co-developed by Sony, Panasonic, Philips, and Toshiba in 1995.

Types of DVDs:

DVDs can be divided into three main categories which are as follows:

o DVD-ROM (Read-Only): These types of DVDs come with media already recorded on them, such as
movie dvds. As the name suggests, data on these discs cannot be erased or added, so these discs are
known as a read-only or non-writable DVD.
o DVD-R (Writable): It allows you to record or write information to the DVD. However, you can write
information only once as it becomes a read-only DVD once it is full.
o DVD-RW (Rewritable or Erasable): This type of discs can be erased, written, or recorded multiple
times.

Memory Units

Memory units are used to measure and represent data. Some of the commonly used memory units are:

1) Bit: The computer memory units start from bit. A bit is the smallest memory unit to measure data stored in
main memory and storage devices. A bit can have only one binary value out of 0 and 1.

2) Byte: It is the fundamental unit to measure data. It contains 8 bits or is equal to 8 bits. Thus a byte can
represent 2*8 or 256 values.
3) Kilobyte: A kilobyte contains 1024 bytes.

4) Megabyte: A megabyte contains 1024 kilobytes.

5) Gigabyte: A gigabyte contains 1024 megabyte.

6) Terabyte: A terabyte contains 1024 gigabytes.


UNIT-2
COMPUTER SOFTWARE
SOFTWARE CONCEPTS
A Computer is an electronic device that can perform various operations of computation at a greater
speed than what an ordinary machine or human mind can do. It is driven by many entities
including the physical and tangible components that we can touch or feel, called
the Hardware and programs and commands that drive the hardware, called the Software.
The Software refers to the set of instructions fed in form of programs to govern the computer
system and process the hardware components. For example:
 The antivirus that we use to protect our computer system is a type of Software.
 The media players that we use to play multimedia files such as movies, music etc. are
Software.
 The Microsoft Office we use to edit the documents is a Software.
Depending on its use and area of implementation, Software’s can be divided into 3 major types:
1. System Software
2. Application Software
3. Utility Software

SYSTEM SOFTWARE

These are the software that directly allows the user to interact with the hardware components of a computer
system. As the humans and machines follow different languages, there has to be an interface that will allow
the users to interact with the core system, this interface is provided by the software. The system software
can be called the main or the alpha software of a computer system as it handles the major portion of
running a hardware. This System Software can be further divided into four major types:
1. The Operating System – It is the main program that governs and maintains the inter-cooperation of
the components of a computer system. For eg., Microsoft Windows, Linux, Mac OS etc.
2. The Language Processor – The hardware components present in the computer system does not
understand human language. There are three types of languages involved in the world of human-
machine interaction:
 Machine-Level Language: The machines only understand the digital signals or the binary codes
or the binary language which consist of strings of 0’s and 1’s. These are totally machine
dependent language.
 Assembly-Level Language: These are the Low-Level Language(LLL), that forms a
correspondence between machine level instruction and general assembly level statements.
Assembly language uses a mnemonics to represent each low-level machine instruction or
operation-code also called the op-codes. For eg., ADD instruction is used to add two entities, the
HALT instruction is used to stop a process etc. It is a machine dependent language and varies
from processor to processor.
 High-Level Language: These are the simple English statements, that humans use to program
and code as it is easy to read and understand to the human world. For eg., Java, C, C++, Python
etc. 00010000010
The machine level language is very complex to understand and code, therefore the users prefer
the High-Level Language or the HLL for coding. These codes need to be converted into the machine
language so that the computer can easily understand and work accordingly. This operation is
performed by the Language Processor which is made up of further three components:
 Assembler: This language processor is used to convert the assembly language into machine
level language.
 Compiler: This language processor is used to convert High-Level Language into machine level
language in one go, thus execution time is fast. The error detection is difficult in a compiler.
Programming Languages like C, C++ and Scala use compiler.
 Interpreter: This language processor is also used to convert High-Level Language into machine
level language line-by-line, thus execution time is slow. Error-detection is easier in an interpreter
as it reports as soon as a bug is caught and restarts the process. This consumes unnecessary
memory. Programming Languages like Python, Ruby and Java uses an interpreter.
3. The Device Drivers – The device drivers and the device programs or the system software that acts as
an interface between the various Input-Output device and the users or the operating system. For eg.,
the Printers, Web cameras come with a driver disk that is needed to be installed into the system to
make the device run in the system.
4. The BIOS – It stands for Basic Input Output System and is a small firmware, that controls the
peripheral or the input-output devices attached to the system. This software is also responsible for
starting the OS or initiating the booting process.

APPLICATION SOFTWARE

These are the basic software used to run to accomplish a particular action and task. These are the
dedicated software, dedicated to performing simple and single tasks. For eg., a single software cannot
serve to both the reservation system and banking system. These are divided into two types:
1. The General Purpose Application Software: These are the types of application software that comes
in-built and ready to use, manufactures by some company or someone. For eg.,
 Microsoft Excel – Used to prepare excel sheets.
 VLC Media Player – Used to play audio/video files.
 Adobe Photoshop – Used for designing and animation and many more.
2. The Specific Purpose Application Software: These are the type of software that is customizable
and mostly used in real-time or business environment. For eg.,
 Ticket Reservation System
 Healthcare Management System
 Hotel Management System
 Payroll Management System

UTILITY SOFTWARE

These are the most basic type of software which provides high utility to the user and the system. These
perform the basic but daily need tasks. For eg.,
 Antivirus Softwares: These provide protection to the computer system from unwanted malware and
viruses. For eg., QuickHeal, McAfee etc.
 Disk Defragmenter Tools: These help the users to analyse the bad sectors of the disk and rearrange
the files in a proper order.
 Text-editors: These help the users to take regular notes and create basic text files. For eg., Notepad,
Gedit etc.

PROGRAMMING SOFTWARE:

It is a set or collection of tools that help developers in writing other software or programs. It
assists them in creating, debugging, and maintaining software or programs or applications. We
can say that these are facilitator software that helps translate programming language such as
Java, C++, Python, etc., into machine language code. So, it is not used by end-users. For
example, compilers, linkers, debuggers, interpreters, text editors, etc. This software is also
called a programming tool or software development tool.

Some examples of programming software include:

o Eclipse: It is a java language editor.


o Coda: It is a programming language editor for Mac.
o Notepad++: It is an open-source editor for windows.
o Sublime text: It is a cross-platform code editor for Linux, Mac, and Windows.

DIFFERENCE BETWEEN HARDWARE AND SOFTWARE:

HARDWARE SOFTWARE

Hardware is a physical parts computer Software is a set of instruction that tells

that cause processing of data. a computer exactly what to do.

It is manufactured. It is developed and engineered.

Hardware can not perform any task software can not be executed without

without software. hardware.

As Hardware are physical electronic

devices, we can see and touch We can see and also use the software

hardware. but can’t actually touch them.

It has four main categories: input device, It is mainly divided into System

output devices, storage, and internal software, Programming software and

components. Application software.

Hardware is not affected by computer Software is affected by computer


viruses. viruses.

It can not be transferred from one place

to another electrically through network. But, it can be transferred.

If hardware is damaged, it is replaced If software is damaged, its backup copy

with new one. can be reinstalled.

Ex: Keyboard, Mouse, Monitor, Printer, Ex: Ms Word, Excel, Power Point,

CPU, Hard disk, RAM, ROM etc. Photoshop, MySQL etc.

OVERVIEW OF OPERATING SYSTEM


DEFINITION OF OS:-

In the Computer System (comprises of Hardware and software), Hardware can only understand
machine code (in the form of 0 and 1) which doesn't make any sense to a naive user.

We need a system which can act as an intermediary and manage all the processes and resources
present in the system.

An Operating System can be defined as an interface between user and hardware. It is


responsible for the execution of all the processes, Resource Allocation, CPU management, File
Management and many other tasks.

The purpose of an operating system is to provide an environment in which a user can execute
programs in convenient and efficient manner.

STRUCTURE OF A COMPUTER SYSTEM

A Computer System consists of:


o Users (people who are using the computer)
o Application Programs (Compilers, Databases, Games, Video player, Browsers, etc.)
o System Programs (Shells, Editors, Compilers, etc.)
o Operating System ( A special program which acts as an interface between user and
hardware )
o Hardware ( CPU, Disks, Memory, etc)
Objectives of Operating System
An operating system consists of a special program that controls the execution of the application
program. The OS acts as an intermediary between applications and hardware components. OS
can be thought of as having three objectives. These are:

 Convenience: It makes a computer more suitable to use.


 Efficiency: It provides the computer system resources with efficiency and in easy to use format.
 Ability to develop: It should be built in such a way that it permits the efficient development,
testing, and installation of new system functions without interfering with service.

Functions of Operating System


Security –
The operating system uses password protection to protect user data and similar other techniques.
it also prevents unauthorized access to programs and user data.

Control over system performance –


Monitors overall system health to help improve performance. records the response time between
service requests and system response to have a complete view of the system health. This can
help improve performance by providing important information needed to troubleshoot problems.

Job accounting –
Operating system Keeps track of time and resources used by various tasks and users, this
information can be used to track resource usage for a particular user or group of user.
Error detecting aids –
Operating system constantly monitors the system to detect errors and avoid the malfunctioning of
computer system.

Coordination between other software and users –


Operating systems also coordinate and assign interpreters, compilers, assemblers and other
software to the various users of the computer systems.

Memory Management –
The operating system manages the Primary Memory or Main Memory. Main memory is made up of
a large array of bytes or words where each byte or word is assigned a certain address. Main
memory is a fast storage and it can be accessed directly by the CPU. For a program to be
executed, it should be first loaded in the main memory. An Operating System performs the
following activities for memory management:

It keeps tracks of primary memory, i.e., which bytes of memory are used by which user program.
The memory addresses that have already been allocated and the memory addresses of the
memory that has not yet been used. In multi programming, the OS decides the order in which
process are granted access to memory, and for how long. It Allocates the memory to a process
when the process requests it and deallocates the memory when the process has terminated or is
performing an I/O operation.

Processor Management –
In a multi programming environment, the OS decides the order in which processes have access to
the processor, and how much processing time each process has. This function of OS is called
process scheduling. An Operating System performs the following activities for processor
management.

Keeps tracks of the status of processes. The program which perform this task is known as traffic
controller. Allocates the CPU that is processor to a process. De-allocates processor when a
process is no more required.

Device Management –
An OS manages device communication via their respective drivers. It performs the following
activities for device management. Keeps tracks of all devices connected to system. designates a
program responsible for every device known as the Input/Output controller. Decides which process
gets access to a certain device and for how long. Allocates devices in an effective and efficient
way. Deallocates devices when they are no longer required.

File Management –
A file system is organized into directories for efficient or easy navigation and usage. These
directories may contain other directories and other files. An Operating System carries out the
following file management activities. It keeps track of where information is stored, user access
settings and status of every file and more… These facilities are collectively known as the file
system.

Moreover, Operating System also provides certain services to the computer system in one form or
the other.
The Operating System provides certain services to the users which can be listed in the
following manner:
Program Execution: The Operating System is responsible for execution of all types of programs
whether it be user programs or system programs. The Operating System utilises various resources
available for the efficient running of all types of functionalities.

Handling Input/Output Operations: The Operating System is responsible for handling all sort of
inputs, i.e, from keyboard, mouse, desktop, etc. The Operating System does all interfacing in the
most appropriate manner regrading all kind of Inputs and Outputs.
For example, there is difference in nature of all types of peripheral devices such as mouse or
keyboard, then Operating System is responsible for handling data between them.

Manipulation of File System: The Operating System is responsible for making of decisions
regarding the storage of all types of data or files, i.e, floppy disk/hard disk/pen drive, etc. The
Operating System decides as how should the data should be manipulated and stored.

Error Detection and Handling: The Operating System is responsible for detection of any types of
error or bugs that can occur while any task. The well secured OS sometimes also acts as
countermeasure for preventing any sort of breach to the Computer System from any external
source and probably handling them.

Resource Allocation: The Operating System ensures the proper use of all the resources
available by deciding which resource to be used by whom for how much time. All the decisions are
taken by the Operating System.

Accounting: The Operating System tracks an account of all the functionalities taking place in the
computer system at a time. All the details such as the types of errors occurred are recorded by the
Operating System.

Information and Resource Protection: The Operating System is responsible for using all the
information and resources available on the machine in the most protected way. The Operating
System must foil an attempt from any external resource to hamper any sort of data or information.

All these services are ensured by the Operating System for the convenience of the users to make
the programming task easier. All different kinds of Operating System more or less provide the
same services.

Following are the major applications of an operating system −


 An operating system is accountable for the formation and deletion of files and directories.
 An operating system manages the process of deletion, suspension, resumption, and
synchronization.
 An operating system manages memory space by allocation and de-allocation.
 An operating system stores, organizes, and names and protects the existing files.
 Further, an operating system manages all the components and devices of the computers
system including modems, printers, plotters, etc.
 In case, if any device fails, the operating system detects and notify.
 An operating system protects from destruction as well as from unauthorized use.
 An operating system facilitates the interface to user and hardware.

TYPES OF OPERATING SYSTEMS


An Operating System performs all the basic tasks like managing file,process, and memory. Thus
operating system acts as manager of all the resources, i.e. resource manager. Thus operating system
becomes an interface between user and machine.

1. Batch Operating System –


This type of operating system does not interact with the computer directly. There is an operator
which takes similar jobs having same requirement and group them into batches. It is the
responsibility of operator to sort the jobs with similar needs.

Advantages of Batch Operating System:


 It is very difficult to guess or know the time required by any job to complete. Processors of the
batch systems know how long the job would be when it is in queue
 Multiple users can share the batch systems
 The idle time for batch system is very less
 It is easy to manage large work repeatedly in batch systems
Disadvantages of Batch Operating System:
 The computer operators should be well known with batch systems
 Batch systems are hard to debug
 It is sometime costly
 The other jobs will have to wait for an unknown time if any job fails
Examples of Batch based Operating System: Payroll System, Bank Statements etc.

2. Time-Sharing Operating Systems –


Each task is given some time to execute, so that all the tasks work smoothly. Each user gets
time of CPU as they use single system. These systems are also known as Multitasking
Systems. The task can be from single user or from different users also. The time that each task
gets to execute is called quantum. After this time interval is over OS switches over to next task.
Advantages of Time-Sharing OS:
 Each task gets an equal opportunity
 Less chances of duplication of software
 CPU idle time can be reduced
Disadvantages of Time-Sharing OS:
 Reliability problem
 One must have to take care of security and integrity of user programs and data
 Data communication problem
Examples of Time-Sharing OSs are: Multics, Unix etc.

3. Multiprocessor Systems
A Multiprocessor system consists of several processors that share a common physical memory.
Multiprocessor system provides higher computing power and speed. In multiprocessor system all
processors operate under single operating system. Multiplicity of the processors and how they do
act together are transparent to the others.

Advantages of Multiprocessor Systems

1. Enhanced performance
2. Execution of several tasks by different processors concurrently, increases the system's
throughput without speeding up the execution of a single task.
3. If possible, system divides task into many subtasks and then these subtasks can be
executed in parallel in different processors. Thereby speeding up the execution of single
tasks.

4. Multiprogramming Batch Systems

 In this the operating system picks up and begins to execute one of the jobs from memory.
 Once this job needs an I/O operation operating system switches to another job (CPU and
OS always busy).
 Jobs in the memory are always less than the number of jobs on disk(Job Pool).
 If several jobs are ready to run at the same time, then the system chooses which one to run
through the process of CPU Scheduling.
 In Non-multiprogrammed system, there are moments when CPU sits idle and does not do
any work.
 In Multiprogramming system, CPU will never be idle and keeps on processing.

Time Sharing Systems are very similar to Multiprogramming batch systems. In fact time sharing
systems are an extension of multiprogramming systems.
In Time sharing systems the prime focus is on minimizing the response time, while in
multiprogramming the prime focus is to maximize the CPU usage.

5. Real-Time Operating System –


These types of OSs serve the real-time systems. The time interval required to process and
respond to inputs is very small. This time interval is called response time.

Real-time systems are used when there are times requirements are very strict like missile
systems, air traffic control systems, robots etc.
Two types of Real-Time Operating System which are as follows:
 Hard Real-Time Systems:
These OSs are meant for the applications where time constraints are very strict and even the
shortest possible delay is not acceptable. These systems are built for saving life like automatic
parachutes or air bags which are required to be readily available in case of any accident.
Virtual memory is almost never found in these systems.
 Soft Real-Time Systems:
These OSs are for applications where for time-constraint is less strict.

Advantages of RTOS:
 Maximum Consumption: Maximum utilization of devices and system,thus more output from
all the resources
 Task Shifting: Time assigned for shifting tasks in these systems are very less. For example
in older systems it takes about 10 micro seconds in shifting one task to another and in latest
systems it takes 3 micro seconds.
 Focus on Application: Focus on running applications and less importance to applications
which are in queue.
 Real time operating system in embedded system: Since sizes of programs are small,
RTOS can also be used in embedded systems like in transport and others.
 Error Free: These types of systems are error free.
 Memory Allocation: Memory allocation is best managed in these types of systems.
Disadvantages of RTOS:
 Limited Tasks: Very few tasks run at the same time and their concentration is very less on
few applications to avoid errors.
 Use heavy system resources: Sometimes the system resources are not so good and they
are expensive as well.
 Complex Algorithms: The algorithms are very complex and difficult for the designer to write on.
 Device driver and interrupt signals: It needs specific device drivers and interrupt signals to
response earliest to interrupts.
 Thread Priority: It is not good to set thread priority as these systems are very less prone to switching
tasks.
Examples of Real-Time Operating Systems are: Scientific experiments, medical imaging
systems, industrial control systems, weapon systems, robots, air traffic control systems, etc.
Let’s see the difference between DOS and Windows:

DISK OPERATING SYSTEM


MS-DOS (shorthand for Microsoft Disk Operating System) is a single tasking, single user,
non-graphical command line operating system. Originally developed for use with IBM’s earliest
line of personal home computers, MS-DOS is one of the most successful operating systems of
its kind. As an operating system, DOS is simple, compact, and remarkably robust; especially
considering its age. While it may have been surpassed by the newer, and more user friendly,
graphical user interface (GUI) operating systems, MS-DOS remains in widespread use by
businesses and independent programmers throughout the world.

MS-DOS is one of the oldest and widely used operating system. DOS is a set of computer
programs, the major functions of which are file management, allocation of system resources,
providing essential features to control hardware devices.
DOS commands can be typed in either upper case or lower case.

A History of MS-DOS
The origins of MS-DOS can be traced back to two earlier operating systems, CP/M and
QDOS. CP/M (AKA Control Program for Microcomputers) was created in the mid 1970s by
Gary Kildall of Digital Research. CP/M was an 8-bit operating system, and was one of the first
to be widely used in the emerging line of commercial microcomputers. In 1980, Tom Paterson
of Seattle Computer Products developed QDOS (Quick and Dirty Operating System) for Intel’s
new 16-bit 8086 central processing unit(CPU). QDOS was largely based on CP/M, and it is
here that Microsoft entered the picture.

In 1981 Microsoft purchased QDOS from Seattle Computer Products, renaming it MS-DOS 1.0
and offering it to IBM for use in their new personal computers. In a prescient move, Gates
retained the licensing for MS-DOS and it would become the most important factor in
Microsoft’s move from a simple vendor of computer programming languages to a giant in the
computer software industry. The success of MS-DOS directly paralleled the growing popularity
of the personal home computer, and remained Microsoft’s most significant source of income
even after the firm began to introduce its own GUI in the form of MS-Windows.

Features of DOS
Following are the significant features of DOS −

 It is a single user system.


 It controls program.
 It is machine independence.
 It manages (computer) files.
 It manages input and output system.
 It manages (computer) memory.
 It provides command processing facilities.
 It operates with Assembler.
Types of DOS Commands
Following are the major types of DOS Command −
 Internal Commands − Commands such as DEL, COPY, TYPE, etc. are the internal
commands that remain stored in computer memory.
 Internal commands are more commonly used and important to the operation
and use of the Windows operating system. By embedding them in the
command.com file, they can be quickly accessed and always available in MS-
DOS and to Windows when needed.

Listing of internal commands


Below are examples of internal commands in MS-DOS and the Windows
command line currently listed in the Computer Hope database.

Assoc For Rd Unlock


Atmadm Goto Ren Ver
Break If Rename Verify
Call LH Rmdir Vol
CD Loadhigh Set
Chdir Lock Setlocal
Cls Md Shift
Color Mkdir Start
Copy Mklink Switches
Ctty Move Time
Date Path Title
Del Pause Type
Dir Popd
Drivparm Prompt
Echo Pushd
Endlocal
Erase
Exit
Where are the internal command files stored?
Internal commands are part of the shell, which could be command.com or
cmd.exe (depending on version of MS-DOS or Windows) and are not
separate files on the hard drive.

How do you run an internal command?


As long as you can open a command line, you can run any of the internal
commands included with your version of MS-DOS or Microsoft Windows.

 External Commands − Commands like FORMAT, DISKCOPY, etc. are the external
commands and remain stored on the disk.
 External commands are powerful commands and can help fix problems,
improve performance, or perform other actions. External commands usually
have higher resource requirements than internal commands. Keeping them in
separate files, separated from internal commands, helps to reduce the load on
Windows. They can also be added to Windows whenever needed by copying the
external command's file to the computer.

Listing of external commands


Below are examples of MS-DOS and Windows
command line external commands currently listed on
Computer Hope.

Append Edit Mwbackup Systeminfo


Arp Edlin Msd Taskkill
Assign Expand Msg Tasklist
At Extract Nbtstat Telnet
Attrib Fasthelp Net Tracert
Backup Fc Netsh Tree
Bcdedit Fciv Netstat Tskill
Bootsect Fdisk Nlsfunc Undelete
Cacls Find Nslookup Unformat
Chcp Forfiles Pathping Wmic
Chkdsk Format Ping Xcopy
Chkntfs FTP Power
Choice Gpupdate Print
Cipher Graftabl Reg
Clip Help Robocopy
Comp Hostname Route
Compact ICacls Runas
Convert Ipconfig Sc
Debug Label ScanDisk
Defrag Loadfix Scanreg
Delpart logoff Schtasks
Deltree Mem Setver
Diskcomp Mode Sfc
Diskcopy More Share
Doskey Move Shutdown
Dosshell Msav Smartdrv
Driverquery Msbackup Sort
Dumpchk Mscdex Subst
Mscdexnt Sys

Where are the external command files stored?


Many of the external commands are located in the Windows\system32 or
Winnt\system32 directories. If you need to locate the external file to delete it,
rename it or replace it, you can also find the file through MS-DOS.

How do you run an external command?


As long as the file exists and you have the proper paths, an external command
runs like an internal command by typing the command name at the prompt.
However, if the paths are not set properly or they are missing because the
command line would not know where to look for the external command, you
would get an error. Unless of course you were in the same directory as the
command.

Can you send me the external command file?


Computer Hope cannot and will not provide any user with a downloadable
version of any of the above files. If you are looking for a download, we suggest
you look for alternative programs that perform the same function as the above
commands.
BASIC DOS COMMANDS :

a) Directory Commands :

 DIR : To list all or specific files of any directory on a specified disk.


 MD : To make directory or subdirectory on a specified disk/drive.
 CD or CHDIR : Change DOS current working directory to specified directory on specified
disk or to check for the current directory on the specified or default drive.
 RMDIR or RD : Removes a specified sub-directory only when it is empty. This command
cannot remove root directory (C:\) or current working directory.
 TREE : Displays all of the directory paths found on the specified drive.
 PATH : Sets a sequential search path for the executables files, if the same are not available
in the current directory.
 SUBST : Substitutes a string alias for the pathname and creates a virtual drive.

b) File Management Commands :

 COPY : Copies one or more files from source disk/drive to the specified disk/drive.
 XCOPY : Copies files and directories, including lower-level directories if they exists.
 DEL : Removes specified files from specified disk/drive.
 REN : Changes the name of a file(Renaming).
 ATTRIB : Sets or shows file attributes (read, write, hidden, Archive).
 BACKUP : Stores or back up one or more files/directories from source disk/drive to other
destination disk/drive.
 RESTORE : Restores files that were backed up using BACKUP command.
 EDIT : Provides a full screen editor to create or edit a text file.
 FORMAT : Formats a disk/drive for data storage and use.

c) General Commands :

 TIME : sets or displays the system time.


 DATE : Sets or displays system date.
 TYPE : Displays the contents of at the specified file.
 PROMPT : Customizes the DOS command prompt.
 If a users requires help on any DOS commands he/she may type help and command name
at the command prompt.

WINDOWS OPERATING SYSTEM


The operating system window is the extension of the disk operating system.
It is the most popular and simplest operating system; it can be used by any person who can read
and understand Basic English, as it does not require any special training.
However, the Windows Operating System requires DOS to run the various application programs
initially. Because of this reason, DOS should be installed into the memory and then window can
be executed.
Microsoft Windows Operating Systems for PCs
The following details the history of MS-DOS and Windows operating systems designed for
personal computers (PCs).
MS-DOS - Microsoft Disk Operating System (1981)
Originally developed by Microsoft for IBM, MS-DOS was the standard operating system for IBM-
compatible personal computers. The initial versions of DOS were very simple and resembled
another operating system called CP/M. Subsequent versions have become increasingly
sophisticated as they incorporated features of minicomputer operating systems.

Windows 1.0 – 2.0 (1985-1992)


Introduced in 1985, Microsoft Windows 1.0 was named due to the computing boxes, or "windows"
that represented a fundamental aspect of the operating system. Instead of typing MS-
DOS commands, windows 1.0 allowed users to point and click to access the windows.
In 1987 Microsoft released Windows 2.0, which was designed for the designed for the Intel 286
processor. This version added desktop icons, keyboard shortcuts and improved graphics support.
Windows 3.0 – 3.1 (1990–1994)
Windows 3.0 was released in May, 1900 offering better icons, performance and advanced
graphics with 16 colors designed for Intel 386 processors. This version is the first release that
provides the standard "look and feel" of Microsoft Windows for many years to come. Windows 3.0
included Program Manager, File Manager and Print Manager and games (Hearts, Minesweeper
and Solitaire). Microsoft released Windows 3.1 in 1992.
Windows 95 (August 1995)
Windows 95 was released in 1995 and was a major upgrade to the Windows operating system.
This OS was a significant advancement over its precursor, Windows 3.1. In addition to sporting a
new user interface, Windows 95 also includes a number of important internal improvements.
Perhaps most important, it supports 32-bit applications, which means that applications written
specifically for this operating system should run much faster.
Although Windows 95 can run older Windows and DOS applications, it has essentially removed
DOS as the underlying platform. This has meant removal of many of the old DOS limitations, such
as 640K of main memory and 8-character filenames. Other important features in this operating
system are the ability to automatically detect and configure installed hardware (plug and play).
Windows 98 (June 1998)
Windows 98 offers support for a number of new technologies, including FAT32, AGP, MMX, USB,
DVD, and ACPI. Its most visible feature, though, is the Active Desktop, which integrates the Web
browser (Internet Explorer) with the operating system. From the user's point of view, there is no
difference between accessing a document residing locally on the user's hard disk or on a Web
server halfway around the world.
Windows ME - Millennium Edition (September 2000)
The Windows Millennium Edition, called "Windows Me" was an update to the Windows 98 core
and included some features of the Windows 2000 operating system. This version also removed
the "boot in DOS" option.
Windows NT 31. - 4.0 (1993-1996)
A version of the Windows operating system. Windows NT (New Technology) is a 32-bit operating
system that supports preemptive multitasking. There are actually two versions of Windows NT:
Windows NT Server, designed to act as a server in networks, and Windows NT Workstation for
stand-alone or client workstations.
Windows 2000 (February 2000)
Often abbreviated as "W2K," Windows 2000 is an operating system for business desktop and
laptop systems to run software applications, connect to Internet and intranet sites, and access
files, printers, and network resources. Microsoft released four versions of Windows 2000:
Professional (for business desktop and laptop systems), Server (both a Web server and an office
server), Advanced Server (for line-of-business applications) and Datacenter Server (for high-traffic
computer networks).

Windows XP (October 2001)


Windows XP was released in 2001. Along with a redesigned look and feel to the user interface, the
new operating system is built on the Windows 2000 kernel, giving the user a more stable and
reliable environment than previous versions of Windows. Windows XP comes in two versions,
Home and Professional. Microsoft focused on mobility for both editions, including plug and play
features for connecting to wireless networks. The operating system also utilizes
the 802.11x wireless security standard. Windows XP is one of Microsoft's best-selling products.
Windows Vista (November 2006)
Windows Vista offered an advancement in reliability, security, ease of deployment, performance
and manageability over Windows XP. New in this version was capabilities to detect hardware
problems before they occur, security features to protect against the latest generation of threats,
faster start-up time and low power consumption of the new sleep state. In many cases, Windows
Vista is noticeably more responsive than Windows XP on identical hardware. Windows Vista
simplifies and centralizes desktop configuration management, reducing the cost of keeping
systems updated.
Windows 7 (October, 2009)
Windows 7 was released by Microsoft on October 22, 2009 as the latest in the 25-year-old line of
Windows operating systems and as the successor to Windows Vista (which itself had followed
Windows XP). Windows 7 was released in conjunction with Windows Server 2008 R2, Windows
7's server counterpart. Enhancements and new features in Windows 7 include multi-touch support,
Internet Explorer 8, improved performance and start-up time, Aero Snap, Aero Shake, support for
virtual hard disks, a new and improved Windows Media Center, and improved security.

Windows 8
Windows 8 was released on August. 1, 2012 and is a completely redesigned operating system
that's been developed from the ground up with touchscreen use in mind as well as near-instant-on
capabilities that enable a Windows 8 PC to load and start up in a matter of seconds rather than in
minutes.
Windows 8 will replace the more traditional Microsoft Windows OS look and feel with a new
"Metro" design system interface that first debuted in the Windows Phone 7 mobile operating
system. The Metro user interface primarily consists of a "Start screen" made up of "Live Tiles,"
which are links to applications and features that are dynamic and update in real time. Windows 8
supports both x86 PCs and ARM processors.
Windows 10
Windows 10 is Microsoft's Windows successor to Windows 8. Windows 10 debuted on July 29,
2015, following a "technical preview" beta release of the new operating system that arrived in Fall
2014 and a "consumer preview" beta in early 2015. Microsoft claims Windows 10 features fast
start up and resume, built-in security and the return of the Start Menu in an expanded form. This
version of Windows will also feature Microsoft Edge, Microsoft's new browser. Any qualified device
(such as tablets, PCs, smartphones and Xbox consoles) can upgrade to Windows 10, including
those with pirated copies of Windows.
Microsoft Operating Systems for Servers and Mobile Devices
Aside from operating systems designed for use on personal computers (PCs) and laptops,
Microsoft has also developed operating systems for services, handheld devices, and mobile
phones.
Windows Server (March 2003)
Windows Server is a series of Microsoft server operating systems. Windows servers are more
powerful versions of their desktop operating system counterparts and are designed to more
efficiently handle corporate networking, Internet/intranet hosting, databases, enterprise-scale
messaging and similar functions. The Windows Server name made its debut with the release of
Windows Server 2003 and continues with the current release, Windows Server 2008 R2, which
shares its codebase with Windows 7. Windows Server 2008 R2 debuted in October 2009.
Windows Home Server (January 2007)
Announced in January 2007, Windows Home Server (WHS) is a "consumer server" designed to
use with multiple computers connected in the home. Home Server allows you to share files such
as digital photos and media files, and also allows you to automatically backup your home
networked computers. Through Windows Media Connect, Windows Home Server lets you share
any media located on your WHS with compatible devices.
Windows CE (November 2006)
A version of the Windows operating system designed for small devices such as personal digital
assistants (PDAs) (or Handheld PCs in the Microsoft vernacular). The Windows CE graphical user
interface (GUI) is very similar to Windows 95 so devices running Windows CE should be easy to
operate for anyone familiar with Windows 95.
Windows Mobile (April 2000)
A mobile operating system for smartphones and mobile devices from Microsoft based on the
Windows CE kernel and designed to look and operate similar to desktop versions of Microsoft
Windows. Windows Mobile has largely been supplanted by Windows Phone 7, although Microsoft
did release, in 2011, Windows Embedded Handheld 6.5, a mobile OS compatible with Windows
Mobile 6.5 that's designed for enterprise mobile and handheld computing devices.
Windows Phone (November 2010)

A mobile operating system for smartphones and mobile devices that serves as the successor to
Microsoft's initial mobile OS platform system, Windows Mobile. Unlike Windows Mobile, Windows
Phone 7 (also referred to as WinPhone7) is targeted more to the consumer market than the
enterprise market, and it replaces the more traditional Microsoft Windows OS look and feel with a
new "Metro" design system user interface.
Windows Phone 7 features a multi-tab Internet Explorer Mobile Web browser that uses a rendering
engine based on Internet Explorer 9 as well Microsoft Office Mobile, a version of Microsoft Office
that’s tailored for mobile devices. Its successors include Windows Phone 8 and Windows 10
Mobile.
versions of Windows Operating System (in short)−
Version Year Version Year

Window 1.01 1985 Windows XP Professional x64 2005

Windows NT 3.1 1993 Windows Vista 2007

Windows 95 1995 Windows 7 2009

Windows 98 1998 Windows 8 2012

Windows 2000 2000 Windows 10 2015

Windows ME 2000 Windows Server 2016 2016

Windows XP 2001

Elements of Windows OS
Following are the significant element of Windows Operating System (WOS) −

 Graphical User Interface


 Icons (pictures, documents, application, program icons, etc.)
 Taskbar
 Start button
 Windows explorer
 Mouse button
 Hardware compatibility
 Software compatibility
 Help, etc.
Features of Windows OS and Advantages and Disadvantages of Windows OS

Best Features of Windows Operating System

1. Speed

Even aside from incompatibilities and other issues that many people had with Vista, one of the
most straightforward was speed – it just felt too sluggish compared to XP, even on pumped up
hardware. Windows 7 brings a more responsive and sprightly feel and Microsoft has spent a lot of
time and effort getting the Start Menu response just right.
Microsoft has also recognized the need for improved desktop responsiveness, which gives the
impression that the computer is responding to the user and that they are in control – something
that was often lacking with Vista.
You can also expect faster boot times. And the boot sequence is now not only prettier than it was
with Vista, but it’s speedier too.

2. Compatibility

In simple terms, compatibility on Windows 7 will be far better than it was with Vista. Many
programs that individuals and companies used on Windows XP did not work immediately and
required updates, but with Windows 7 almost all applications that work on Vista should still run.

3. Lower Hardware Requirements

Vista gained a reputation for making even the beefiest hardware look rather ordinary. Windows 7,
however, will run well on lower end hardware, making the transition from Window XP less painful.

Microsoft is even pushing Windows 7 for netbooks. This could provide a modern replacement
for Windows XP, which has found a new lease of life as the OS of choice on netbooks, supplanting
Linux. The downside is that Windows 7 Starter Edition, as it will be called, will be limited to only
three applications running at the same time.

4. Search and Organization

One of the best things about Windows 7 is the improved search tool, which now rivals Mac OS X’s
Spotlight to be able to find what you need quickly and easily. For example, typing ‘mouse’ will bring
up the mouse option within the control panel or typing a word will display it and split it up neatly
into files, folders and applications.
Also introduced is the concept of Libraries, which takes the ‘My Documents’ concept a stage
further. The various Libraries, such as Documents and Pictures, will watch multiple locations which
you can add yourself, so you don’t have to keep everything in one place.

5. Safety and Security

New security features in Windows include two new authentication methods tailored towards
touchscreens (PINs and picture passwords), the addition of antivirus capabilities
to Windows Defender (bringing it in parity with Microsoft Security Essentials) Smart Screen filtering
integrated into Windows, and support for the "Secure Boot" functionality on UEFI systems to
protect against malware infecting the boot process. Family Safety offers Parental controls, which
allows parents to monitor and manage their children's activities on a device with activity reports
and safety controls. Windows 8 also provides integrated system recovery through the new
"Refresh" and "Reset" functions, including system recovery from USB drive. Windows 8's first
security patches would be released on November 13, 2012; it would contain three fixes deemed
"critical" by the company.

6. Interface and Desktop

Windows introduces significant changes to the operating system's user interface, many of which
are aimed at improving its experience on tablet computers and other touchscreen devices.
The new user interface is based on Microsoft's Metro design language, and uses a Start screen
similar to that of Windows Phone as the primary means of launching applications. The Start screen
displays a customizable array of tiles linking to various apps and desktop programs, some of which
can display constantly updated information and content through "live tiles". As a form of
multitasking, apps can be snapped to the side of a screen. Alongside the traditional Control Panel,
a new simplified and touch-optimized settings app known as "PC Settings" is used for
basic configuration and user settings. It does not include many of the advanced options still
accessible from the normal Control Panel.

Microsoft Windows 8.1

7. Taskbar/Start menu

At first glance, the task bar looks like nothing has much has changed since Vista. In fact, that’s not
the case and it’s a lot more powerful. Microsoft is now making best use of its aero technology. By
default, taskbar icons are now larger and items are grouped together and are not labelled with
clumsy text.

If you have multiple Word documents or Windows Explorer windows open then you’ll see a stack
appear on the task bar. Hover the mouse over the app and each Window will be visible in a
thumbnail. Hover over each thumbnail and it will become visible, while all other
open windows temporarily disappear, save for their outlines. You can close each document or
Window down from the thumbnail directly or click on it to bring it to the front.

In the Start menu, a small arrow to the right of applications such as Word now expands to give a
list of recent documents and any can be pinned so you can keep one permanently on the list.

Advantages and Disadvantages of Microsoft Windows

The biggest advantage of Windows is that it provides ready-made solutions that can be
implemented by just about anyone who’s ever used a computer.

Microsoft Office is also 100% compatible with any file or document produced in the office space in
America. In fact, MS Office isn’t compatible with other software and systems, so much as other
software and systems strive to be compatible with Office!

Finally, software services are in large supply when it comes to Windows. From Microsoft’s official
services, to Maryland software support, to Microsoft certification training for individuals, there is no
lack of software support for Windows.

Of course, Windows detractors will tell you that there is more need for software services when it
comes to Windows. And while this worldwide operating system is far from trash, it is often not as
stable as its Mac or Linux counterparts.
The only other major disadvantage of using Windows in the workplace is that over 95% of all
viruses and malicious software are written for the Windows OS. This means you have to double-
down all security measures if you’re using Microsoft software across the board.

DIFFERENCE BETWEEN DOS AND WINDOWS


S.NO DOS WINDOW

While windows are multitasking

1. DOS is single tasking operating system. operating systems.

2. It consumes low power. While windows consume high power.

It consumes less memory in comparison of

3. windows. While it consumes more memory.

4. DOS does not support networking. While window supports networking.

5. DOS is complex in terms of using. Whereas it is simple for using.

6. DOS does not share time. While window can share time.

Whereas windows are the graphical

7. DOS is a command line operating system. operating systems.

DOS operating system is less preferred than While windows are more preferred by

8. windows. the users in comparison of DOS.

In DOS operating system multimedia is not While windows support multimedia

9. supported such as: Games, movies,songs etc. such as: Games, movies,songs etc.

In DOS operation systems, operation are While in windows OS, operation are

10. performed speedily than windows OS. performed slowly than DOS OS.

There is only one window opened at a time in While in windows, multiple windows

11. DOS. can be opened at a time.

UNIX OPERATING SYSTEM


Unix and Unix-like operating systems are a family of computer operating systems that are derived from
the original Unix System from Bell Labs.

Initial proprietary derivatives included the HP-UX and the SunOS systems. However, growing
incompatibility between these systems led to the creation of interoperability standards like POSIX.
Modern POSIX systems include Linux, its variants, and Mac OS.
UNIX is the most powerful and popular multi-user and multi-tasking Operating System. The basic
concepts of UNIX were originated in the Multics project of 1969. The Multics system was intended as a
time-sharing system that would allow multiple users to simultaneously access a mainframe computer.

Ken Thompson, Dennis Ritchie, and others developed the basic building blocks of Unix including a
hierarchical file system, i.e., the concepts of processes and a command line interpreter for the PDP-7.
From there, multiple generations of Unix were developed for various machines.

Growing incompatibility between these systems led to the creation of interoperability standards like
POSIX and Single UNIX Specification.

UNIX programs are designed around some core philosophies that include requirements like single
purpose, interoperable, and working with a standardized text interface. UNIX systems are built around
a core kernel that manages the system and the other processes.

Kernel subsystems may include process management, file management, memory management,
network management and others.

There are several prominent features of UNIX, and few among them are stated below:
 It is a multi-user system where the same resources can be shared by different users.
 It provides multi-tasking, wherein each user can execute many processes at the same time.
 It was the first operating system that was written in a high-level language (C Language).
This made it easy to port to other machines with minimum adaptations.
 It provides a hierarchical file structure which allows easier access and maintenance of data.
 Unix has built-in networking functions so that different users can easily exchange
information.
 Unix functionality can be extended through user programs built on a standard programming
interface.

UNIX Architecture

We will understand how user commands are executed in UNIX. User commands are often entered
on a command line interface that is provided by a ‘shell’. The shell is a program that reads the user
commands, evaluates it, and then prints the result. For evaluating the command, the shell may
execute other commands, or pass them to the ‘kernel’.

The kernel is the core of the operating system that directly interacts with the underlying hardware
to provide a set of standard services.
Difference between Unix and Linux –
Linux is essentially a clone of Unix. But, basic differences are shown below:
LINUX UNIX

The source code of Linux is freely available to The source code of Unix is not

its users freely available general public

It has graphical user interface along with It only has command line

command line interface interface

Linux OS is portable, flexible, and can be

executed in different hard drives Unix OS is not portable

Different version of Linux are Ubuntu, Linux Different version of Unix are

Mint, RedHot, Solaries, etc. AIS, HP-UX, BSD, Iris, etc.

The file systems supported by Linux are as The file systems supported by

follows: xfs, ramfs, vfat, cramfsm, ext3, ext4, Unix are as follows: zfs, js, hfx,

ext2, ext1, ufs, autofs, devpts, ntfs gps, xfs, vxfs

INTRODUCTION TO PROGRAMMING LANGUAGES


A computer is a computational device which is used to process the data under the control of a
computer program.
Program is a sequence of instruction along with data. While executing the program, raw data is
processed into a desired output format.
These computer programs are written in a programming language which is high level languages.
High level languages are nearly human languages which are more complex then the computer
understandable language which are called machine language, or low level language.
Between high-level language and machine language there are assembly language also called
symbolic machine code.

Assembly languages are particularly computer architecture specific. Utility program (Assembler) is
used to convert assembly code into executable machine code.

High Level Programming Language are portable but require Interpretation or compiling toconvert it
into a machine language which is computer understood.
Programming Language- it is vocabulary and a collection of rules that command a
computer, devices, and applications to work according to the written codes. The
programming language enables us to write efficient programs and develop online solutions
such as- mobile applications, web applications, and games, etc.
Programming is used to automate, maintain, assemble, measure and interpret the
processing of the data and information. It helps in accelerating the input and output of the
devices or applications.

Hierarchy of Computer language –

There have been many programming language some of them are listed below:

C Python C++

C# R Ruby

COBOL ADA Java

Fortran BASIC Altair BASIC

True BASIC Visual BASIC GW BASIC

QBASIC PureBASIC PASCAL

Turbo Pascal GO ALGOL

LISP SCALA Swift

Rust Prolog Reia

Racket Scheme Shimula

Perl PHP Java Script

CoffeeScript VisualFoxPro Babel


Logo Lua Smalltalk

Matlab F F#

Dart Datalog dbase

Haskell dylan Julia

ksh metro Mumps

Nim OCaml pick

TCL D CPL

Curry ActionScript Erlang

Clojure DarkBASCIC Assembly

Characteristics of a programming Language –


 A programming language must be simple, easy to learn and use, have good readability and
human recognizable.
 Abstraction is a must-have Characteristics for a programming language in which ability to
define the complex structure and then its degree of usability comes.
 A portable programming language is always preferred.
 Programming language’s efficiency must be high so that it can be easily converted into a
machine code and executed consumes little space in memory.
 A programming language should be well structured and documented so that it is suitable for
application development.
 Necessary tools for development, debugging, testing, and maintenance of a program must be
provided by a programming language.
 A programming language should provide single environment known as Integrated
Development Environment (IDE).
 A programming language must be consistent in terms of syntax and semantics.

COMPILER AND INTERPRETER


What is Compiler?
A compiler is a computer program that transforms code written in a high-level programming
language into the machine code. It is a program which translates the human-readable code to a
language a computer processor understands (binary 1 and 0 bits). The computer processes the
machine code to perform the corresponding tasks.

A compiler should comply with the syntax rule of that programming language in which it is written.
However, the compiler is only a program and cannot fix errors found in that program. So, if you
make a mistake, you need to make changes in the syntax of your program. Otherwise, it will not
compile.
What is Interpreter?
An interpreter is a computer program, which coverts each high-level program statement into the
machine code. This includes source code, pre-compiled code, and scripts. Both compiler and
interpreters do the same job which is converting higher level programming language to machine
code. However, a compiler will convert the code into machine code (create an exe) before program
run. Interpreters convert code into machine code when the program is run.

HIGH-LEVEL LANGUAGES

High-level languages, like C, C++, JAVA, etc., are very near to English. It makes programming
process easy. However, it must be translated into machine language before execution. This
translation process is either conducted by either a compiler or an interpreter. Also known as
source code.

MACHINE CODE

Machine languages are very close to the hardware. Every computer has its machine language. A
machine language programs are made up of series of binary pattern. (Eg. 110110) It represents
the simple operations which should be performed by the computer. Machine language programs
are executable so that they can be run directly.

OBJECT CODE

On compilation of source code, the machine code generated for different processors like Intel,
AMD, an ARM is different. tTo make code portable, the source code is first converted to Object
Code. It is an intermediary code (similar to machine code) that no processor will understand. At
run time, the object code is converted to the machine code of the underlying platform.

Java is both Compiled and Interpreted.

To exploit relative advantages of compilers are interpreters some programming language like Java
are both compiled and interpreted. The Java code itself is compiled into Object Code. At run time,
the JVM interprets the Object code into machine code of the target computer.

Difference between Compiler and Interpreter


INTERPRETER COMPILER

Scans the entire program and translates it as a


Translates program one statement at a time. whole into machine code.

It takes less amount of time to analyze the It takes large amount of time to analyze the
source code but the overall execution time is source code but the overall execution time is
slower. comparatively faster.

Generates intermediate object code which


No intermediate object code is generated, further requires linking, hence requires more
hence are memory efficient. memory.

Continues translating the program until the first It generates the error message only after
error is met, in which case it stops. Hence scanning the whole program. Hence debugging
debugging is easy. is comparatively hard.

Programming language like Python, Ruby use Programming language like C, C++ use
interpreters. compilers.

Generations of programming language


Programming languages have been developed over the year in a phased manner. Each phase of
developed has made the programming language more user-friendly, easier to use and more
powerful. Each phase of improved made in the development of the programming languages can
be referred to as a generation. The programming language in terms of their performance reliability
and robustness can be grouped into five different generations,

1. First generation languages (1GL)


2. Second generation languages (2GL)
3. Third generation languages (3GL)
4. Fourth generation languages (4GL)
5. Fifth generation languages (5GL)

1. First Generation Language (Machine language)

The first generation programming language is also called low-level programming language
because they were used to program the computer system at a very low level of abstraction. i.e. at
the machine level. The machine language also referred to as the native language of the computer
system is the first generation programming language. In the machine language, a programmer
only deals with a binary number.

Advantages of first generation language

 They are translation free and can be directly executed by the computers.
 The programs written in these languages are executed very speedily and efficiently by the
CPU of the computer system.
 The programs written in these languages utilize the memory in an efficient manner because
it is possible to keep track of each bit of data.
2. Second Generation language (Assembly Language)

The second generation programming language also belongs to the category of low-level-
programming language. The second generation language comprises assembly languages that use
the concept of mnemonics for the writing program. In the assembly language, symbolic names are
used to represent the opcode and the operand part of the instruction.

Advantages of second generation language

 It is easy to develop understand and modify the program developed in these languages are
compared to those developed in the first generation programming language.
 The programs written in these languages are less prone to errors and therefore can be
maintained with a great case.

3. Third Generation languages (High-Level Languages)

The third generation programming languages were designed to overcome the various limitations
of the first and second generation programming languages. The languages of the third and later
generation are considered as a high-level language because they enable the programmer to
concentrate only on the logic of the programs without considering the internal architecture of the
computer system.

Advantages of third generation programming language

 It is easy to develop, learn and understand the program.


 As the program written in these languages are less prone to errors they are easy to
maintain.
 The program written in these languages can be developed in very less time as compared to
the first and second generation language.

Examples: FORTRAN, ALGOL, COBOL, C++, C

4. Fourth generation language (Very High-level Languages)

The languages of this generation were considered as very high-level programming languages
required a lot of time and effort that affected the productivity of a programmer. The fourth
generation programming languages were designed and developed to reduce the time, cost and
effort needed to develop different types of software applications.

Advantages of fourth generation languages

 These programming languages allow the efficient use of data by implementing the various
database.
 They require less time, cost and effort to develop different types of software applications.
 The program developed in these languages are highly portable as compared to the
programs developed in the languages of other generation.

Examples: SOL, CSS, coldfusion


5. Fifth generation language (Artificial Intelligence Language)

The programming languages of this generation mainly focus on constraint programming. The
major fields in which the fifth generation programming language are employed are Artificial
Intelligence and Artificial Neural Networks

Advantages of fifth generation languages

 These languages can be used to query the database in a fast and efficient manner.
 In this generation of language, the user can communicate with the computer system in a
simple and an easy manner.

Examples: mercury, prolog, OPS5

COMPUTER VIRUS
 A computer virus is a malicious program that self-replicates by copying itself to another
program. In other words, the computer virus spreads by itself into other executable code or
documents.
 The purpose of creating a computer virus is to infect vulnerable systems, gain admin control
and steal user sensitive data.
 Hackers design computer viruses with malicious intent and prey on online users by tricking
them.
 One of the ideal methods by which viruses spread is through emails – opening the attachment
in the email, visiting an infected website, clicking on an executable file, or viewing an infected
advertisement can cause the virus to spread to your system.
 Besides that, infections also spread while connecting with already infected removable storage
devices, such as USB drives.
 It is quite easy and simple for the viruses to sneak into a computer by dodging the defense
systems.
 A successful breach can cause serious issues for the user such as infecting other resources or
system software, modifying or deleting key functions or applications and copy/delete or encrypt
data.

The History of Computer Virus


 Robert Thomas, an engineer at BBN Technologies developed the first known computer virus in
the year 1971.
 The first virus was christened as the “Creeper” virus, and the experimental program carried out
by Thomas infected mainframes on ARPANET. The teletype message displayed on the screens
read, “I’m the creeper: Catch me if you can.”
 But the original wild computer virus, probably the first one to be tracked down in the history of
computer viruses was “Elk Cloner.”
 The Elk Cloner infected Apple II operating systems through floppy disks.
 The message displayed on infected Apple Computers was a humorous one.
 The virus was developed by Richard Skrenta, a teenager in the year 1982.
 Even though the computer viruses were designed as a prank, it also enlightened how a
malicious program could be installed in a computer’s memory and stop users from removing the
program.
 It was Fred Cohen, who coined the term “computer virus” and it was after a year in 1983.
 The term came into being when he attempted to write an academic paper titled “Computer
Viruses – Theory and Experiments” detailing about the malicious programs in his work.

Signs of Virus Infection


It is vital for any computer user to be aware of these warning signs –
• Slower system performance
• Pop-ups bombarding the screen
• Programs running on their own
• Files multiplying/duplicating on their own
• New files or programs in the computer
• Files, folders or programs getting deleted or corrupted
• The sound of a hard drive

How Does Virus Affect?


 By downloading files from the Internet.
 During the removable of media or drives.
 Through pen drive.
 Through e-mail attachments.
 Through unpatched software & services.
 Through unprotected or poor administrator passwords.

Impact of Virus

 Disrupts the normal functionality of respective computer system.


 Disrupts system network use.
 Modifies configuration setting of the system.
 Destructs data.
 Disrupts computer network resources.
 Destructs of confidential data.

Types of Virus
Following are the major types of computer virus −
Worms

Computer worm is similar to virus but is technically different from virus. It can replicate and spread
like virus but unlike viruses it don't need a host program to spread. Being able to self replicate it
can produce multiple copies of itself. It spreads through networks such as an email sent to an
infected email id can infect your system with computer worm.

Trojan Horse
Trojan horse is a malware like a virus or worm but it is technically different from both.
It can't replicate like virus and worm. Trojan horse hides itself in a program. Once you
install any such program the trojan horse enters into your computer. It can provide
unauthorized access to your computer, send your files to other computers and may
delete files or can make other unwanted changes in your computer.

Bombs
It is similar to Trojan Horse, but Logic bombs have some specialty; these include a timing device
and hence it will go off only at a particular date and time.

Other types of virus :


1. File Virus : This type of virus infects the system by appending itself to the end of a file. It
changes the start of a program so that the control jumps to its code. After the execution of its
code, the control returns back to the main program. Its execution is not even noticed. It is also
called Parasitic virus because it leaves no file intact but also leaves the host functional.
2. Boot sector Virus : It infects the boot sector of the system, executing every time system is
booted and before operating system is loaded. It infects other bootable media like floppy
disks. These are also known as memory virus as they do not infect file system.

3. Macro Virus : Unlike most virus which are written in low-level language(like C or assembly
language), these are written in high-level language like Visual Basic. These viruses are
triggered when a program capable of executing a macro is run. For example, macro virus can
be contained in spreadsheet files.
4. Source code Virus : It looks for source code and modifies it to include virus and to help
spread it.
5. Polymorphic Virus : A virus signature is a pattern that can identify a virus(a series of bytes
that make up virus code). So in order to avoid detection by antivirus a polymorphic virus
changes each time it is installed. The functionality of virus remains same but its signature is
changed.
6. Encrypted Virus : In order to avoid detection by antivirus, this type of virus exists in
encrypted form. It carries a decryption algorithm along with it. So the virus first decrypts and
then executes.
7. Stealth Virus : It is a very tricky virus as it changes the code that can be used to detect it.
Hence, the detection of virus becomes very difficult. For example, it can change the read
system call such that whenever user asks to read a code modified by virus, the original form
of code is shown rather than infected code.
8. Tunneling Virus : This virus attempts to bypass detection by antivirus scanner by installing
itself in the interrupt handler chain. Interception programs, which remain in the background of
an operating system and catch viruses, become disabled during the course of a tunneling
virus. Similar viruses install themselves in device drivers.
9. Multipartite Virus : This type of virus is able to infect multiple parts of a system including boot
sector,memory and files. This makes it difficult to detect and contain.

10. Armored Virus : An armored virus is coded to make it difficult for antivirus to unravel and
understand. It uses a variety of techniques to do so like fooling antivirus to believe that it lies
somewhere else than its real location or using compression to complicate its code.

11. Resident virus: It stays permanently in the primary memory (RAM) of computer. When you
start the computer it becomes active and corrupts the files and programs running on the computer.

Virus Detection
The most fundamental method of detection of virus is to check the functionality of your computer
system; a virus affected computer does not take command properly.
However, if there is antivirus software in your computer system, then it can easily check programs
and files on a system for virus signatures.

Virus Preventive Measures


Let us now see the different virus preventive measures. A computer system can be protected
from virus through the following −

 Installation of effective antivirus software.


 Patching up the operating system.
 Patching up the client software.
 Putting highly secured Passwords.
 Use of Firewalls.

Most Effective Antivirus


Following are the most popular and effective antivirus from which you can choose one for your
personal computer −

 McAfee Antivirus Plus


 Symantec Norton Antivirus
 Avast Pro Antivirus
 Bitdefender Antivirus Plus
 Kaspersky Anti-Virus
UNIT-3
Computer Network and Internet

Computer Network tutorial provides basic and advanced concepts of Data Communication & Networks
(DCN). Our Computer Networking Tutorial is designed for beginners and professionals.

Our Computer Network tutorial includes all topics of Computer Network such as introduction, features,
types of computer network, architecture, hardware, software, internet, intranet, website, LAN, WAN, etc.

What is Computer Network?


A computer network is a set of devices connected through links. A node can be computer, printer, or any
other device capable of sending or receiving the data. The links connecting the nodes are known as
communication channels.

Computer Network uses distributed processing in which task is divided among several computers. Instead,
a single computer handles an entire task, each separate computer handles a subset.

What is a Computer Network?


o Computer Network is a group of computers connected with each other through wires, optical
fibres or optical links so that various devices can interact with each other through a network.
o The aim of the computer network is the sharing of resources among various devices.
o In the case of computer network technology, there are several types of networks that vary from
simple to complex level.
OSI Model
o OSI stands for Open System Interconnection
o OSI a reference model that describes how information from a software application in
one computer moves through a physical medium to the software application in another computer.
o OSI consists of seven layers, and each layer performs a particular network function.
o OSI model was developed by the International Organization for Standardization (ISO) in 1984, and it is
now considered as an architectural model for the inter-computer communications.
o OSI model divides the whole task into seven smaller and manageable tasks. Each layer is assigned a
particular task.
o Each layer is self-contained, so that task assigned to each layer can be performed independently.

Characteristics of OSI Model:

o The OSI model is divided into two layers: upper layers and lower layers.
o The upper layer of the OSI model mainly deals with the application related issues, and they are
implemented only in the software. The application layer is closest to the end user. Both the end user
and the application layer interact with the software applications. An upper layer refers to the layer just
above another layer.
o The lower layer of the OSI model deals with the data transport issues. The data link layer and the
physical layer are implemented in hardware and software. The physical layer is the lowest layer of the
OSI model and is closest to the physical medium. The physical layer is mainly responsible for placing the
information on the physical medium.

Functions of the OSI Layers

There are the seven OSI layers. Each layer has different functions. A list of seven layers are given below:

1. Physical Layer
2. Data-Link Layer
3. Network Layer
4. Transport Layer
5. Session Layer
6. Presentation Layer
7. Application Layer

Physical layer

o The main functionality of the physical layer is to transmit the individual bits from one node to another
node.
o It is the lowest layer of the OSI model.
o It establishes, maintains and deactivates the physical connection.
o It specifies the mechanical, electrical and procedural network interface specifications.
Functions of a Physical layer:

o Line Configuration: It defines the way how two or more devices can be connected physically.
o Data Transmission: It defines the transmission mode whether it is simplex, half-duplex or full-duplex
mode between the two devices on the network.
o Topology: It defines the way how network devices are arranged.
o Signals: It determines the type of the signal used for transmitting the information.

Data-Link Layer

o This layer is responsible for the error-free transfer of data frames.


o It defines the format of the data on the network.
o It provides a reliable and efficient communication between two or more devices.
o It is mainly responsible for the unique identification of each device that resides on a local network.
o It contains two sub-layers:
o Logical Link Control Layer
o It is responsible for transferring the packets to the Network layer of the receiver that is
receiving.
o It identifies the address of the network layer protocol from the header.
o It also provides flow control.
o Media Access Control Layer
o A Media access control layer is a link between the Logical Link Control layer and the
network's physical layer.
o It is used for transferring the packets over the network.

Functions of the Data-link layer


o Framing: The data link layer translates the physical's raw bit stream into packets known as Frames. The
Data link layer adds the header and trailer to the frame. The header which is added to the frame
contains the hardware destination and source address.

o Physical Addressing: The Data link layer adds a header to the frame that contains a destination address.
The frame is transmitted to the destination address mentioned in the header.
o Flow Control: Flow control is the main functionality of the Data-link layer. It is the technique through
which the constant data rate is maintained on both the sides so that no data get corrupted. It ensures
that the transmitting station such as a server with higher processing speed does not exceed the
receiving station, with lower processing speed.
o Error Control: Error control is achieved by adding a calculated value CRC (Cyclic Redundancy Check) that
is placed to the Data link layer's trailer which is added to the message frame before it is sent to the
physical layer. If any error seems to occurr, then the receiver sends the acknowledgment for the
retransmission of the corrupted frames.
o Access Control: When two or more devices are connected to the same communication channel, then
the data link layer protocols are used to determine which device has control over the link at a given
time.

Network Layer

o It is a layer 3 that manages device addressing, tracks the location of devices on the network.
o It determines the best path to move data from source to the destination based on the network
conditions, the priority of service, and other factors.
o The Data link layer is responsible for routing and forwarding the packets.
o Routers are the layer 3 devices, they are specified in this layer and used to provide the routing services
within an internetwork.
o The protocols used to route the network traffic are known as Network layer protocols. Examples of
protocols are IP and Ipv6.

Functions of Network Layer:

o Internetworking: An internetworking is the main responsibility of the network layer. It provides a logical
connection between different devices.

Internetworking ensures data communication among networks owned and operated by


different entities using a common data communication and the Internet Routing Protocol.

o Addressing: A Network layer adds the source and destination address to the header of the frame.
Addressing is used to identify the device on the internet.
o Routing: Routing is the major component of the network layer, and it determines the best optimal path
out of the multiple paths from source to the destination.
o Packetizing: A Network Layer receives the packets from the upper layer and converts them into packets.
This process is known as Packetizing. It is achieved by internet protocol (IP).

Transport Layer

o The Transport layer is a Layer 4 ensures that messages are transmitted in the order in which they are
sent and there is no duplication of data.
o The main responsibility of the transport layer is to transfer the data completely.
o It receives the data from the upper layer and converts them into smaller units known as segments.
o This layer can be termed as an end-to-end layer as it provides a point-to-point connection between
source and destination to deliver the data reliably.
The two protocols used in this layer are:

o Transmission Control Protocol


o It is a standard protocol that allows the systems to communicate over the internet.
o It establishes and maintains a connection between hosts.
o When data is sent over the TCP connection, then the TCP protocol divides the data into smaller
units known as segments. Each segment travels over the internet using multiple routes, and they
arrive in different orders at the destination. The transmission control protocol reorders the
packets in the correct order at the receiving end.
o User Datagram Protocol
o User Datagram Protocol is a transport layer protocol.
o It is an unreliable transport protocol as in this case receiver does not send any acknowledgment
when the packet is received, the sender does not wait for any acknowledgment. Therefore, this
makes a protocol unreliable.

Functions of Transport Layer:

o Service-point addressing: Computers run several programs simultaneously due to this reason, the
transmission of data from source to the destination not only from one computer to another computer
but also from one process to another process. The transport layer adds the header that contains the
address known as a service-point address or port address. The responsibility of the network layer is to
transmit the data from one computer to another computer and the responsibility of the transport layer
is to transmit the message to the correct process.
o Segmentation and reassembly: When the transport layer receives the message from the upper layer, it
divides the message into multiple segments, and each segment is assigned with a sequence number
that uniquely identifies each segment. When the message has arrived at the destination, then the
transport layer reassembles the message based on their sequence numbers.
o Connection control: Transport layer provides two services Connection-oriented service and
connectionless service. A connectionless service treats each segment as an individual packet, and they
all travel in different routes to reach the destination. A connection-oriented service makes a connection
with the transport layer at the destination machine before delivering the packets. In connection-
oriented service, all the packets travel in the single route.
o Flow control: The transport layer also responsible for flow control but it is performed end-to-end rather
than across a single link.
o Error control: The transport layer is also responsible for Error control. Error control is performed end-
to-end rather than across the single link. The sender transport layer ensures that message reach at the
destination without any error.
Session Layer

o It is a layer 3 in the OSI model.


o The Session layer is used to establish, maintain and synchronizes the interaction between
communicating devices.

Functions of Session layer:

o Dialog control: Session layer acts as a dialog controller that creates a dialog between two processes or
we can say that it allows the communication between two processes which can be either half-duplex or
full-duplex.
o Synchronization: Session layer adds some checkpoints when transmitting the data in a sequence. If
some error occurs in the middle of the transmission of data, then the transmission will take place again
from the checkpoint. This process is known as Synchronization and recovery.

Presentation Layer
o A Presentation layer is mainly concerned with the syntax and semantics of the information exchanged
between the two systems.
o It acts as a data translator for a network.
o This layer is a part of the operating system that converts the data from one presentation format to
another format.
o The Presentation layer is also known as the syntax layer.

Functions of Presentation layer:

o Translation: The processes in two systems exchange the information in the form of character strings,
numbers and so on. Different computers use different encoding methods, the presentation layer
handles the interoperability between the different encoding methods. It converts the data from sender-
dependent format into a common format and changes the common format into receiver-dependent
format at the receiving end.
o Encryption: Encryption is needed to maintain privacy. Encryption is a process of converting the sender-
transmitted information into another form and sends the resulting message over the network.
o Compression: Data compression is a process of compressing the data, i.e., it reduces the number of bits
to be transmitted. Data compression is very important in multimedia such as text, audio, video.

Application Layer

o An application layer serves as a window for users and application processes to access network service.
o It handles issues such as network transparency, resource allocation, etc.
o An application layer is not an application, but it performs the application layer functions.
o This layer provides the network services to the end-users.

Functions of Application layer:


o File transfer, access, and management (FTAM): An application layer allows a user to access the files in a
remote computer, to retrieve the files from a computer and to manage the files in a remote computer.
o Mail services: An application layer provides the facility for email forwarding and storage.
o Directory services: An application provides the distributed database sources and is used to provide that
global information about various objects.

TCP/IP model

o The TCP/IP model was developed prior to the OSI model.


o The TCP/IP model is not exactly similar to the OSI model.
o The TCP/IP model consists of five layers: the application layer, transport layer, network layer, data link
layer and physical layer.
o The first four layers provide physical standards, network interface, internetworking, and transport
functions that correspond to the first four layers of the OSI model and these four layers are represented
in TCP/IP model by a single layer called the application layer.
o TCP/IP is a hierarchical protocol made up of interactive modules, and each of them provides specific
functionality.

Here, hierarchical means that each upper-layer protocol is supported by two or more lower-level protocols.

Functions of TCP/IP layers:


It contains four layers, unlike seven layers in the OSI model. The layers are:
1. Process/Application Layer
2. Host-to-Host/Transport Layer
3. Internet Layer
4. Network Access/Link Layer

Network Access Layer

o A network layer is the lowest layer of the TCP/IP model.


o A network layer is the combination of the Physical layer and Data Link layer defined in the OSI reference
model.
o It defines how the data should be sent physically through the network.
o This layer is mainly responsible for the transmission of the data between two devices on the same
network.
o The functions carried out by this layer are encapsulating the IP datagram into frames transmitted by the
network and mapping of IP addresses into physical addresses.
o The protocols used by this layer are ethernet, token ring, FDDI, X.25, frame relay.

Internet Layer

o An internet layer is the second layer of the TCP/IP model.


o An internet layer is also known as the network layer.
o The main responsibility of the internet layer is to send the packets from any network, and they arrive at
the destination irrespective of the route they take.
Following are the protocols used in this layer are:

IP Protocol: IP protocol is used in this layer, and it is the most significant part of the entire TCP/IP suite.

Following are the responsibilities of this protocol:

o IP Addressing: This protocol implements logical host addresses known as IP addresses. The IP addresses
are used by the internet and higher layers to identify the device and to provide internetwork routing.
o Host-to-host communication: It determines the path through which the data is to be transmitted.
o Data Encapsulation and Formatting: An IP protocol accepts the data from the transport layer protocol.
An IP protocol ensures that the data is sent and received securely, it encapsulates the data into message
known as IP datagram.
o Fragmentation and Reassembly: The limit imposed on the size of the IP datagram by data link layer
protocol is known as Maximum Transmission unit (MTU). If the size of IP datagram is greater than the
MTU unit, then the IP protocol splits the datagram into smaller units so that they can travel over the
local network. Fragmentation can be done by the sender or intermediate router. At the receiver side, all
the fragments are reassembled to form an original message.
o Routing: When IP datagram is sent over the same local network such as LAN, MAN, WAN, it is known as
direct delivery. When source and destination are on the distant network, then the IP datagram is sent
indirectly. This can be accomplished by routing the IP datagram through various devices such as routers.

ARP Protocol

o ARP stands for Address Resolution Protocol.


o ARP is a network layer protocol which is used to find the physical address from the IP address.
o The two terms are mainly associated with the ARP Protocol:
o ARP request: When a sender wants to know the physical address of the device, it broadcasts the
ARP request to the network.
o ARP reply: Every device attached to the network will accept the ARP request and process the
request, but only recipient recognize the IP address and sends back its physical address in the
form of ARP reply. The recipient adds the physical address both to its cache memory and to the
datagram header

ICMP Protocol

o ICMP stands for Internet Control Message Protocol.


o It is a mechanism used by the hosts or routers to send notifications regarding datagram problems back
to the sender.
o A datagram travels from router-to-router until it reaches its destination. If a router is unable to route
the data because of some unusual conditions such as disabled links, a device is on fire or network
congestion, then the ICMP protocol is used to inform the sender that the datagram is undeliverable.
o An ICMP protocol mainly uses two terms:
o ICMP Test: ICMP Test is used to test whether the destination is reachable or not.
o ICMP Reply: ICMP Reply is used to check whether the destination device is responding or not.
o The core responsibility of the ICMP protocol is to report the problems, not correct them. The
responsibility of the correction lies with the sender.
o ICMP can send the messages only to the source, but not to the intermediate routers because the IP
datagram carries the addresses of the source and destination but not of the router that it is passed to.

Transport Layer

The transport layer is responsible for the reliability, flow control, and correction of data which is being sent
over the network.

The two protocols used in the transport layer are User Datagram protocol and Transmission control protocol.

o User Datagram Protocol (UDP)


o It provides connectionless service and end-to-end delivery of transmission.
o It is an unreliable protocol as it discovers the errors but not specify the error.
o User Datagram Protocol discovers the error, and ICMP protocol reports the error to the sender
that user datagram has been damaged.
o UDP consists of the following fields:
Source port address: The source port address is the address of the application program that has
created the message.
Destination port address: The destination port address is the address of the application program
that receives the message.
Total length: It defines the total number of bytes of the user datagram in bytes.
Checksum: The checksum is a 16-bit field used in error detection.
o UDP does not specify which packet is lost. UDP contains only checksum; it does not contain any
ID of a data segment.

o Transmission Control Protocol (TCP)


o It provides a full transport layer services to applications.
o It creates a virtual circuit between the sender and receiver, and it is active for the duration of
the transmission.
o TCP is a reliable protocol as it detects the error and retransmits the damaged frames. Therefore,
it ensures all the segments must be received and acknowledged before the transmission is
considered to be completed and a virtual circuit is discarded.
o At the sending end, TCP divides the whole message into smaller units known as segment, and
each segment contains a sequence number which is required for reordering the frames to form
an original message.
o At the receiving end, TCP collects all the segments and reorders them based on sequence
numbers.

Application Layer

o An application layer is the topmost layer in the TCP/IP model.


o It is responsible for handling high-level protocols, issues of representation.
o This layer allows the user to interact with the application.
o When one application layer protocol wants to communicate with another application layer, it forwards
its data to the transport layer.
o There is an ambiguity occurs in the application layer. Every application cannot be placed inside the
application layer except those who interact with the communication system. For example: text editor
cannot be considered in application layer while web browser using HTTP protocol to interact with the
network where HTTP protocol is an application layer protocol.

Following are the main protocols used in the application layer:


o HTTP: HTTP stands for Hypertext transfer protocol. This protocol allows us to access the data over the
world wide web. It transfers the data in the form of plain text, audio, video. It is known as a Hypertext
transfer protocol as it has the efficiency to use in a hypertext environment where there are rapid jumps
from one document to another.
o SNMP: SNMP stands for Simple Network Management Protocol. It is a framework used for managing
the devices on the internet by using the TCP/IP protocol suite.
o SMTP: SMTP stands for Simple mail transfer protocol. The TCP/IP protocol that supports the e-mail is
known as a Simple mail transfer protocol. This protocol is used to send the data to another e-mail
address.
o DNS: DNS stands for Domain Name System. An IP address is used to identify the connection of a host to
the internet uniquely. But, people prefer to use the names instead of addresses. Therefore, the system
that maps the name to the address is known as Domain Name System.
o TELNET: It is an abbreviation for Terminal Network. It establishes the connection between the local
computer and remote computer in such a way that the local terminal appears to be a terminal at the
remote system.
o FTP: FTP stands for File Transfer Protocol. FTP is a standard internet protocol used for transmitting the
files from one computer to another computer.

PROTOCOLS
In the world of technology, there are vast numbers of users' communicating with different devices in different
languages. That also includes many ways in which they transmit data along with the different software they
implement. So, communicating worldwide will not be possible if there were no fixed 'standards' that will
govern the way user communicates for data as well as the way our devices treat those data. Here we will be
discussing these standard set of rules.
Yes, we're talking about "protocols" which are set of rules that help in governing the way a particular
technology will function for communication. In other words, it can be said that the protocols are digital
languages implemented in the form of networking algorithms. There are different networks and network
protocols, user's use while surfing.

Types of Protocols
There are various types of protocols that support a major and compassionate role in communicating with
different devices across the network. These are:

1. Transmission Control Protocol (TCP)


2. Internet Protocol (IP)
3. User Datagram Protocol (UDP)
4. Post office Protocol (POP)
5. Simple mail transport Protocol (SMTP)
6. File Transfer Protocol (FTP)
7. Hyper Text Transfer Protocol (HTTP)
8. Hyper Text Transfer Protocol Secure (HTTPS)
9. Telnet
10. Gopher

1. Transmission Control Protocol (TCP): TCP is a popular communication protocol which is used for
communicating over a network. It divides any message into series of packets that are sent from source to
destination and there it gets reassembled at the destination.
2. Internet Protocol (IP): IP is designed explicitly as addressing protocol. It is mostly used with TCP. The IP
addresses in packets help in routing them through different nodes in a network until it reaches the
destination system. TCP/IP is the most popular protocol connecting the networks.
3. User Datagram Protocol (UDP): UDP is a substitute communication protocol to Transmission Control Protocol
implemented primarily for creating loss-tolerating and low-latency linking between different applications.
4. Post office Protocol (POP): POP3 is designed for receiving incoming E-mails.
5. Simple mail transport Protocol (SMTP): SMTP is designed to send and distribute outgoing E-Mail.
6. File Transfer Protocol (FTP): FTP allows users to transfer files from one machine to another. Types of files may
include program files, multimedia files, text files, and documents, etc.
7. Hyper Text Transfer Protocol (HTTP): HTTP is designed for transferring a hypertext among two or more
systems. HTML tags are used for creating links. These links may be in any form like text or images. HTTP is
designed on Client-server principles which allow a client system for establishing a connection with the server
machine for making a request. The server acknowledges the request initiated by the client and responds
accordingly.
8. Hyper Text Transfer Protocol Secure (HTTPS): HTTPS is abbreviated as Hyper Text Transfer Protocol Secure is a
standard protocol to secure the communication among two computers one using the browser and other
fetching data from web server. HTTP is used for transferring data between the client browser (request) and
the web server (response) in the hypertext format, same in case of HTTPS except that the transferring of data
is done in an encrypted format. So it can be said that https thwart hackers from interpretation or modification
of data throughout the transfer of packets.
9. Telnet: Telnet is a set of rules designed for connecting one system with another. The connecting process here
is termed as remote login. The system which requests for connection is the local computer, and the system
which accepts the connection is the remote computer.
10. Gopher: Gopher is a collection of rules implemented for searching, retrieving as well as displaying documents
from isolated sites. Gopher also works on the client/server principle.

Some Other Protocols

Some other popular protocols act as co-functioning protocols associated with these primary protocols for core
functioning. These are:

 ARP (Address Resolution Protocol)


 DHCP (Dynamic Host Configuration Protocol)
 IMAP4 (Internet Message Access Protocol)
 SIP (Session Initiation Protocol)
 RTP (Real-Time Transport Protocol)
 RLP (Resource Location Protocol)
 RAP (Route Access Protocol)
 L2TP (Layer Two Tunnelling Protocol)
 PPTP (Point To Point Tunnelling Protocol)
 SNMP (Simple Network Management Protocol)
 TFTP (Trivial File Transfer Protocol)

Components Of Computer Network:


Major components of a computer network are:
NIC(National interface card)
NIC is a device that helps the computer to communicate with another device. The network interface card
contains the hardware addresses, the data-link layer protocol use this address to identify the system on
the network so that it transfers the data to the correct destination.

There are two types of NIC: wireless NIC and wired NIC.

o Wireless NIC: All the modern laptops use the wireless NIC. In Wireless NIC, a connection is made
using the antenna that employs the radio wave technology.
o Wired NIC: Cables use the wired NIC to transfer the data over the medium.

Hub
Hub is a central device that splits the network connection into multiple devices. When computer requests
for information from a computer, it sends the request to the Hub. Hub distributes this request to all the
interconnected computers.

Switches
Switch is a networking device that groups all the devices over the network to transfer the data to another
device. A switch is better than Hub as it does not broadcast the message over the network, i.e., it sends
the message to the device for which it belongs to. Therefore, we can say that switch sends the message
directly from source to the destination.
Cables and connectors
Cable is a transmission media that transmits the communication signals. There are three types of
cables:

o Twisted pair cable: It is a high-speed cable that transmits the data over 1Gbps or more.
o Coaxial cable: Coaxial cable resembles like a TV installation cable. Coaxial cable is more expensive
than twisted pair cable, but it provides the high data transmission speed.
o Fibre optic cable: Fibre optic cable is a high-speed cable that transmits the data using light
beams. It provides high data transmission speed as compared to other cables. It is more expensive
as compared to other cables, so it is installed at the government level.

Router
Router is a device that connects the LAN to the internet. The router is mainly used to connect the distinct
networks or connect the internet to multiple computers.

Modem
Modem connects the computer to the internet over the existing telephone line. A modem is not integrated
with the computer motherboard. A modem is a separate part on the PC slot found on the motherboard.

Uses Of Computer Network


o Resource sharing: Resource sharing is the sharing of resources such as programs, printers, and
data among the users on the network without the requirement of the physical location of the
resource and user.
o Server-Client model: Computer networking is used in the server-client model. A server is a
central computer used to store the information and maintained by the system administrator. Clients
are the machines used to access the information stored in the server remotely.
o Communication medium: Computer network behaves as a communication medium among the
users. For example, a company contains more than one computer has an email system which the
employees use for daily communication.
o E-commerce: Computer network is also important in businesses. We can do the business over the
internet. For example, amazon.com is doing their business over the internet, i.e., they are doing
their business over the internet.
Computer Network Types
A computer network is a group of computers linked to each other that enables the computer to
communicate with another computer and share their resources, data, and applications.

A computer network can be categorized by their size. A computer network is mainly of four types:

o LAN(Local Area Network)


o PAN(Personal Area Network)
o MAN(Metropolitan Area Network)
o WAN(Wide Area Network)

LAN(Local Area Network)


o Local Area Network is a group of computers connected to each other in a small area such as
building, office.
o LAN is used for connecting two or more personal computers through a communication medium such
as twisted pair, coaxial cable, etc.
o It is less costly as it is built with inexpensive hardware such as hubs, network adapters, and
ethernet cables.
o The data is transferred at an extremely faster rate in Local Area Network.
o Local Area Network provides higher security.
PAN(Personal Area Network)
o Personal Area Network is a network arranged within an individual person, typically within a range of
10 meters.
o Personal Area Network is used for connecting the computer devices of personal use is known as
Personal Area Network.
o Thomas Zimmerman was the first research scientist to bring the idea of the Personal Area
Network.
o Personal Area Network covers an area of 30 feet.
o Personal computer devices that are used to develop the personal area network are the laptop,
mobile phones, media player and play stations.

There are two types of Personal Area Network:

o Wired Personal Area Network


o Wireless Personal Area Network

Wireless Personal Area Network: Wireless Personal Area Network is developed by simply using wireless
technologies such as WiFi, Bluetooth. It is a low range network.
Wired Personal Area Network: Wired Personal Area Network is created by using the USB.

Examples Of Personal Area Network:


o Body Area Network: Body Area Network is a network that moves with a person. For example, a
mobile network moves with a person. Suppose a person establishes a network connection and then
creates a connection with another device to share the information.
o Offline Network: An offline network can be created inside the home, so it is also known as
a home network. A home network is designed to integrate the devices such as printers, computer,
television but they are not connected to the internet.
o Small Home Office: It is used to connect a variety of devices to the internet and to a corporate
network using a VPN

MAN(Metropolitan Area Network)


o A metropolitan area network is a network that covers a larger geographic area by interconnecting a
different LAN to form a larger network.
o Government agencies use MAN to connect to the citizens and private industries.
o In MAN, various LANs are connected to each other through a telephone exchange line.
o The most widely used protocols in MAN are RS-232, Frame Relay, ATM, ISDN, OC-3, ADSL, etc.
o It has a higher range than Local Area Network(LAN).
Uses Of Metropolitan Area Network:
o MAN is used in communication between the banks in a city.
o It can be used in an Airline Reservation.
o It can be used in a college within a city.
o It can also be used for communication in the military.

WAN(Wide Area Network)


o A Wide Area Network is a network that extends over a large geographical area such as states or
countries.
o A Wide Area Network is quite bigger network than the LAN.
o A Wide Area Network is not limited to a single location, but it spans over a large geographical area
through a telephone line, fibre optic cable or satellite links.
o The internet is one of the biggest WAN in the world.
o A Wide Area Network is widely used in the field of Business, government, and education.
What is Topology?

Topology defines the structure of the network of how all the components are interconnected to each other.
There are two types of topology: physical and logical topology.

Physical topology is the geometric representation of all the nodes in a network. N1 N2

Bus Topology BRIDGE

o The bus topology is designed in such a way that all the stations are connected through a single cable
known as a backbone cable.
o Each node is either connected to the backbone cable by drop cable or directly connected to the
backbone cable.
o When a node wants to send a message over the network, it puts a message over the network. All the
stations available in the network will receive the message whether it has been addressed or not.
o The bus topology is mainly used in 802.3 (ethernet) and 802.4 standard networks.
o The configuration of a bus topology is quite simpler as compared to other topologies.
o The backbone cable is considered as a "single lane" through which the message is broadcast to all the
stations.
o The most common access method of the bus topologies is CSMA (Carrier Sense Multiple Access).

CSMA: It is a media access control used to control the data flow so that data integrity is maintained, i.e., the
packets do not get lost. There are two alternative ways of handling the problems that occur when two nodes
send the messages simultaneously.

o CSMA CD: CSMA CD (Collision detection) is an access method used to detect the collision. Once the
collision is detected, the sender will stop transmitting the data. Therefore, it works on "recovery after
the collision".
o CSMA CA: CSMA CA (Collision Avoidance) is an access method used to avoid the collision by checking
whether the transmission media is busy or not. If busy, then the sender waits until the media becomes
idle. This technique effectively reduces the possibility of the collision. It does not work on "recovery
after the collision".

Advantages of Bus topology:


o Low-cost cable: In bus topology, nodes are directly connected to the cable without passing through a
hub. Therefore, the initial cost of installation is low.
o Moderate data speeds: Coaxial or twisted pair cables are mainly used in bus-based networks that
support upto 10 Mbps.
o Familiar technology: Bus topology is a familiar technology as the installation and troubleshooting
techniques are well known, and hardware components are easily available.
o Limited failure: A failure in one node will not have any effect on other nodes.

Disadvantages of Bus topology:


o Extensive cabling: A bus topology is quite simpler, but still it requires a lot of cabling.
o Difficult troubleshooting: It requires specialized test equipment to determine the cable faults. If any
fault occurs in the cable, then it would disrupt the communication for all the nodes.
o Signal interference: If two nodes send the messages simultaneously, then the signals of both the nodes
collide with each other.
o Reconfiguration difficult: Adding new devices to the network would slow down the network.
o Attenuation: Attenuation is a loss of signal leads to communication issues. Repeaters are used to
regenerate the signal.

Ring Topology

o Ring topology is like a bus topology, but with connected ends.


o The node that receives the message from the previous computer will retransmit to the next node.
o The data flows in one direction, i.e., it is unidirectional.
o The data flows in a single loop continuously known as an endless loop.
o It has no terminated ends, i.e., each node is connected to other node and having no termination point.
o The data in a ring topology flow in a clockwise direction.
o The most common access method of the ring topology is token passing.
o Token passing: It is a network access method in which token is passed from one node to another
node.
o Token: It is a frame that circulates around the network.

Working of Token passing


o A token moves around the network, and it is passed from computer to computer until it reaches the
destination.
o The sender modifies the token by putting the address along with the data.
o The data is passed from one device to another device until the destination address matches. Once the
token received by the destination device, then it sends the acknowledgment to the sender.
o In a ring topology, a token is used as a carrier.

Advantages of Ring topology:


o Network Management: Faulty devices can be removed from the network without bringing the network
down.
o Product availability: Many hardware and software tools for network operation and monitoring are
available.
o Cost: Twisted pair cabling is inexpensive and easily available. Therefore, the installation cost is very low.
o Reliable: It is a more reliable network because the communication system is not dependent on the
single host computer.

Disadvantages of Ring topology:


o Difficult troubleshooting: It requires specialized test equipment to determine the cable faults. If any
fault occurs in the cable, then it would disrupt the communication for all the nodes.
o Failure: The breakdown in one station leads to the failure of the overall network.
o Reconfiguration difficult: Adding new devices to the network would slow down the network.
o Delay: Communication delay is directly proportional to the number of nodes. Adding new devices
increases the communication delay.

Star Topology
o Star topology is an arrangement of the network in which every node is connected to the central hub,
switch or a central computer.
o The central computer is known as a server, and the peripheral devices attached to the server are known
as clients.
o Coaxial cable or RJ-45 cables are used to connect the computers.
o Hubs or Switches are mainly used as connection devices in a physical star topology.
o Star topology is the most popular topology in network implementation.

Advantages of Star topology


o Efficient troubleshooting: Troubleshooting is quite efficient in a star topology as compared to bus
topology. In a bus topology, the manager has to inspect the kilometers of cable. In a star topology, all
the stations are connected to the centralized network. Therefore, the network administrator has to go
to the single station to troubleshoot the problem.
o Network control: Complex network control features can be easily implemented in the star topology.
Any changes made in the star topology are automatically accommodated.
o Limited failure: As each station is connected to the central hub with its own cable, therefore failure in
one cable will not affect the entire network.
o Familiar technology: Star topology is a familiar technology as its tools are cost-effective.
o Easily expandable: It is easily expandable as new stations can be added to the open ports on the hub.
o Cost effective: Star topology networks are cost-effective as it uses inexpensive coaxial cable.
o High data speeds: It supports a bandwidth of approx 100Mbps. Ethernet 100BaseT is one of the most
popular Star topology networks.

Disadvantages of Star topology


o A Central point of failure: If the central hub or switch goes down, then all the connected nodes will not
be able to communicate with each other.
o Cable: Sometimes cable routing becomes difficult when a significant amount of routing is required.

Tree topology

o Tree topology combines the characteristics of bus topology and star topology.
o A tree topology is a type of structure in which all the computers are connected with each other in
hierarchical fashion.
o The top-most node in tree topology is known as a root node, and all other nodes are the descendants of
the root node.
o There is only one path exists between two nodes for the data transmission. Thus, it forms a parent-child
hierarchy.

Advantages of Tree topology


o Support for broadband transmission: Tree topology is mainly used to provide broadband transmission,
i.e., signals are sent over long distances without being attenuated.
o Easily expandable: We can add the new device to the existing network. Therefore, we can say that tree
topology is easily expandable.
o Easily manageable: In tree topology, the whole network is divided into segments known as star
networks which can be easily managed and maintained.
o Error detection: Error detection and error correction are very easy in a tree topology.
o Limited failure: The breakdown in one station does not affect the entire network.
o Point-to-point wiring: It has point-to-point wiring for individual segments.

Disadvantages of Tree topology


o Difficult troubleshooting: If any fault occurs in the node, then it becomes difficult to troubleshoot the
problem.
o High cost: Devices required for broadband transmission are very costly.
o Failure: A tree topology mainly relies on main bus cable and failure in main bus cable will damage the
overall network.
o Reconfiguration difficult: If new devices are added, then it becomes difficult to reconfigure.

Mesh topology

o Mesh technology is an arrangement of the network in which computers are interconnected with each
other through various redundant connections.
o There are multiple paths from one computer to another computer.
o It does not contain the switch, hub or any central computer which acts as a central point of
communication.
o The Internet is an example of the mesh topology.
o Mesh topology is mainly used for WAN implementations where communication failures are a critical
concern.
o Mesh topology is mainly used for wireless networks.
o Mesh topology can be formed by using the formula:
Number of cables = (n*(n-1))/2;
Where n is the number of nodes that represents the network.

Mesh topology is divided into two categories:

o Fully connected mesh topology


o Partially connected mesh topology

o Full Mesh Topology: In a full mesh topology, each computer is connected to all the computers available
in the network.
o Partial Mesh Topology: In a partial mesh topology, not all but certain computers are connected to those
computers with which they communicate frequently.

Advantages of Mesh topology:

Reliable: The mesh topology networks are very reliable as if any link breakdown will not affect the
communication between connected computers.

Fast Communication: Communication is very fast between the nodes.

Easier Reconfiguration: Adding new devices would not disrupt the communication between other devices.

Disadvantages of Mesh topology


o Cost: A mesh topology contains a large number of connected devices such as a router and more
transmission media than other topologies.
o Management: Mesh topology networks are very large and very difficult to maintain and manage. If the
network is not monitored carefully, then the communication link failure goes undetected.
o Efficiency: In this topology, redundant connections are high that reduces the efficiency of the network.

Hybrid Topology
o The combination of various different topologies is known as Hybrid topology.
o A Hybrid topology is a connection between different links and nodes to transfer the data.
o When two or more different topologies are combined together is termed as Hybrid topology and if
similar topologies are connected with each other will not result in Hybrid topology. For example, if there
exist a ring topology in one branch of ICICI bank and bus topology in another branch of ICICI bank,
connecting these two topologies will result in Hybrid topology.

Advantages of Hybrid Topology


o Reliable: If a fault occurs in any part of the network will not affect the functioning of the rest of the
network.
o Scalable: Size of the network can be easily expanded by adding new devices without affecting the
functionality of the existing network.
o Flexible: This topology is very flexible as it can be designed according to the requirements of the
organization.
o Effective: Hybrid topology is very effective as it can be designed in such a way that the strength of the
network is maximized and weakness of the network is minimized.

Disadvantages of Hybrid topology


o Complex design: The major drawback of the Hybrid topology is the design of the Hybrid network. It is
very difficult to design the architecture of the Hybrid network.
o Costly Hub: The Hubs used in the Hybrid topology are very expensive as these hubs are different
from usual Hubs used in other topologies.
o Costly infrastructure: The infrastructure cost is very high as a hybrid network requires a lot of
cabling, network devices, etc.
Examples Of Wide Area Network:
o Mobile Broadband: A 4G network is widely used across a region or country.
o Last mile: A telecom company is used to provide the internet services to the customers in
hundreds of cities by connecting their home with fiber.
o Private network: A bank provides a private network that connects the 44 offices. This network is
made by using the telephone leased line provided by the telecom company.

Advantages Of Wide Area Network:


Following are the advantages of the Wide Area Network:

o Geographical area: A Wide Area Network provides a large geographical area. Suppose if the
branch of our office is in a different city then we can connect with them through WAN. The internet
provides a leased line through which we can connect with another branch.
o Centralized data: In case of WAN network, data is centralized. Therefore, we do not need to buy
the emails, files or back up servers.
o Get updated files: Software companies work on the live server. Therefore, the programmers get
the updated files within seconds.
o Exchange messages: In a WAN network, messages are transmitted fast. The web application like
Facebook, Whatsapp, Skype allows you to communicate with friends.
o Sharing of software and resources: In WAN network, we can share the software and other
resources like a hard drive, RAM.
o Global business: We can do the business over the internet globally.
o High bandwidth: If we use the leased lines for our company then this gives the high bandwidth.
The high bandwidth increases the data transfer rate which in turn increases the productivity of our
company.

Disadvantages of Wide Area Network:


The following are the disadvantages of the Wide Area Network:

o Security issue: A WAN network has more security issues as compared to LAN and MAN network as
all the technologies are combined together that creates the security problem.
o Needs Firewall & antivirus software: The data is transferred on the internet which can be
changed or hacked by the hackers, so the firewall needs to be used. Some people can inject the
virus in our system so antivirus is needed to protect from such a virus.
o High Setup cost: An installation cost of the WAN network is high as it involves the purchasing of
routers, switches.
o Troubleshooting problems: It covers a large area so fixing the problem is difficult.

Internetwork
o An internetwork is defined as two or more computer network LANs or WAN or computer network
segments are connected using devices, and they are configured by a local addressing scheme. This
process is known as internetworking.
o An interconnection between public, private, commercial, industrial, or government computer
networks can also be defined as internetworking.
o An internetworking uses the internet protocol.
o The reference model used for internetworking is Open System Interconnection(OSI).

Types Of Internetwork:
1. Extranet: An extranet is a communication network based on the internet protocol such
as Transmission Control protocol and internet protocol. It is used for information sharing. The access
to the extranet is restricted to only those users who have login credentials. An extranet is the lowest level
of internetworking. It can be categorized as MAN, WAN or other computer networks. An extranet cannot
have a single LAN, atleast it must have one connection to the external network.

2. Intranet: An intranet is a private network based on the internet protocol such as Transmission
Control protocol and internet protocol. An intranet belongs to an organization which is only accessible
by the organization's employee or members. The main aim of the intranet is to share the information
and resources among the organization employees. An intranet provides the facility to work in groups and
for teleconferences.
Intranet advantages:
o Communication: It provides a cheap and easy communication. An employee of the organization
can communicate with another employee through email, chat.
o Time-saving: Information on the intranet is shared in real time, so it is time-saving.
o Collaboration: Collaboration is one of the most important advantage of the intranet. The
information is distributed among the employees of the organization and can only be accessed by the
authorized user.
o Platform independency: It is a neutral architecture as the computer can be connected to another
device with different architecture.
o Cost effective: People can see the data and documents by using the browser and distributes the
duplicate copies over the intranet. This leads to a reduction in the cost.

Network Devices (Hub, Repeater, Bridge, Switch, Router,


Gateways and Brouter)
1. Repeater – A repeater operates at the physical layer. Its job is to regenerate the signal over the
same network before the signal becomes too weak or corrupted so as to extend the length to
which the signal can be transmitted over the same network. An important point to be noted about
repeaters is that they do not amplify the signal. When the signal becomes weak, they copy the
signal bit by bit and regenerate it at the original strength. It is a 2 port device.

2. Hub – A hub is basically a multiport repeater. A hub connects multiple wires coming from
different branches, for example, the connector in star topology which connects different stations.
Hubs cannot filter data, so data packets are sent to all connected devices. In other
words, collision domain of all hosts connected through Hub remains one. Also, they do not have
intelligence to find out best path for data packets which leads to inefficiencies and wastage.
Types of Hub
 Active Hub:- These are the hubs which have their own power supply and can clean, boost
and relay the signal along with the network. It serves both as a repeater as well as wiring
centre. These are used to extend the maximum distance between nodes.
 Passive Hub :- These are the hubs which collect wiring from nodes and power supply from
active hub. These hubs relay signals onto the network without cleaning and boosting them
and can’t be used to extend the distance between nodes.

3. Bridge – A bridge operates at data link layer. A bridge is a repeater, with add on the
functionality of filtering content by reading the MAC addresses of source and destination. It is
also used for interconnecting two LANs working on the same protocol. It has a single input and
single output port, thus making it a 2 port device.
Types of Bridges
Transparent Bridges:- These are the bridge in which the stations are completely unaware of
the
bridge’s existence i.e. whether or not a bridge is added or deleted from the network,
reconfiguration of
the stations is unnecessary. These bridges make use of two processes i.e. bridge forwarding
and bridge learning.

Source Routing Bridges:- In these bridges, routing operation is performed by source station
and the frame specifies which route to follow. The hot can discover frame by sending a special
frame called discovery frame, which spreads through the entire network using all possible
paths to destination.

4. Switch – A switch is a multiport bridge with a buffer and a design that can boost its
efficiency(a large number of ports imply less traffic) and performance. A switch is a data link
layer device. The switch can perform error checking before forwarding data, that makes it very
efficient as it does not forward packets that have errors and forward good packets selectively
to correct port only. In other words, switch divides collision domain of hosts, but broadcast
domain remains same.

5. Routers – A router is a device like a switch that routes data packets based on their IP
addresses. Router is mainly a Network Layer device. Routers normally connect LANs and WANs
together and have a dynamically updating routing table based on which they make decisions on
routing the data packets. Router divide broadcast domains of hosts connected through it.

6. Gateway – A gateway, as the name suggests, is a passage to connect two networks together
that may work upon different networking models. They basically work as the messenger agents
that take data from one system, interpret it, and transfer it to another system. Gateways are
also called protocol converters and can operate at any network layer. Gateways are generally
more complex than switch or router.
7. Brouter – It is also known as bridging router is a device which combines features of both
bridge and router. It can work either at data link layer or at network layer. Working as router, it
is capable of routing packets across networks and working as bridge, it is capable of filtering
local area network traffic.

SERVICES OF INTERNET -E-mail, FTP, Telnet


Email, discussion groups, long-distance computing, and file transfers are some of the important services provided by the Internet.
Email is the fastest means of communication with email one can also send software and certain forms of compressed digital
image as an attachment. News groups or discussion groups facilitate Internet user to join for various kinds of debate, discussion
and news sharing. Long-distance computing was an original inspiration for development of

ARPANET and does still provide a very useful service on Internet. Programmers can maintain accounts on distant, powerful
computers, executive programs. File transfer service allows Internet users to access remote machines and retrieve programs,
data or text.

(a) E-Mail (Electronic Mail)


E-mail or Electronic mail is a paperless method of sending messages, notes or letters from one person to another or even many
people at the same time via Internet. E-mail is very fast compared to the normal post. E-mail messages usually take only few
seconds to arrive at their destination. One can send messages anytime of the day or night, and, it will get delivered immediately.
You need not to wait for the post office to open and you don’t have to get worried about holidays. It works 24 hours a day and
seven days a week. What’s more, the copy of the message you have sent will be available whenever you want to look at it even
in the middle of the night. You have the privilege of sending something extra such as a file, graphics, images etc. along with your
e-mail. The biggest advantage of using e-mail is that it is cheap, especially when sending messages to other states or countries
and at the same time it can be delivered to a number of people around the world.

It allows you to compose note, get the address of the recipient and send it. Once the mail is received and read, it can be
forwarded replied. One can even store it for later use, or delete. In e-mail even the sender can request for delivery receipt and
read receipt from the recipient.

(i) Features of E-mail:

One-to-one or one-to-many communications

Instant communications

Physical presence of recipient is not required

Most inexpensive mail services, 24-hours a day and seven days a week

Encourages informal communications


(ii) Components of an E-mail Address As in the case of normal mail system, e-mail is also based upon the concept of a
recipient address. The email address provides all of the information required to get a message to the recipient from any where in
the world. Consider the e-mail ID.

abc@hotmail.com

In the above example john is the username of the person who will be sending/receiving the email. Hotmail is the mail server
where the username john has been registered and com is the type of organization on the internet which is hosting the mail/
server.

(b) FTP (File Transfer Protocol)

File Transfer Protocol, is an Internet utility software used to uploaded and download files. It gives access to directories or folders
on remote computers and allows software, data and text files to be transfer between different kinds of computers. FTP works on
the basis of same principle as that of Client/ Server. FTP “Client” is a program running on your computer that enables you to
communicate with remote computers. The FTP client takes FTP command and sends these as requests for information from the
remote computer known as FTP servers. To access remote FTP server it is required, but not necessary to have an account in the
FTP server. When the FTP client gets connected, FTP server asks for the identification in terms of User Login name and
password of the FTP client (Fig. 3.1). If one does not have an account in the remote FTP server, still he can connect to the server
using anonymous login.

Using anonymous login anyone can login in to a FTP server and can access public archives; anywhere in the world, without
having an account. One can easily Login to the FTP site with the username anonymous and e-mail address as password.

(i) Objectives of FTP : Provide flexibility and promote sharing of computer programs, files and data

Transfer data reliably and more efficiently over network

Encourage implicit or indirect use of remote computers using Internet

Shield a user from variations in storage systems among hosts.

(ii) The basic steps in an FTP session Start up your FTP client, by typing ftp on your system’s command line/’C>’ prompt (or,
if you are in a Windows, double-click on the FTP icon).

Give the FTP client an address to connect. This is the FTP server address to which the FTP client will get connected

Identify yourself to the FTP remote site by giving the Login Name
Give the remote site a password

Remote site will verify the Login Name/Password to allow the FTP client to access its files

Look directory for files in FTP server

Change Directories if requird

Set the transfer mode (optional);

Get the file(s) you want, and

Quit.

(c) Telnet (Remote Computing)


Telnet or remote computing is telecommunication utility software, which uses available telecommunication facility and allows you
become a user on a remote computer. Once you gain access to remote computer, you can use it for the intended purpose. The
TELNET works in a very step by step procedure. The commands typed on the client computer are sent to the local Internet
Service Provider (ISP), and then from the ISP to the remote computer that you have gained access. Most of the ISP provides
facility to TELENET into your own account from another city and check your e-mail while you are traveling or away on business.

The following steps are required for a TELNET session

Start up the TELNET program

Give the TELNET program an address to connect (some really nifty TELNET packages allow you to combine steps 1 and 2 into
one simple step)

Make a note of what the “escape character” is

Log in to the remote computer,

Set the “terminal emulation”

Play around on the remote computer, and

Quit.

(d)What is Web Conferencing?

Video conferencing or Video teleconferencing is a method of communicating by two-


way video and audio transmission with help of telecommunication technologies.

Web Conferencing is an online service by which you can hold live meetings, conferencing,
presentations and trainings via the internet particularly on TCP/IP connections. You can connect to the
conference either by telephone or using your computer’s speakers and microphone through
a VoIP connection.
Web conferencing usually allows real time point-to-point communication as well as multi task
communications from one sender to many receivers in separate locations. Depending on the service,
either an application (additional software) is downloaded and installed or a web-based application is
launched in the attendee’s browser. The newest open source technology for Web Conferencing is
Google’s WebRTC.

(e) World Wide Web (WWW)


 WWW is also known as W3. It offers a way to access documents spread over the several
servers over the internet. These documents may contain texts, graphics, audio, video,
hyperlinks. The hyperlinks allow the users to navigate between the documents.
 The development of the World Wide Web was begun in 1989 by Tim Berners-Lee and his
colleagues at CERN, an international scientific organization based in Geneva, Switzerland.
They created a protocol, HyperText Transfer Protocol (HTTP), which
standardized communication between servers and clients. Their text-based Web browser
was made available for general release in January 1992.
 World Wide Web, which is also known as a Web, is a collection of websites or web pages
stored in web servers and connected to local computers through the internet. These
websites contain text pages, digital images, audios, videos, etc. Users can access the
content of these sites from any part of the world over the internet using their devices such
as computers, laptops, cell phones, etc. The WWW, along with internet, enables the
retrieval and display of text and media to your device.
 The building blocks of the Web are web pages which are formatted in HTML and connected
by links called "hypertext" or hyperlinks and accessed by HTTP. These links are electronic
connections that link related pieces of information so that users can access the desired
information quickly. Hypertext offers the advantage to select a word or phrase from text
and thus to access other pages that provide additional information related to that word or
phrase.
 A web page is given an online address called a Uniform Resource Locator (URL). A
particular collection of web pages that belong to a specific URL is called a website,
e.g., www.facebook.com, www.google.com, etc. So, the World Wide Web is like a huge
electronic book whose pages are stored on multiple servers across the world.
 Small websites store all of their WebPages on a single server, but big websites or
organizations place their WebPages on different servers in different countries so that when
users of a country search their site they could get the information quickly from the nearest
server.
 So, the web provides a communication platform for users to retrieve and exchange
information over the internet. Unlike a book, where we move from one page to another in
a sequence, on World Wide Web we follow a web of hypertext links to visit a web page and
from that web page to move to other web pages. You need a browser, which is installed on
your computer, to access the Web.

Difference between World Wide Web and Internet:


Some people use the terms 'internet' and 'World Wide Web' interchangeably. They think they are
the same thing, but it is not so. Internet is entirely different from WWW. It is a worldwide
network of devices like computers, laptops, tablets, etc. It enables users to send emails to other
users and chat with them online. For example, when you send an email or chatting with someone
online, you are using the internet.
But, when you have opened a website like google.com for information, you are using the World
Wide Web; a network of servers over the internet. You request a webpage from your computer
using a browser, and the server renders that page to your browser. Your computer is called a
client who runs a program (web browser), and asks the other computer (server) for the
information it needs.

Chatting
On the Internet, chatting is talking to other people who are using the Internet at the
same time you are. Usually, this "talking" is the exchange of typed-in messages
requiring one site as the repository for the messages (or "chat site") and a group of
users who take part from anywhere on the Internet. In some cases, a private chat can
be arranged between two parties who meet initially in a group chat. Chats can be
ongoing or scheduled for a particular time and duration.

Most chats are focused on a particular topic of interest and some involve guest experts
or famous people who "talk" to anyone joining the chat. (Transcripts of a chat can be
archived for later reference.)

Online chat in a less stringent definition may be primarily any direct text-based or
video-based (webcams), one-on-one chat or one-to-many group chat (formally also
known as synchronous conferencing), using tools such as instant
messengers, Internet Relay Chat (IRC), talkers and possibly MUDs.

The expression online chat comes from the word chat which means "informal
conversation". Online chat includes web-based applications that allow
communication – often directly addressed, but anonymous between users in a
multi-user environment.

Web conferencing is a more specific online service, that is often sold as a service,
hosted on a web server controlled by the vendor.
The best (and most secure) chat apps
 Facebook Messenger. Facebook's foray into the world of mobile messaging is called Messenger.
...
 WhatsApp. ...
 Telegram. ...
 Signal. ...
 WeChat. ...
 Line. ...
 Skype. ...
 Viber.

Electronic newspaper
An electronic newspaper is a self-contained, reusable, and refreshable version of a
traditional newspaper that acquires and holds information electronically. (The electronic
newspaper should not be confused with newspapers that offer an online version at a Web site.)
An electronic newspaper is a self-contained, reusable, and refreshable version of a traditional
newspaper that acquires and holds information electronically.

Electronic Newspapers India

The Times of India


The Economic Times
Dainik Bhaskar
Hindustan Times
Dainik Jagran
The Indian Express
The Hindu etc..
Online shopping
Online shopping is a form of electronic commerce which allows consumers to directly
buy goods or services from a seller over the Internet using a web browser. Consumers find a
product of interest by visiting the website of the retailer directly or by searching among
alternative vendors using a shopping search engine, which displays the same product's
availability and pricing at different e-retailers. As of 2016, customers can shop online using a
range of different computers and devices, including desktop computers, laptops, tablet
computers and smart phones.
An online shop evokes the physical analogy of buying products or services at a regular "bricks-
and-mortar" retailer or shopping center; the process is called business-to-consumer (B2C)
online shopping. When an online store is set up to enable businesses to buy from other
businesses, the process is called business-to-business (B2B) online shopping. A typical online
store enables the customer to browse the firm's range of products and services, view photos or
images of the products, along with information about the product specifications, features and
prices.
Who provides online shopping?
Most retail stores also have a website that allows their customers to buy from
them online and either ship the items to their home or pick up at a nearby store
location. Wal-Mart, Best Buy, Sears, and other retail businesses offer this type of
shopping experience.Some companies only sell products through their website
and do not have a retail storefront. For example, Amazon, Flipkart ,Tiger Direct,
Newegg etc conduct their business exclusively online.
Types of internet connectivity

There exist several ways to connect to the internet. Following are these connection types available:

1. Dial-up Connection
2. ISDN
3. DSL
4. Cable TV Internet connections
5. Satellite Internet connections
6. Wireless Internet Connections

Dial-up Connection
Dial-up connection uses telephone line to connect PC to the internet. It requires a modem to setup
dial-up connection. This modem works as an interface between PC and the telephone line.
There is also a communication program that instructs the modem to make a call to specific number
provided by an ISP.
Dial-up connection uses either of the following protocols:
1. Serial Line Internet Protocol (SLIP)
2. Point to Point Protocol (PPP)
The following diagram shows the accessing internet using modem:

ISDN
ISDN is acronym of Integrated Services Digital Network. It establishes the connection using the
phone lines which carry digital signals instead of analog signals.
There are two techniques to deliver ISDN services:
1. Basic Rate Interface (BRI)
2. Primary Rate Interface (PRI)
Key points:
 The BRI ISDN consists of three distinct channels on a single ISDN line: t1o 64kbps B (Bearer) channel
and one 16kbps D (Delta or Data) channels.
 The PRI ISDN consists of 23 B channels and one D channels with both have operating capacity of
64kbps individually making a total transmission rate of 1.54Mbps.
The following diagram shows accessing internet using ISDN connection:

DSL
DSL is acronym of Digital Subscriber Line. It is a form of broadband connection as it provides
connection over ordinary telephone lines.
Following are the several versions of DSL technique available today:
1. Asymmetric DSL (ADSL)
2. Symmetric DSL (SDSL)
3. High bit-rate DSL (HDSL)
4. Rate adaptive DSL (RDSL)
5. Very high bit-rate DSL (VDSL)
6. ISDN DSL (IDSL)
All of the above mentioned technologies differ in their upload and download speed, bit transfer rate
and level of service.
The following diagram shows that how we can connect to internet using DSL technology:
Cable TV Internet Connection
Cable TV Internet connection is provided through Cable TV lines. It uses coaxial cable which is
capable of transferring data at much higher speed than common telephone line.
Key Points:
 A cable modem is used to access this service, provided by the cable operator.
 The Cable modem comprises of two connections: one for internet service and other for Cable TV
signals.
 Since Cable TV internet connections share a set amount of bandwidth with a group of customers,
therefore, data transfer rate also depends on number of customers using the internet at the same time.
The following diagram shows that how internet is accessed using Cable TV connection:
Satellite Internet Connection
Satellite Internet connection offers high speed connection to the internet. There are two types of
satellite internet connection: one way connection or two way connection.
In one way connection, we can only download data but if we want to upload, we need a dialup access
through ISP over telephone line.
In two way connection, we can download and upload the data by the satellite. It does not require any
dialup connection.
The following diagram shows how internet is accessed using satellite internet connection:

Wireless Internet Connection


Wireless Internet Connection makes use of radio frequency bands to connect to the internet and
offers a very high speed. The wireless internet connection can be obtained by either WiFi or
Bluetooth.
Key Points:
 Wi Fi wireless technology is based on IEEE 802.11 standards which allow the electronic device to
connect to the internet.
 Bluetooth wireless technology makes use of short-wavelength radio waves and helps to create personal
area network (PAN).

ISP: Internet Service Provider


 ISP stands for Internet Service Provider. It is a company that ISP
 For example, when you connect to the Internet, the connection between your Internet-enabled
device and the internet is executed through a specific transmission technology that involves the
transfer of information packets through an Internet Protocol route.
 Data is transmitted through different technologies, including cable modem, dial-up, DSL, high speed
interconnects. Accordingly, based on the method of data transmission, the Internet access provided
by ISPs can be divided into many types, some of which are as follows:
 Dial-up Internet access: It is the oldest technology to provide Internet access by modem to
modem connection using telephone lines. In this method, the user's computer is connected to a
modem with a telephone line. This method has become outdated today due to slow connection
speed. However, in remote areas, this method can be used where the broadband network is not
available.
 DSL: DSL, which stands for 'digital subscriber line' is an advanced version of the dial-up Internet
access method. It uses high frequency to execute a connection over the telephone network and
allows the internet and the phone connection to run on the same telephone line. This method offers
an Asymmetric Digital Subscriber (ADSL), where the upload speed is less than the download speed,
and a Symmetric Digital Subscriber Line (SDSL), which offers equal upload and download speeds.
Out of these two, ADSL is more popular among users and is popularly known as DSL.
 Wireless Broadband :It is a modern broadband technology for Internet access. It allows high-
speed wireless internet within a large area. To use this technology, you are required to place a dish
on the top of your house and point it to the transmitter of your Wireless Internet Service Provider
(WISP).
 Wi-Fi Internet: It is the short form for "wireless fidelity," which is a wireless networking
technology that provides wireless high-speed Internet connections using radio waves. To use the
internet, you are required to be within the range of wi-fi network. It is commonly used in public
places such as hotels, airports, restaurants to provide internet access to customers.
 ISDN: It is a short form of Integrated Services Digital Network. It is a telephone system network
which integrates a high-quality digital transmission of voice and data over the same standard phone
line. It offers a fast upstream and downstream Internet connection speed and allows both voice calls
and data transfer.
 Ethernet: It is a wired LAN (Local Area Network) where computers are connected within a primary
physical space. It enables devices to communicate with each other via a protocol (a set of rules or
common network language). It may provide different speeds such as 10 Mbps, 100 Mbps and 10
Gbps.

service providers in India are as follows.


1. BSNL. ...
2. MTNL. ...
3. Bharti Airtel. ...
4. Hathway Cable. ...
5. Tata Communications. ...
6. You Telecom. ...
7. Reliance Communications. ...
8. Sify Broadband.
9. Jio etc…

https://youtu.be/7IS7gigunyI

https://youtu.be/vv4y_uOneC0
UNIT- 4
FILE MANAGEMENT AND DATA PROCESSING
File
File is nothing but an Electronic document. The contents can be ordinary Text or it can be an
executable program. Each file is given a file name to identify it. The File name is in the form File
Name . Extension
Filename can consist of Alphabets or combinations of alphabets, numerals and special characters.
Extension indicates the type of file.
Example : sum.doc Here
File name is sum
Extension name is .doc which indicates Document file.

Folder
Folder contains a group of files. Folder is otherwise called as directory. Folder may have a set of
files under it. It may have other folders under it also. This files and folders can be arranged in
hierarchical manner or a tree like structure.

File organization
The arrangement of records in a file is known as File Organisation. File Organisation deals with
the arrangement of data items in the secondary storage devices like magnetic disk. That is, the
file organisation deals with how the logical tuples (rows) of tables (relations) are organised on the
physical storage medium.
For organising records efficiently in the form of a computer file, following three things are
important:
(a) A logical method should be selected to organise records in a file.
(b) File structure should be so designed that it would allow quick access to needed data items.
(c) Means of adding or deleting data items or records from files must be present. Depending on
the above considerations, a file may be organised as:
(a) Sequential file
(b) Direct or random access file
(c) Indexed-sequential file

Sequential file
A sequential file is a file in which the records are stored in some order, say the student file contains
records of students in the ascending order of roll number of students.
It is not necessary that all the records of a sequential file should be in physical adjacent positions.
On a magnetic tape, the records are written one after the other along the length of the tape. In
case of magnetic disks, the records of a sequential file may not be in contiguous locations. The
sequential order may be given with the help of pointers on each record.
Sequential files are preferable when they are to be stored on sequential access devices such as
Magnetic tapes.
A sequential file on disk
The main advantages of sequential file organisation are:
(a) File design is simple.
(b) Location or records requires only the record key.
(c) When the activity rate is high, simplicity of the accessing method makes
processing efficient.
(d) Low-cost file media such as magnetic tapes can be used for storing data.
The main drawbacks of sequential file organisation are.
(a) Updating requires that all transaction records are sorted in the record key
sequence.
(b) A new master file, physically separate and exclusive, is always created as a
result of sequential updating.
(c) Addition and deletion of records is not simple.
Direct Access File.
A sequential file is not suitable for on-line enquiry. Suppose a customer at a bank wishes to know
the balance amount in his savings account. If the customer file is organised sequentially, the
record of this customer has to be obtained by searching sequentially from the beginning. There is
no way of picking out the particular record without traversing the file from the beginning and this
may take a long time. Hence, in such situations, random access or direct access file organisation
provides a means of accessing records speedily.

In random access or direct access method of file organisation, each record has its own address
on the file. With the help of this physical address, the record can be directly accessed for reading
or writing. The records need not be in any sequence within the file and also need not be in
adjacent locations on the storage medium. Such a file cannot be created on a magnetic tape
medium. Random (or direct) files are created only on magnetic disks. Since every record can be
independently accessed, every transaction can be manipulated individually. Random access file
organisation is best suited for on-line processing systems where current information is the one
that is always required.
The advantages of Direct Access file organisation are:
(a) Immediate access to records is possible.
(b) Up-to-date information will always be available on the file.
(c) Several files can be simultaneously updated.
(d) Addition and deletion or records is not very complex.
(e) No new master file is created for updating a random access file.
The disadvantages of Direct Access file organisation are:
(a) Less efficient in the use of storage space.
(b) Uses a relatively expensive medium.
(c) Not well suited for batch processing.
(d) Data security is less due to direct access facility.
Indexed Sequential File
Some files may be required to support both batch processing and on-line processing. For
example, an inventory or stock file may be updated periodically by batch processing and at the
same time may have to provide current information about stock availability on-line. They can be
thus, organised as indexed sequential files. Indexed Sequential file combines the advantages of
sequential and direct access file organisations.
An indexed sequential file is basically a sequential file organised serially on key fields. In addition,
an index is maintained which speedsúp the access of isolated records. Just as you may be
indexes to locate information in book, similarly an index is provided for the file. The file is divided
into a number of blocks and the highest key in each block is indexed.

Indexed sequential files are also known as Indexed Sequential Access Method (ISAM) files.
Within each block, the record is searched sequentially. This method is much faster than
searching the entire file sequentially. It is also possible to have more than one level of indexing to
make the search process faster.
The main advantage of indexed sequential file organisation is that it is suitable for both sequential
and on-line or direct access processing.

The main disadvantages of this organisation are:


(a) Less efficient in the use of storage space.
(b) Additions and deletions of records are more complex as they effect both the index and the
record number in the file.

Deciding on a File Organisation


The major factors to be considered while deciding which file organisation should be chosen are
the following:
(a) Percentage of actual records processed in a day. If large number of records are accessed at a
time, direct access file organisation should be used. If very few records are accessed, sequential
file organisation will be more suitable and cheaper.
(b) Files that are frequently updated must be stored on a direct access storage device, such as
disk.
(c) Selection of file organisation also depend on the mode of processing i.e. where the system
requires an online processing or batch processing.

DATA PROCESSING
Data Processing means, processing the input data to produce some meaningful and purposeful
information. Computer has the capability of processing high-volume of data in less time with
higher accuracy. Hence the data processing performed by computer is sometimes called
Electronic Data Processing (EDP). Data processing involves 5 distinct steps.
- Data capturing
- Data validation
- Processing / Execution
- Data storage
- Data Retrieval/Out generation
Data capturing encompasses the activities of input the data to the computer. Before giving input
to the system the required data are to be first identified and put in the defined format called
source data layout. The aim of this layout is to have faster data entry. To reduce the volume of
data and also have better organisation and easy access to data those can suitably be coded.
After data are ready they can be entered to the computer through keyboard. This is sometimes
called data capture through intelligent terminal. The other form of data capture is through
scanners or optical devices. In this type of data capturing data are not entered rather data are
captured from the source document or paper as it is Photographs, fingerprints, signatures,
objective multiple type answers in answer papers etc. are captured through this method. Another
form of data capturing is through some interfacing devices from where data can be transferred
directly to the computer. Example of this is Electronic cash Registers used in shops and cash
counters.

After data capturing, the data is validated. Data validation involves checking of input data to fit to
requirements or specifications. For example price of a book can be numeric only. If by mistake
Alphabetic data are entered then it is checked and error is shown to revalidate the data. This
prevents unwanted and unspecified data to enter into the system and causing errors.
The valid input data are stored in file or database and processed as per the instructions. The
instructions are put in programs or software. This software or program, when executed does the
processing of input data and produces the output. Again outputs are stored in files in memory.

After processing of data, the outputs are produced. The outputs may be formed in different
ways depending on the requirements and specifications. The same set of data can be printed in
tabular form or in form of graphs. There are variety of ways for presenting data. The printed
output is sometimes called hardcopy. There can be provision of answering to queries of user
where the answer is displayed on the monitor screen itself. So it depends on the requirements of
user.
An important step of Data Processing is maintaining Database. Database is nothing but
collection of data which is controlled centrally with many provisions of data security. This is
where, normally data are stored for reference. The input data and output data are stored in
database. Even after processing of data and producing of data is over, database is maintained
properly with safety for future needs and reference. The important tool of data processing is file.
File is nothing but an electronic document where data can be stored. Depending on the type of
file structure and organisation the data access speed varies.
UNIT-5
PROBLEM SOLVING METHODOLOGY
DEFINITION-

Problem solving methodology is a process of working through details of a problem to


reach a solution . problem solving may include mathematical or systematic operation
and can be a gauge of an individual’s critical thinking skill.

Steps of Problem solving methodology

1. Understand the problem- collect the problem to generate a program.


2. Analyze the problem-analyze the various steps of solving the problem.
3. Design the problem-design the problem by creating flowchart and writing
algorithm.
4. Code the program-create coding by using proper programming language.

ALGORITHM

It is a step by step procedure which defines a set of instruction to be executed in


certain order to get the desired output.

Characteristics of algorithm

1. Precision – the steps are precisely stated(defined).


2. Uniqueness – results of each step are uniquely defined and only depend on the
input and the result of the preceding steps.

3. Effectiveness- An algorithm is also generally expected to be effective. This


means that all of the operations to be performed in the algorithm must be
sufficiently basic that they can in principle be done exactly and in a finite length
of time.
Example of not effectiveness
:e=1+1/1!+1/2!+....add it to x. Not effective
because summation of infinite terms.

4. Finiteness-An algorithm must always terminate after a finite number of steps.


5. Unambiguous- algorithm should be clear and unambiguous. Each steps should
be clear and must lead to any one meaning.
Ex: toss a coin . a coin has 2 sides i.e. head and tail. It shows 2 possible values.

Examples
Write an algorithm to add numbers.
Step1-Read the numbers x,y
Step2-sum=x+y
Step3-print sum
Step-4-end

Or you can write

Algorithm
 An algorithm is a step-by-step method for solving some problem.
 An algorithm is a procedure having well defined steps for solving a particular
problem.
 Algorithm is finite set of logic or instructions, written in order for accomplish the
certain predefined task.
 It is not the complete program or code, it is just a solution (logic) of a problem,
which can be represented either as an informal description using a Flowchart or
Pseudo code.

Example: Design an algorithm to multiply the two numbers x and y and display the
result in z.

o Step 1 START
o Step 2 declare three integers x, y & z
o Step 3 define values of x & y
o Step 4 multiply values of x & y
o Step 5 store the output of step 4 in z
o Step 6 print z
o Step 7 end

. Alternatively the algorithm can be written as ?

o Step 1 START MULTIPLY


o Step 2 get values of x & y
o Step 3 z← x * y
o Step 4 display z
o Step 5 end

Characteristics of an Algorithm

An algorithm must follow the mentioned below characteristics:

o Input: An algorithm must have 0 or well defined inputs.


o Output: An algorithm must have 1 or well defined outputs, and should match
with the desired output.
o Feasibility: An algorithm must be terminated after the finite number of steps.
o Independent: An algorithm must have step-by-step directions which is
independent of any programming code.
o Unambiguous: An algorithm must be unambiguous and clear. Each of their steps
and input/outputs must be clear and lead to only one meaning.

Building Blocks: It has been proven that any algorithm can be constructed from just three
basic building blocks. These three building blocks are Sequence, Selection, and
Iteration(Repetition).

1. SEQUENCE. In a computer program or an algorithm, sequence involves


simple steps which are to be executed one after the other. The steps are
executed in the same order in which they are written.
Consider an example-1, Algorithm for Addition of two numbers:
Step1:Start (you canalso write or start your algorithmfrom step2 and write
the step as step1 without writing step1:start)
Step2:inputtwo
numbersaandb
Step 3: set
sum=a+b
Step 4: Print sum
Step 5: stop // or step5: end
Example-2
you can write step3 as set a=a+b
set b=a-b set a=a-b
Example-3
Swapping of two variables using
third variable Step1:read the
value of a and b
Step2:set temp=a
Set a=b
Set b=temp
Step3:print the
value of a and b
Step4: end
Example-4
Algorithm for simple interest.
Step1:read the value of principal, rate and time
Step2:set si=((principal*rate*time)/100)
Step3: print si
Step4:end

All these algorithms perform the steps in a purely sequential order.

2. Decision

Decision statements are used when the outcome of the process depends on
some condition. Decision means choosing between two actions, depending on
whether a condition is true or false.

A decision statement can be stated as following manner:-

Using if
If condition then process Example 1:
Algorithm for check whether a person is eligible to vote.
Step 1: read age
Step 2: if age>=18
Step 3: eligible to vote
Step 4: end
1. Using if-else

if else statement is used to add alternative set of else statements for if


condition. In case if condition fails (FALSE) then alternatively it will
execute else statements.

Whenever we have specific requirement like execute set of block


statements if given condition is TRUE else execute other statements in
that situation we can use swift if else statement.

If condition
then process1/statement1
Else
Process2/statement 2

Example 1:algorithm to find whether a number is


even or not. Step 1: input a number as a
Step 2:if a%2=0
then print “even”
else
print “odd”
step 3: end
Example-2:
write an algorithm to find the larger among
two numbers.
Step 1: input two numbers a and b
Step 2: if a>b
then print a is larger
else
print b is larger
step 3: end

2.Using if else-if else

In, if else-if else statement is used to add alternative set of multiple else-if and
single else statements for if condition. In case if condition fails (FALSE) then
alternatively check for another condition in case if it failed for all defined
conditions the it will execute else statements.

If we want to add multiple condition checks in single program then by using s if


else-if else statement we can easily add multiple conditions. In if else-if else
statement we have a chance to add multiple else if statements but we are
restricted to add only one if and else conditions in statement.

If condition1
then print staement1
else if condition2
then print statement2
else
print statement3

example:
Step 1: input two numbers a and b
Step 2: if a>b then
print a is larger
else if a<b then
print b is larger
else
print the numbers are equal
Step 3: end

3. Repetition/ Iteration :

Repetition allows for a portion of an algorithm or computer program to be


executed any number of times dependent on some condition being met. An
occurrence of repetition is usually known as a loop. ... This construct is often
called a guarded loop. Repeat a block of statements while a condition is true.

It can be implemented using construct such as while, do-while

and for loop. First we have to initialize the variable.

1. Using while:

while is used to execute set of statements continuously until, the defined condition
is TRUE.
Q.Write an algorithm to print first 5 natural numbers

Step 1: Initialize i=1 , n=5


Step 2: repeat step while i<=5
Step 3: Print i 1 2
Step 4: Increment i+1

Step 5: end

Q.Write an algorithm to find the factorial of a number entered by user.


Step 1: Start
Step 2: Declare variables n,factorial and i.
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
Step 5: Repeat the steps until i=n
factorial←factorial*i
i←i+1
Step 6: Display factorial
Step 7: end

Using for loop//


using do-while//
PSEUDOCODE
 pseudocode is an artificial and informal language that helps programmers develop
algorithms.pseudocode is a “text-based”detail(algorithmic) design tool.

 It’s simply an implementation of an algorithm in the form of annotations and informative


text written in plain English. It has no syntax like any of the programming language and
thus can’t be compiled or interpreted by the computer.
How to write a Pseudo Code?
 Pseudo code is a term which is often used in programming and algorithm based fields. It
is a methodology that allows the programmer to represent the implementation of an
algorithm.
 Simply, we can say that it’s the cooked up representation of an algorithm.
 Often at times, algorithms are represented with the help of pseudo codes as they can be
interpreted by programmers no matter what their programming background or
knowledge is.
 Pseudo code, as the name suggests, is a false code or a representation of code which can
be understood by even a layman with some school level programming knowledge.

Advantages of Pseudo code

 Improves the readability of any approach. It’s one of the best approaches to start
implementation of an algorithm.
 Acts as a bridge between the program and the algorithm or flowchart. Also works as a
rough documentation, so the program of one developer can be understood easily when a
pseudo code is written out. In industries, the approach of documentation is essential. And
that’s where a pseudo-code proves vital.
 The main goal of a pseudo code is to explain what exactly each line of a program should do,
hence making the code construction phase easier for the programmer.

How to write a Pseudo-code?

Arrange the sequence of tasks and write the pseudocode accordingly.


Start with the statement of a pseudo code which establishes the main goal or the aim.
Example:
This program will allow the user to check
the number whether it's even or odd.
The way the if-else, for, while loops are indented in a program, indent the statements likewise,
as it helps to comprehend the decision control and execution mechanism. They also improve
the readability to a great extent.

Use appropriate naming conventions. The human tendency follows the approach to follow
what we see. If a programmer goes through a pseudo code, his approach will be the same as
per it, so the naming must be simple and distinct.
Use appropriate sentence casings, such as CamelCase for methods, upper case for constants
and lower case for variables.
Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it
in programming.
Check whether all the sections of a pseudo code is complete, finite and clear to understand
and comprehend.
Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple
to understand even for a layman or client, hence don’t incorporate too many technical terms.

STATEMENTS
A statement is defined as an instruction that directs the computer to perform a specific action. In
writing pseudo code, we will refer to singular instructions as statements.

When writing pseudo code, we assume that the order of execution of the statements is from top
to bottom. This changes when using control structures, functions and exception handling.

Mathematical operations
Mathematical operations are integral to solution development. They allow us to manipulate the
values we have stored.
Here are common mathematical symbols:

Assignment: ← or := Example: c ← 2πr, c := 2πr Comparison: =, ≠, <, >, ≤, ≥Arithmetic: +, −, ×,


/, mod , Floor/ceiling: ⌊, ⌋, ⌈, ⌉a ← ⌊b⌋ + ⌈c⌉ Logical: and, or Sums, products: Σ Π Example: h
← Σ a ∈A 1/a
Keywords:A keyword is a word that is reserved by a program because the word has a special
meaning. Keywords can be commands or parameters. Every programming language has its own
keywords (reserved words). Keywords cannot be used as variable names.

In Pseudocode, they are used to indicate common input-output and processing operations. They
are written fully in uppercase.

START: This is the start of your pseudocode.


INPUT: This is data retrieved from the user through typing or through an input device.
READ / GET: This is input used when reading data from a data file.
PRINT, DISPLAY, SHOW: This will show your output to a screen or the relevant output device.
COMPUTE, CALCULATE, DETERMINE: This is used to calculate the result of an expression.
SET, INIT: To initialize values
INCREMENT, BUMP: To increase the value of a variable
DECREMENT: To reduce the value of a variable

CONDITIONALS
During algorithm development, we need statements which evaluate expressions and execute
instructions depending on whether the expression evaluated to True or False. Here are some
common conditions used in Pseudocode:

IF — ELSE IF — ELSE
This is a conditional that is used to provide statements to be executed if a certain condition is
met. This also applies to multiple conditions and different variables.

Here is an if statement with one condition


IF you are happy
THEN smile
ENDIF

Here is an if statement with an else section. Else allows for some statements to be executed if
the “if” condition is not met.
IF you are happy THEN
smile
ELSE
frown
ENDIF

We can add additional conditions to execute different statements if met.


IF you are happy THEN
smile
ELSE IF you are sad
frown
ELSE
keep face plain
ENDIF

CASE
Case structures are used if we want to compare a single variable against several conditions.
INPUT colorCASE color of red: PRINT "red"
green: PRINT "green"
blue: PRINT "blue"OTHERS
PRINT "Please enter a value color"ENDCASE

The OTHERS clause with its statement is optional. Conditions are normally numbers or characters

ITERATION
To iterate is to repeat a set of instructions in order to generate a sequence of outcomes. We
iterate so that we can achieve a certain goal.

FOR structure
The FOR loop takes a group of elements and runs the code within the loop for each element.
FOR every month in a year Compute number of daysENDFOR

WHILE structure
Similar to the FOR loop, the while loop is a way to repeat a block of code as long as a predefined
condition remains true. Unlike the FOR loop, the while loop evaluates based on how long the
condition will remain true.

To avoid a scenario where our while loop runs infinitely, we add an operation to manipulate the
value within each iteration. This can be through an increment, decrement, et cetera.

PRECONDITION: variable X is equal to 1


WHILE Population < Limit Compute Population as Population + Births — Deaths
ENDWHILE
FUNCTIONS
When solving advanced tasks it is necessary to break down the concepts in block of statements
in different locations. This is especially true when the statements in question serve a particular
purpose. To reuse this code, we create functions. We can then call these functions every-time we
need them to run.
Function clear monitor
Pass In: nothing
Direct the operating system to clear the monitor
Pass Out: nothing
Endfunction

To emulate a function call in pseudocode, we can use the Call keyword


call: clear monitor

Examples of Pseudocode
create a program to add 2 numbers together and then display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
Compare that pseudocode to an example of a flowchart to add two numbers

START

ENTER 2 NOS
A,B

SET C=A+B

PRINT C

END
compute the area of a rectangle:
Get the length, l, and width, w
Compute the area = l*w
Display the area
compute the perimeter of a rectangle:
Enter length, l
Enter width, w
Compute Perimeter = 2*l + 2*w
Display Perimeter of a rectangle

CONCLUSION
There are no technical rules for Pseudocode. It is meant to be human readable and still convey
meaning and flow.There are different guide and tutorials which lean more towards language-
specific pseudocode, examples of such are Fortran style pseudo code, Pascal style pseudo
code, C style pseudo code and Structured Basic style pseudo code.
FLOWCHART
A flowchart is simply a graphical representation of steps. It shows steps in sequential order
and is widely used in presenting the flow of algorithms, workflow or processes. Typically, a
flowchart shows the steps as boxes of various kinds, and their order by connecting them with
arrows.

Guide to Flowchart Symbols, from Basic to Advanced


1. The Oval
An End or a Beginning

The oval, or terminator, is used to represent the start and end of a process. Use the Gliffy
flowchart tool to drag and drop one of these bad boys and you've got yourself the beginning of
a flowchart. Remember to use the same symbol again to show that your flowchart is complete.

2. The Rectangle
A Step in the Flowcharting Process

The rectangle is your go-to symbol once you've started flowcharting. It represents any step in
the process you’re diagramming and is the workhorse of the flowchart diagram. Use rectangles
to capture process steps like basic tasks or actions in your process.

3. The Arrow
Indicate Directional Flow
The arrow is used to guide the viewer along their flowcharting path. And while there are many
different types of arrow tips to choose from, we recommend sticking with one or two for your
entire flowchart. This keeps your diagram looking clean, but also allows you to emphasize
certain steps in your process.

4. The Diamond
Indicate a Decision

The diamond symbolizes that a decision is required to move forward. This could be a binary,
this-or-that choice or a more complex decision with multiple choices. Make sure that you
capture each possible choice within your diagram.

With those four basic symbols, you likely have everything you need to get started on your own
flowchart! Give it a try with Gliffy or read on for more info on intermediate flowcharting
symbols.

Intermediate & Advanced Flowchart Symbols

As you know, flowcharts are made up of a sequence of actions, data, services, and/or materials.
They illustrate where data is being input and output, where information is being stored, what
decisions need to be made, and which people need to be involved. In addition to the basics,
these intermediate flowchart symbols will help you describe your process with even more
detail.
Document Symbols

Single and multiple document icons show that there are additional points of reference involved
in your flowchart. You might use these to indicate items like “create an invoice” or “review
testing paperwork.”
Data Symbols

Data symbols clarify where the data your flowchart references is being stored. (You probably
won’t use the paper tape symbol, but it definitely came in handy back in the day.)

Input & Output

Input and output symbols show where and how data is coming in and out throughout your
process.

Merging & Connecting

Agreed-upon merging and connector symbols make it easier to connect flowcharts that span
multiple pages.
Additional Useful Shapes

The above are a few additional symbols that prove your flowcharting prowess when put to good
use.
Using Flowchart Symbols

Types of flowcharts

 Document Flowcharts: These “have the purpose of showing existing controls over document-flow
through the components of a system. … The chart is read from left to right and documents the flow of
documents through the various business units.”
 Data Flowcharts: These show “the controls governing data flows in a system. … Data flowcharts are
used primarily to show the channels that data is transmitted through the system rather than how
controls flow.”
 System Flowcharts: These “show the flow of data to and through the major components of a system
such as data entry, programs, storage media, processors, and communication networks.”
 Program Flowcharts: These show “the controls placed internally to a program within a system.
Example : Draw a flowchart to input two numbers from user and display the largest of two
numbers

Q1. Add 10 and 20

Flowchart
Q2. Find the sum of 5 numbers

Flowchart

Q3. Print Hello World 10 times

Flowchart
Q4. Draw a flowchart to log in to facebook account.

Flowchart

Draw flowchart to find the largest among three different numbers entered by user .
Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0

Draw a flowchart to find the Fibonacci series till term≤1000.


Flowchart for calculate factorial value of a number:

Difference between Algorithm and Flowchart


Algorithm Flowchart
It is a procedure for solving problems. It is a graphic representation of a process.
The process is shown in step-by-step The process is shown in block-by-block information
instruction. diagram.
It is complex and difficult to understand. It is intuitive and easy to understand.
It is convenient to debug errors. It is hard to debug errors.
The solution is showcased in natural
The solution is showcased in pictorial format.
language.
It is somewhat easier to solve complex
It is hard to solve complex problem.
problem.
It costs more time to create an algorithm. It costs less time to create a flowchart.
Generations of programming language
Programming languages have been developed over the year in a phased manner. Each
phase of developed has made the programming language more user-friendly, easier to use
and more powerful. Each phase of improved made in the development of the programming
languages can be referred to as a generation. The programming language in terms of their
performance reliability and robustness can be grouped into five different generations,

1. First generation languages (1GL)


2. Second generation languages (2GL)
3. Third generation languages (3GL)
4. Fourth generation languages (4GL)
5. Fifth generation languages (5GL)

1. First Generation Language (Machine language)


The first generation programming language is also called low-level programming language
because they were used to program the computer system at a very low level of abstraction.
i.e. at the machine level. The machine language also referred to as the native language of
the computer system is the first generation programming language. In the machine
language, a programmer only deals with a binary number.

Advantages of first generation language

 They are translation free and can be directly executed by the computers.
 The programs written in these languages are executed very speedily and efficiently by
the CPU of the computer system.
 The programs written in these languages utilize the memory in an efficient manner
because it is possible to keep track of each bit of data.

2. Second Generation language (Assembly Language)


The second generation programming language also belongs to the category of low-level-
programming language. The second generation language comprises assembly languages
that use the concept of mnemonics for the writing program. In the assembly language,
symbolic names are used to represent the opcode and the operand part of the instruction.

Advantages of second generation language


 It is easy to develop understand and modify the program developed in these
languages are compared to those developed in the first generation programming
language.
 The programs written in these languages are less prone to errors and therefore can be
maintained with a great case.

3. Third Generation languages (High-Level Languages)


The third generation programming languages were designed to overcome the various
limitations of the first and second generation programming languages. The languages of
the third and later generation are considered as a high-level language because they enable
the programmer to concentrate only on the logic of the programs without considering the
internal architecture of the computer system.

Advantages of third generation programming language

 It is easy to develop, learn and understand the program.


 As the program written in these languages are less prone to errors they are easy to
maintain.
 The program written in these languages can be developed in very less time as
compared to the first and second generation language.

Examples: FORTRAN, ALGOL, COBOL, C++, C

4. Fourth generation language (Very High-level Languages)


The languages of this generation were considered as very high-level programming
languages required a lot of time and effort that affected the productivity of a programmer.
The fourth generation programming languages were designed and developed to reduce the
time, cost and effort needed to develop different types of software applications.

Advantages of fourth generation languages

 These programming languages allow the efficient use of data by implementing the
various database.
 They require less time, cost and effort to develop different types of software
applications.
 The program developed in these languages are highly portable as compared to the
programs developed in the languages of other generation.

Examples: SOL, CSS, ColdFusion


5. Fifth generation language (Artificial Intelligence Language)
The programming languages of this generation mainly focus on constraint programming.
The major fields in which the fifth generation programming language are employed are
Artificial Intelligence and Artificial Neural Networks

Advantages of fifth generation languages

 These languages can be used to query the database in a fast and efficient manner.
 In this generation of language, the user can communicate with the computer system
in a simple and an easy manner.

Examples: mercury, prolog, OPS5

Structured Programming Approach with Advantages


and Disadvantages
Structured Programming Approach, as the word suggests, can be defined as a programming
approach in which the program is made as a single structure. It means that the code will execute
the instruction by instruction one after the other. It doesn’t support the possibility of jumping from
one instruction to some other with the help of any statement like GOTO, etc. Therefore, the
instructions in this approach will be executed in a serial and structured manner. The languages that
support Structured programming approach are:
 C
 C++
 Java
 C#
On the contrary, in the Assembly languages like Microprocessor 8085, etc, the statements do not
get executed in a structured manner. It allows jump statements like GOTO. So the program flow
might be random.

Advantages Of Structured Programming Language


 Structured programming is user-friendly and easy to understand.
 In this programming, programs are easier to read and learn.
 It avoids the increased possibility of data corruption.
 The main advantage of structured programming is reduced complexity.
 Increase the productivity of application program development.
 Application programs are less likely to contain logic errors.
 Errors are more easily found.
 It is easier to maintain.
 It is independent of the machine on which it is used, i.e. programs developed in high-level
languages can be run on any computer.

Disadvantages Of Structured Programming Language


 Same code repetition

The code that is written may appear in different parts of the program. It can be vulnerable to
various problems because of its location. Programs have variables, which means that they
can take on different values at different parts of the program.

 Lack of encapsulation

Its lack of availability in structured programming means that programs will be longer.
 Lack of information hiding

Information hiding involves isolating design decisions in a computer program that have the
greatest chance to change. This protects other parts of the program from modifications if the
design decision is changed.
CHAPTER-6

OVERVIEW OF C PROGRAMMING LANGUAGE

The C Language is developed for creating system applications that directly interact with the
hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why it is
known as mother language.

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language

1) C as a mother language

C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of
the programming languages follow C syntax, for example, C++, Java, C#, etc.

It provides the core concepts like the array, strings, functions, file handling, etc. that are
being used in many languages like C++, Java, C#, etc.

2) C as a system programming language

A system programming language is used to create system software. C language is a system


programming language because it can be used to do low-level programming (for example
driver and kernel). It is generally used to create hardware devices, OS, drivers, kernels, etc.
For example, Linux kernel is written in C.

It can't be used for internet programming like Java, .Net, PHP, etc.

3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.

A procedural language breaks the program into functions, data structures, etc.

C is a procedural language. In C, variables and function prototypes must be declared before


being used.

4) C as a structured programming language

A structured programming language is a subset of the procedural language. Structure


means to break a program into parts or blocks so that it may be easy to understand.

In the C language, we break the program into parts using functions. It makes the program
easier to understand and modify.

5) C as a mid-level programming language

C is considered as a middle-level language because it supports the feature of both low-


level and high-level languages. C language program is converted into assembly code, it
supports pointer arithmetic (low-level), but it is machine independent (a feature of high-
level).

A Low-level language is specific to one machine, i.e., machine dependent. It is machine


dependent, fast to run. But it is not easy to understand.

A High-Level language is not specific to one machine, i.e., machine independent. It is easy
to understand.

C Program

In this tutorial, all C programs are given with C compiler so that you can quickly change the
C program code.

File: main.c

1. #include <stdio.h>
2. int main() {
3. printf("good morning");
4. return 0;
5. }
History of C Language

History of C language is interesting to know. Here we are going to discuss a brief history of the c
language.

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee


Features of C Language

C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10.Extensible

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.
3) Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop system applications
such as kernel, driver, etc. It also supports the features of a high-level language. That is why it is
known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the program into parts
using functions. So, it is easy to understand and modify. Functions also provide code reusability.

5) Rich Library
C provides a lot of inbuilt functions that make the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.

10) Extensible
C language is extensible because it can easily adopt new features.
C Language Introduction

C is a procedural programming language. It was initially developed by Dennis Ritchie in the


year 1972. It was mainly developed as a system programming language to write an operating
system. The main features of C language include low-level access to memory, a simple set of
keywords, and clean style, these features make C language suitable for system programmings
like an operating system or compiler development.
Many later languages have borrowed syntax/features directly or indirectly from C language.
Like syntax of Java, PHP, JavaScript, and many other languages are mainly based on C
language. C++ is nearly a superset of C language (There are few programs that may compile in
C, but not in C++).
Beginning with C programming:
1. Structure of a C program
After the above discussion, we can formally assess the structure of a C program. By
structure, it is meant that any program can be written in this structure only. Writing a C
program in any other structure will hence lead to a Compilation Error.

The structure of a C program is as follows:

The components of the above structure are:


1. Header Files Inclusion: The first and foremost component is the inclusion of the
Header files in a C program.
A header file is a file with extension .h which contains C function declarations and
macro definitions to be shared between several source files.
Some of C Header files:
 stdio.h – Defines core input and output functions
 stdlib.h – Defines numeric conversion functions, pseudo-random network
generator, memory allocation
 string.h – Defines string handling functions
 math.h – Defines common mathematical functions
 stddef.h – Defines several useful types and macros.
 stdint.h – Defines exact width integer types.

Syntax to include a header file in C:


#include
2. Main Method Declaration: The next part of a C program is to declare the main()
function. The syntax to declare the main function is:
Syntax to Declare main method:
int main()
{}
3. Variable Declaration: The next part of any C program is the variable declaration. It
refers to the variables that are to be used in the function. Please note that in the C
program, no variable can be used without being declared. Also in a C program, the
variables are to be declared before any operation in the function.
Example:
int main()
{
int a;
.
.
4. Body: Body of a function in C program, refers to the operations that are performed
in the functions. It can be anything like manipulations, searching, sorting, printing,
etc.
Example:
int main()
{
int a;

printf("%d", a);
.
.
5. Return Statement: The last part in any C program is the return statement. The
return statement refers to the returning of the values from a function. This return
statement and return value depend upon the return type of the function. For
example, if the return type is void, then there will be no return statement. In any
other case, there will be a return statement and the return value will be of the type
of the specified return type.
Example:

int main()
{
int a;

printf("%d", a);

return 0;
}
2. Writing first program:
Following is first program in C

#include <stdio.h>
int main(void)
{
printf("hello");
return 0;
}
Let us analyze the program line by line.
Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed
by preprocessor which is a program invoked by the compiler. In a very basic
term, preprocessor takes a C program and produces another C program. The produced
program has no lines starting with #, all such lines are processed by the preprocessor. In the
above example, preprocessor copies the preprocessed code of stdio.h to our file. The .h files
are called header files in C. These header files generally contain declaration of functions. We
need stdio.h for the function printf() used in the program.

Line 2 [ int main(void) ] There must to be starting point from where execution of compiled C
program begins. In C, the execution typically begins with first line of main(). The void written
in brackets indicates that the main doesn’t take any parameter (See this for more details).
main() can be written to take parameters also. We will be covering that in future posts.
The int written before main indicates return type of main(). The value returned by main
indicates status of program termination. See this post for more details on return type.

Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define a scope and mainly used
in functions and control statements like if, else, loops. All functions must start and end with
curly brackets.

Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library function to print something on


standard output. The semicolon at the end of printf indicates line termination. In C, semicolon
is always used to indicate end of statement.

Line 5 [ return 0; ] The return statement returns the value from main(). The returned value
may be used by operating system to know termination status of your program. The value 0
typically means successful termination.

How to execute the above program:


Inorder to execute the above program, we need to have a compiler to compile and run our
programs. There are certain online compilers
like https://ide.geeksforgeeks.org/, http://ideone.com/ or http://codepad.org/ that can be
used to start C without installing a compiler.
Windows: There are many compilers available freely for compilation of C programs like Code
Blocks and Dev-CPP. We strongly recommend Code Blocks.

Linux: For Linux, gcc comes bundled with the linux, Code Blocks can also be used with Linux.

Flow of C Program

The C program follows many steps in execution.

To understand the flow of C program well,

let us see a simple program first.

File: simple.c

1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }

Execution Flow

Let's try to understand the flow of above program by the figure given below.
1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to
convert preprocessor directives into their respective values. The preprocessor generates an
expanded source code.

2) Expanded source code is sent to compiler which compiles the code and converts it into
assembly code.

3) The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.

4) The object code is sent to linker which links it to the library such as header files. Then it
is converted into executable code. A simple.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it is executed.
After execution, output is sent to console.

Constants in C

A constant is a value or variable that can't be changed in the program, for example: 10, 20,
'a', 3.4, "c programming" etc.

There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program” etc.

2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword
2. #define preprocessor
1) C const keyword

The const keyword is used to define constant in C programming.

1. const float PI=3.14;

Now, the value of PI variable can't be changed.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }

Output: Compile Time Error: Cannot modify a const object

2) C #define preprocessor

The #define preprocessor is also used to define constant.

Constants are like a variable, except that their value never changes during execution once
defined.

C Constants

C Constants is the most fundamental and essential part of the C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the same
during the entire execution of the program.
 Constants are also called literals.
 Constants can be any of the data types.
 It is considered best practice to define constants using only upper-case names.
Table of Contents
1. Constant Definition in C

2. Constant Types in C

3. Integer Constant

4. Real constant

5. Single Character Constants

6. String Constants

7. Backslash character constant

Constant Definition in C
Syntax:

const type constant_name;

const keyword defines a constant in C.

Example:

#include<stdio.h>

main()

const int SIDE = 10;

int area;

area = SIDE*SIDE;

printf("The area of the square with side: %d is: %d sq. units"

, SIDE, area);

}
Program Output:

Putting const either before or after the type is possible.

int const SIDE = 10;

or

const int SIDE = 10;

Constant Types in C
Constants are categorized into two basic types, and each of these types has its
subtypes/categories. These are:

Primary Constants

1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants

Integer Constant

It's referring to a sequence of digits. Integers are of three types viz:

1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6

Real constant

The numbers containing fractional parts like 99.25 are called real or floating points constant.

Single Character Constants

It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be
noted that the character '8' is not the same as 8. Character constants have a specific set of
integer values known as ASCII values (American Standard Code for Information Interchange).

Example:

'X', '5', ';'

String Constants

These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are
different - because "G" represents a string as it is enclosed within a pair of double quotes
whereas 'G' represents a single character.

Example:

"Hello!", "2015", "2+1"

Backslash character constant

C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as
"Escape Sequence".

For Example:

\t is used to give a tab

\n is used to give a new line


Constants Meaning

\a beep sound

\b backspace

\f form feed

\n new line

\r carriage return

\t horizontal tab

\v vertical tab

\' single quote

\" double quote

\\ backslash

\0 null

Secondary Constant

 Array
 Pointer
 Structure
 Union
 Enum
C - Constants and Literals

Constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant,
a character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified
after their definition.

Integer Literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base
or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals −
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
Following are other examples of various types of integer literals −
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both;
and while representing exponential form, you must include the integer part, the fractional
part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */

Character Constants

Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable
of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a
backslash for example, newline (\n) or tab (\t).
Following is the example to show a few escape sequence characters −
#include <stdio.h>

int main() {
printf("Hello\tWorld\n\n");

return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World

String Literals

String literals or constants are enclosed in double quotes "". A string contains characters that
are similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using
white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"


Defining Constants

There are two simple ways in C to define constants −


 Using #define preprocessor.
 Using const keyword.

The #define Preprocessor

Given below is the form to use #define preprocessor to define a constant −


#define identifier value
The following example explains it in detail −
#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50

The const Keyword

You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
Note that it is a good programming practice to define constants in CAPITALS.

Variables in C

Variables are memory locations(storage area) in the C programming language.

The primary purpose of variables is to store data in memory for later use.
Unlike constants which do not change during the program execution, variables value may
change during execution. If you declare a variable in C, that means you are asking to the
operating system for reserve a piece of memory with that variable name.

Table of Contents

1. Variable Definition in C

2. Variable Definition and Initialization

3. Variable Assignment

4. There are some rules on choosing variable names

5. C Program to Print Value of a Variable

Variable Definition in C
Syntax:

type variable_name;
or

type variable_name, variable_name, variable_name;

Variable Definition and Initialization


Example:

int width, height=5;

char letter='A';

float age, area;

double d;

width = 10; /* actual initialization */

age = 26.5;

Variable Assignment
Variable assignment is a process of assigning a value to a variable.

Example:

int width = 60;

int age = 31;

There are some rules on choosing variable names

 A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the
underscore character.
 The first character must be a letter or underscore.
 Blank spaces cannot be used in variable names.
 Special characters like #, $ are not allowed.
 C keywords cannot be used as variable names.
 Variable names are case sensitive.
 Values of the variables can be numeric or alphabetic.
 Variable type can be char, int, float, double or void.

C Program to Print Value of a Variable


Example:

#include<stdio.h>

void main()

int age =5; /* c program to print value of a variable */

printf("I am %d years old.\n", age);

Program Output:

I am 5 years old.

Data Types in C

A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double


Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating
system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767


signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to


2,147,483,647

signed long int 4 byte -2,147,483,648 to


2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Basic types

Here's a table containing commonly used types in C programming for quick access.

Type Size (bytes) Format Specifier

int at least 2, usually 4 %d, %i


Type Size (bytes) Format Specifier

char 1 %c

float 4 %f

double 8 %lf

short int 2 usually %hd

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %ld, %li

long long int at least 8 %lld, %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf


int

Integers are whole numbers that can have both zero, positive and negative values but no
decimal values. For example, 0, -5, 10
We can use int for declaring an integer variable.

int id;

Here, id is a variable of type integer.


You can declare multiple variables at once in C programming. For example,

int id, age;

The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -
2147483648 to 2147483647.

float and double

float and double are used to hold real numbers.

float salary;
double price;

In C, floating-point numbers can also be represented in exponential. For example,

float normalizationFactor = 22.442e2;

What's the difference between float and double?


The size of float (single precision float data type) is 4 bytes. And the size of double (double
precision float data type) is 8 bytes.
char

Keyword char is used for declaring character type variables. For example,

char test = 'h';

The size of the character variable is 1 byte.

void

void is an incomplete type. It means "nothing" or "no type". You can think of void as absent.
For example, if a function is not returning anything, its return type should be void.
Note that, you cannot create variables of void type.

short and long

If you need to use a large number, you can use a type specifier long. Here's how:

long a;
long long b;
long double c;

Here variables a and b can store integer values. And, c can store a floating-point number.
If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can
use short.

short d;

You can always check the size of a variable using the sizeof() operator.

#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;

printf("size of short = %d bytes\n", sizeof(a));


printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d));
return 0;
}

signed and unsigned

In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by
using them. For example,

unsigned int x;
int y;

Here, the variable x can hold only zero and positive values because we have used
the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1, whereas
variable x can hold values from 0 to 232-1.

Other data types defined in C programming are:

 bool Type

 Enumerated type

 Complex types
Derived Data Types

Data types that are derived from fundamental data types are derived types. For example:
arrays, pointers, function types, structures, etc.

We will learn about these derived data types in later tutorials.

C Identifiers

Identifiers are names given to different names given to entities such as constants, variables,
structures, functions etc.

Example:

int amount;

double totalbalance;

In the above example, amount and totalbalance are identifiers and int, and double are
keywords.

Rules for Naming Identifiers

 An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters & digits) and
underscore( _ ) symbol.
 Identifier names must be unique
 The first character must be an alphabet or underscore.
 You cannot use a keyword as identifiers.
 Only first thirty-one (31) characters are significant.
 Must not contain white spaces.
 Identifiers are case-sensitive.
C Operators

An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

o Arithmetic Operators
o Relational Operators
o Shift Operators 0110
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o Misc Operator

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to
left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to


right

Unary + - ! ~ ++ - - (type)* & sizeof Right to


left

Multiplicative */% Left to


right

Additive +- Left to
right
Shift << >> Left to
right

Relational < <= > >= Left to


right

Equality == != Left to
right

Bitwise AND & Left to


right

Bitwise XOR ^ Left to


right

Bitwise OR | Left to
right

Logical AND && Left to


right

Logical OR || Left to
right

Conditional ?: Right to
left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to


left

Comma , Left to
right

Arithmetic Operators

Arithmetic Operators are used to performing mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and modulus (%).
Operator Description

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

C Program to Add Two Numbers


Example:

#include <stdio.h>

void main()

int i=3,j=7,k; /* Variables Defining and Assign values */ k=i+j;

printf("sum of two numbers is %d\n", k);

Program Output:

Increment and Decrement Operators


Increment and Decrement Operators are useful operators generally used to minimize the
calculation, i.e. ++x and x++ means x=x+1 or -x and x−−means x=x-1. But there is a slight
difference between ++ or −− written before or after the operand. Applying the pre-increment
first add one to the operand and then the result is assigned to the variable on the left
whereas post-increment first assigns the value to the variable on the left and then increment
the operand.i++

i--

Operator Description

++ Increment

−− Decrement

Example: To Demonstrate prefix and postfix modes.

#include <stdio.h>//stdio.h is a header file used for input.output purpose.

void main()

//set a and b both equal to 5.

int a=5, b=5;

//Print them and decrementing each time.

//Use postfix mode for a and prefix mode for b.

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);

printf("\n%d %d",a--,--b);
}

Program Output:

54

43

32

21

10

Relational Operators
Relational operators are used to comparing two quantities or values.

Operator Description

== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

Logical Operators
C provides three logical operators when we test more than one condition to make decisions.
These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning logical NOT).
Operator Description

&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates to
False, the result is False)

|| Or operator. It performs a logical disjunction on two expressions. (if either or


both expressions evaluate to True, the result is True)

! Not operator. It performs logical negation on an expression.

Bitwise Operators
C provides a special operator for bit operation between two variables.

Operator Description

<< Binary Left Shift Operator

>> Binary Right Shift Operator

~ Binary Ones Complement Operator

& Binary AND Operator

^ Binary XOR Operator

| Binary OR Operator

Assignment Operators
Assignment operators applied to assign the result of an expression to a variable. C has a
collection of shorthand assignment operators.
Operator Description

= Assign

+= Increments then assign

-= Decrements then assign

*= Multiplies then assign

/= Divides then assign

%= Modulus then assign

<<= Left shift and assign

>>= Right shift and assign

&= Bitwise AND assign

^= Bitwise exclusive OR and assign

|= Bitwise inclusive OR and assign

Conditional Operator
C offers a ternary operator which is the conditional operator (?: in combination) to construct
conditional expressions.

Operator Description
?: Conditional Expression

Special Operators
C supports some special operators

Operator Description

sizeof() Returns the size of a memory location.

& Returns the address of a memory location. &I *i

* Pointer to a variable.

Program to demonstrate the use of sizeof operator


Example:

#include <stdio.h>

void main()

int i=10; /* Variables Defining and Assign values */ printf("integer: %d\n", sizeof(i));

Program Output:
C Type Conversion – Implicit & Explicit Type Conversion in C

When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is
called type conversion.

Type conversion in c can be classified into the following two types:

Implicit Type Conversion

When the type conversion is performed automatically by the compiler without


programmer’s intervention, such type of conversion is known as implicit type
conversion or type promotion.

The compiler converts all operands into the data type of the largest operand. A+B

The sequence of rules that are applied while evaluating expressions are given below:

All short and char are automatically converted to int, then,

1. If either of the operand is of type long double, then others will be converted to long double
and result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to unsigned
long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
1. if a long int can represent all values of an unsigned int, the unsigned int is converted to
long int.
2. otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then other will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.

It should be noted that the final result of expression is converted to type of variable on left
side of assignment operator before assigning value to it.

Also, conversion of float to int causes truncation of fractional part, conversion of double to
float causes rounding of digits and the conversion of long int to int causes dropping of excess
higher order bits. 0 1

bool -> char -> short int -> int ->


unsigned int -> long -> unsigned ->
long long -> float -> double -> long double

Example of Type Implicit Conversion:


// An example of implicit conversion
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y; 10+ 97=107(X)

// x is implicitly converted to float


float z = x + 1.0; 107+1.0

printf("x = %d, z = %f", x, z); X=107 Z=


return 0;
}
Output:
x = 107, z = 108.000000

Explicit Type Conversion

The type conversion performed by the programmer by posing the data type of the expression
of specific type is known as explicit type conversion.

The explicit type conversion is also known as type casting.


Type casting in c is done in the following form:

(data_type)expression;

where, data_type is any valid c data type, and expression may be constant, variable or
expression.

For example,

x=(int)a+b*d;

The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:

1. All integer types to be converted to float.


2. All float types to be converted to double.
3. All character types to be converted to integer.

// C program to demonstrate explicit type casting


#include<stdio.h>

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

printf("sum = %d", sum);

return 0;

Output:
sum = 2
Type Casting

Type Casting in C is used to convert a variable from one data type to another data type, and
after type casting compiler treats the variable as of the new data type.

Syntax:
(type_name) expression

Without Type Casting


Example:

#include <stdio.h>

main ()

int a;

a = 15/6;

printf("%d",a);

Program Output:

In the above C program, 15/6 alone will produce integer value as 2.

After Type Casting


#include <stdio.h>

main ()

float a;

a = (float) 15/6;

printf("%f",a);

}
Program Output:

After type cast is done before division to retain float value 2.500000.

Stdio.h

Step 1: enter two nos a and b

Step 2:set sum=a+b

Step 3: display sum

Step4: end

Read two nos a & b

Set sum=a+b

Print sum

end
start

Enter two nos a & b

Sum=a+b

Print sum

end
READ number
remainder=number%2
IF remainder==0
WRITE "Even Number"
ELSE
WRITE "Odd Number"
ENDIF
algorithm

Step 1: Start
Step 2: [ Take Input ] Read: Number

Step 3: Check: If Number%2 == 0 Then

Print : N is an Even Number.

Else

Print : N is an Odd Number.

Step 4: Exit

1. #include <stdio.h>
2. int main()
3. {
4. int number;
5.
6. printf("Enter an integer: ");
7. scanf("%d", &number);
8.
9. // True if the number is perfectly divisible by 2
10. if(number % 2 == 0)
11. printf("%d is even.", number);
12. else
13. printf("%d is odd.", number);
14.
15. return 0;
16. }
Output

1. Enter an integer: -7
2. -7 is odd.

Decision Control Statements in C Programming


Introduction

We generally follow a sequence in the program but at times we would just want to execute
only selected statements.
 This type of conditional processing is really useful to the programs.
 It allows the programmers to build the programs that determine which statements of
the code should be executed and which are to be ignored.

Conditional statements

The conditional statements help to jump from one part of a program to another depending if
a particular condition is satisfied or not.
The conditional statements are:

1. if statement

It is one of the most simple form of decision control statements which is frequently used in
decision making.

Syntax:
if (test expression)
{
statement 1;
…...............
statement n;
}
statement x;

 The if structure may have one statement or n number of statements which are
enclosed within the curly braces ({ }).
 Initially the test expression is evaluated.
 If this expression is true the statement of the if block is executed or all the statements
will be skipped and statement x will be executed.
Example: Demonstrating an if statement

Write a program to print the highest number.

#include <stdio.h>
void main()
{
int n;
printf("Enter a number:");
scanf("%d", &n); 120
printf ("The entered number %d", n);
if (n>100)
{
printf ("You entered a higher number");
}
printf ("You entered lower no.");
}
o/p
In the above program, a number is accepted as an input from the user and the output is
given. The expression (n>100) is given. If the user gives a number higher than 100 then only
will the message be printed else the statement will be skipped.

#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}

2. If-else statement

Example of multiple if statements

We can use multiple if statements to check more than one conditions.

#include <stdio.h>
int main()
{
int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}
printf("End of Program");
return 0;
}
In the above example the output depends on the user input.

Output:

enter the value of x:20


enter the value of y:20
x is equal to y
End of Program

There are times where we would like to write that if the expression is true an action should
be taken and if the expression is false there would be no action. We can also include an action
for both the conditions.

In such cases, we use the if-else statement.

Syntax:
if (expression)
Statement 1;
else
Statement 2;

If the expression is true statement 1 will be executed and if the expression is false statement
2 will be executed.

Example: Program for leap year Boolean AND OR

#include <stdio.h>
#include<conio.h>
void main()
{
int yr;
clrscr();
printf("Enter a year:");
scanf("%d", &yr);1971
if ((yr%4 == 0) && ((yr%100 !=0) || (yr%400==0)))
printf("It's a leap year...!!!!");
else
printf ("It's not a leap year....!!!");
}
Output:
Enter a year: 1997
It's not a leap year...!!!

3. if-else-if statement

 This statement works in the normal way as the if statement.


 Its construct is known as the nested if statement.
 After the first if branch the program can have many other else-if branches depending
on the expressions that need to be tested.
Syntax:
if (test expression 1)
{
statement block 1;
}
else if (test expression 2)
{
statement block 2;
}
....................
else
{
statement block x;
}
statement y;
Example: Program to find largest of the three numbers by using && operator.

#include <stdio.h>
void main()
{
int n1=10, n2=30, n3=75;
if (n1>n2 && n1>n3)
printf("%d is the largest number",n1);
else if(n2>n1 && n2>n3)
printf("%d is the largest number", n2);
else
printf("%d is the largest number", n3);
}

Output:
75 is the largest number.

4. Switch case

This case statement is a multi-way decision statement which is a simpler version of the if-else
block which evaluates only one variable.

Syntax:
switch (expression)
{
case expression 1: statement 1;
statement 2;
............
statement n;
break;

case expression 2: statement 1;


statement 2;
..........
statement n;
break;

default: statement 1;
statement 2;
...........
statement n;
}

All the expressions should have a result of an integer value or the character value.

Example: Write a program to check if the character entered is a vowel or not.

#include <stdio.h>
void main( )
{
char ch;
printf("Enter any character:");
scanf("%c", &ch);
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':
printf("%c is a vowel",ch);
break;
default:
printf("%c is not a vowel", ch);
}
}

Output:
Enter any character: c
c is not a vowel.

Types of Loops in C

Depending upon the position of a control statement in a program, looping statement in C is


classified into two types:

1. Entry controlled loop

2. Exit controlled loop


In an entry control loop in C, a condition is checked before executing the body of a loop. It is
also called as a pre-checking loop.

In an exit controlled loop, a condition is checked after executing the body of a loop. It is also
called as a post-checking loop.

The control conditions must be well defined and specified otherwise the loop will execute an
infinite number of times. The loop that does not stop executing and processes the statements
number of times is called as an infinite loop. An infinite loop is also called as an "Endless
loop." Following are some characteristics of an infinite loop:

1. No termination condition is specified.

2. The specified conditions never meet.

The specified condition determines whether to execute the loop body or not.

'C' programming language provides us with three types of loop constructs:

1. The while loop

2. The do-while loop

3. The for loop

Sr. Loop
Description
No. Type

While In while loop, a condition is evaluated before processing a body of the loop. If a
1.
Loop condition is true then and only then the body of a loop is executed.

Do-While In a do...while loop, the condition is always executed after the body of a loop. It is
2.
Loop also called an exit-controlled loop.

In a for loop, the initial value is performed only once, then the condition tests and
3. For Loop compares the counter to a fixed value after each iteration, stopping the for loop
when false is returned.

While Loop in C

A while loop is the most straightforward looping structure. While loop syntax in C
programming language is as follows:
Syntax of While Loop in C:
while (condition) {
statements;
}

It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body


of the loop. If a condition is true then and only then the body of a loop is executed. After the
body of a loop is executed then control again goes back at the beginning, and the condition is
checked if it is true, the same process is executed until the condition becomes false. Once the
condition becomes false, the control goes out of the loop.

After exiting the loop, the control goes to the statements which are immediately after the
loop. The body of a loop can contain more than one statement. If it contains only one
statement, then the curly braces are not compulsory. It is a good practice though to use the
curly braces even we have a single statement in the body.

In while loop, if the condition is not true, then the body of a loop will not be executed, not
even once. It is different in do while loop which we will see shortly.

Following program illustrates while loop in C programming example:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; 11 //incrementing operation
}
return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10

The above program illustrates the use of while loop. In the above program, we have printed
series of numbers from 1 to 10 using a while loop.

While Loop in C Programming

1. We have initialized a variable called num with value 1. We are going to print from 1 to
10 hence the variable is initialized with value 1. If you want to print from 0, then assign
the value 0 during initialization.
2. In a while loop, we have provided a condition (num<=10), which means the loop will
execute the body until the value of num becomes 10. After that, the loop will be
terminated, and control will fall outside the loop.
3. In the body of a loop, we have a print function to print our number and an increment
operation to increment the value per execution of a loop. An initial value of num is 1,
after the execution, it will become 2, and during the next execution, it will become 3.
This process will continue until the value becomes 10 and then it will print the series on
console and terminate the loop.

\n is used for formatting purposes which means the value will be printed on a new line.

Do-While loop in C

A do...while loop in C is similar to the while loop except that the condition is always executed
after the body of a loop. It is also called an exit-controlled loop.

Syntax of do while loop in C programming language is as follows:

Syntax of Do-While Loop in C:


do {
statements
} while (expression);

As we saw in a while loop, the body is executed if and only if the condition is true. In some
cases, we have to execute a body of the loop at least once even if the condition is false. This
type of operation can be achieved by using a do-while loop.

In the do-while loop, the body of a loop is always executed at least once. After the body is
executed, then it checks the condition. If the condition is true, then it will again execute the
body of a loop otherwise control is transferred out of the loop.

Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.
The critical difference between the while and do-while loop is that in while loop the while is
written at the beginning. In do-while loop, the while condition is written at the end and
terminates with a semi-colon (;)

The following loop program in C illustrates the working of a do-while loop:

Below is a do-while loop in C example to print a table of number 2:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}

Output:

2
4
6
8
10
12
14
16
18
20

In the above example, we have printed multiplication table of 2 using a do-while loop. Let's
see how the program was able to print the series.

Do-While Loop in C Programming

1. First, we have initialized a variable 'num' with value 1. Then we have written a do-while
loop.
2. In a loop, we have a print function that will print the series by multiplying the value of
num with 2.
3. After each increment, the value of num will increase by 1, and it will be printed on the
screen.
4. Initially, the value of num is 1. In a body of a loop, the print function will be executed in
this way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This
will go on until the value of num becomes 10. After that loop will be terminated and a
statement which is immediately after the loop will be executed. In this case return 0.

For loop in C

A for loop is a more efficient loop structure in 'C' programming. The general structure of for
loop syntax in C is as follows:

Syntax of For Loop in C: int a=4;


for (initial value; condition; incrementation or decrementation )
{
statements;
}

 The initial value of the for loop is performed only once.


 The condition is a Boolean expression that tests and compares the counter to a fixed
value after each iteration, stopping the for loop when false is returned.
 The incrementation/decrementation increases (or decreases) the counter by a set
value.

Following program illustrates the for loop in C programming example:

#include<stdio.h> number-1
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10

The above program prints the number series from 1-10 using for loop.

For Loop in C Programming

1. We have declared a variable of an int data type to store values.


2. In for loop, in the initialization part, we have assigned value 1 to the variable number.
In the condition part, we have specified our condition and then the increment part.
3. In the body of a loop, we have a print function to print the numbers on a new line in
the console. We have the value one stored in number, after the first iteration the value
will be incremented, and it will become 2. Now the variable number has the value 2.
The condition will be rechecked and since the condition is true loop will be executed,
and it will print two on the screen. This loop will keep on executing until the value of
the variable becomes 10. After that, the loop will be terminated, and a series of 1-10
will be printed on the screen.

In C, the for loop can have multiple expressions separated by commas in each part.

For example:

for (x = 0, y = num; x < y; i++, y--) {


statements;
}

Also, we can skip the initial value expression, condition and/or increment by adding a
semicolon.

For example:

int i=0;
int max = 10;
for (; i < max; i++) {
printf("%d\n", i);
}

Notice that loops can also be nested where there is an outer loop and an inner loop. For each
iteration of the outer loop, the inner loop repeats its entire cycle.

Consider the following example with multiple conditions in for loop, that uses nested for loop
in C programming to output a multiplication table: 123
#include <stdio.h>
int main() {
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) { // outer loop
for (j = 1; j <= max; j++) { // inner loop
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n"); /* blank line between tables */
}}

Output:

1x0=0
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5

2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10

The nesting of for loops can be done up-to any level. The nested loops should be adequately
indented to make code readable. In some versions of 'C,' the nesting is limited up to 15 loops,
but some provide more.

The nested loops are mostly used in array applications which we will see in further tutorials.

Break Statement in C

The break statement is used mainly in in the switch statement. It is also useful for
immediately stopping a loop.

We consider the following program which introduces a break to exit a while loop:

#include <stdio.h>
int main() {
int num = 5;
while (3 > 0)
{
if (3== 3)
break;
printf("%d\n", num);
num--;
}
}

Output:

5
4

Continue Statement in C

When you want to skip to the next iteration but remain in the loop, you should use the
continue statement.

For example:

#include <stdio.h>
int main() {
int nb = 7;
while (nb > 0)
{
nb--;
if (nb == 5)
continue;
printf("%d\n", nb);
}}

Output:

6
4
3
2
1

So, the value 5 is skipped.

Which loop to Select?


Selection of a loop is always a tough task for a programmer, to select a loop do the following
steps:

 Analyze the problem and check whether it requires a pre-test or a post-test loop.
 If pre-test is required, use a while or for a loop.
 If post-test is required, use a do-while loop.
CHAPTER-7

ADVANCE FEATURES IN C

C Functions
In c, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity to the
C program. In other words, we can say that the collection of functions creates a
program. The function is also known as procedure or subroutine in other
programming languages.

Printf();

Clrscr();

Getch();

void add_prog()

Void sub()

Void mul()

Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Syntax of a function
return_type function_name (argument list) void ()
{
Set of statements – Block of code
}

Function Aspects

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to


tell the compiler about the function name, function parameters, and return
type.

o Function call Function can be called from anywhere in the program.


parameter list must not differ in function calling and function declaration.
We must pass the same number of functions as it is declared in the function
declaration.

o Function definition It contains the actual statements which are to be


executed. It is the most important aspect to which the control comes when
the function is called. Here, we must notice that only one value can be
returned from the function.

Return a;

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);int add(int a,int


b);

2 Function call function_name (argument_list); add();

3 Function definition return_type function_name (argument list) {function


body;}int add(){ }

Function declaration consists of 4 parts.

 returntype
 function name
 parameter list
 terminating semicolon
Returntype
When a function is declared to perform some sort of calculation or any operation and is
expected to provide with some result at the end, in such cases, a return statement is
added at the end of function body. Return type specifies the type of
value(int, float, char, double) that function is expected to return to the program which
called the function.
Note: In case your function doesn't return any value, the return type would be void.
Function Name
Function name is an identifier and it specifies the name of the function. The function name
is any valid C identifier and therefore must follow the same naming rules like other
variables in C language.

Parameter list

The parameter list declares the type and number of arguments that the function expects
when it is called. Also, the parameters in the parameter list receives the argument values
when the function is called. They are often referred as formal parameters.

The syntax of creating function in c language is given below:

return_type function_name(data_type parameter...){


//code to be executed
}

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header
files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.

Return Value

A C function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the
function.
Example without return value:

void hello(){
printf("hello c");
}

If you want to return any value from the function, you need to use any data type
such as int, long, char, etc. The return type depends on the value to be returned
from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

int get(){
return 10;
}

In the above example, we have to return 10 as a value, so the return type is int. If
you want to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use
float as the return type of the method.

float get(){
return 10.2;
}

Now, you need to call the function, to get the value of the function.

Different aspects of function calling

A function may or may not accept any argument. It may or may not return any
value. Based on these facts, There are four different aspects of function calls.

o function without arguments and without return value () void void add()
o function without arguments and with return value () int int add()
o function with arguments and without return value (int a) void void add(int a)
o function with arguments and with return value (int a) float float add(float a)

Example for Function without argument and without return value

Example 1
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("oops");
11. }

Output

Hello oops

Example 2
1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value

Example 1
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }
Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the area of the square


1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and without return value

Example 1
1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers.


1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value

Example 1
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }

Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

C Library Functions

Library functions are the inbuilt function in C that are grouped and placed at a common place called the library.
Such functions are used to perform some specific operations. For example, printf is a library function used to
print on the console. The library functions are created by the designers of compilers. All C standard library
functions are defined inside the different header files saved with the extension .h. We need to include these
header files in our program to make use of the library functions defined in such header files. For example, To
use the library functions such as printf/scanf we need to include stdio.h in our program which is a header file
that contains all the library functions regarding standard input/output.

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.
Call by value in C

o In call by value method, the value of the actual parameters is copied into the formal parameters. In
other words, we can say that the value of the variable is used in the function call in the call by value
method.
o In call by value method, we can not modify the value of the actual parameter by the formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since the value of the
actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal parameter is the
argument which is used in the function definition.

Concept of call by value in c language by the example given below:

1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }

Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change
by changing the formal parameters in call by value, a = 10, b = 20
10. }
11. void swap (int a, int b)
12. {
13. int temp;
14. temp = a;
15. a=b;
16. b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10
18. }

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C

o In call by reference, the address of the variable is passed into the function call as the actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters since the address
of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and actual parameters.
All the operations in the function are performed on the value stored at the address of the actual
parameters, and the modified value gets stored at the same address.

Example for the call by reference.

1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }

Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Call by reference Example: Swapping the values of the two variables


1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in c
all by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10
18. }

Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c

No. Call by value Call by reference

1 A copy of the value is passed into the function An address of value is passed into the function

2 Changes made inside the function are limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of the
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.

3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location same memory location

SCOPE OF THE VARIABLE

Global variable

Global variables can be accessed at any point throughout the program, and can be used in any function. There
is single copy of the global variable is available.Global variables are defined outside of all the functions, usually
on top of the program.

Local variable
Variable declared inside a function or block of code are called local variables. They can be accessed only inside
that function or block of code. Local variables are not available to outside function.

Example Program:

#include <stdio.h>/* global variable declaration */

int sum;

int main ()

/* local variable declaration */ int a, b;

/* actual initialization */ a = 10;

b = 20;

sum = a + b;

printf ("value of a = %d, b = %d and sum of (a and b) is = %d\n", a, b, sum return 0;

Note :- A program can have same name for local and global variables but local variable overrides the value.

C storage classes
In C Programming Language a “Storage Class” refers to the scope or visibility and the life time of the C
Variable. Scope of the C Variable defines the availability of the variable in block of the C Program, and by
life time of variable means how long variable will persist in the program.

Functions of storage class

It tell the location of the C Variable.

Sets the initial or default value of

C Variable. It defines the scope of

the C Variable.

It defines the life time of C Variable.


Types of storage class
C Programming Language Supports following four type of storage classes:

auto register static extern

auto-storage class

It is the default storage class for local variables. Variables with auto storage class are declared at the
beginning of a code block, and memory is allocated automatically as the program execution enters to a
code block and frees up automatically on exiting from the code block. The scope of automatic variables is
local to the block where the declared and are not accessible directly in the other block.

Syntax:

auto [data_type] [variable_name];

Example :

auto int a;

register-storage class

C Variables with register storage class are same as local variables to the code block but the are stored in
CPU register instead of computer memory. Hence it enables the quick access of that variable. Maximum
size of the variable is equal to register size and dependent upon the

register size

Syntax:

register [data_type] [variable_name];

Example:

register int a;

static-storage class

It is default storage class for global variables.Static storage class can be used only if we want the value of a
variable to persist between different function calls. C Variable declared with static storage class will keep its
value retained for different function calls.

Syntax:

static [data_type] [variable_name];

Example:

static int a;

extern-storage class
C Variable declared with extern storage class is said to be “Global Variables”, it means variables is accessible
throughout the program till the end of program execution. External variables are declared outside the functions
and can be invoked from and anywhere in a program.External variables can be accessed very fast as compared
to any other storage classes.

Syntax:

extern [data_type] [variable_name];

Example:

extern int a;

C - Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows
you to call a function inside the same function, then it is called a recursive call of the function.

How recursion works?


void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

……..

}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite
loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a
number, generating Fibonacci series, etc.

Number Factorial

The following example calculates the factorial of a given number using a recursive function –
Recursion is used to calculate the factorial of a number
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Output
Enter the number whose factorial you want to calculate?5
factorial = 120

Fibonacci Series

The following example generates the Fibonacci series for a given number using a recursive function −
#include <stdio.h>
int fibonacci(int i) {

if(i == 0) {
return 0;
}

if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

int main() {

int i;

for (i = 0; i < 10; i++) {


printf("%d\t\n", fibonacci(i));
}

return 0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
Some more examples:

1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }

Output
Enter the value of n? 12
144

What are the different types of Recursion in C?

1. Primitive Recursion
It is the types of recursion that can be converted into a loop.

We have already seen the Fibonacci series example which can be programmed with recursion as well as with
loop.

2. Tail Recursion
It is a primitive recursion in which the recursive call is present as the last thing in the function.

In the above Fibonacci example, the recursive function is executed as the last statement of the ‘fibo’ function.

3. Single Recursion
It is the types of recursion when there is only one recursive call in the function.
4. Multiple Recursion
As by its name, it is the types of recursion when there are multiple recursive calls in the function.

It is just the opposite of a single recursion. Recursion can be either single or multiple type.

5. Mutual Recursion or Indirect Recursion)


There are two or more functions involved in this type of recursion.

In this type of recursion, a function calls another function, which eventually calls the original function.

6. General Recursion
If there is a function which cannot be defined without recursion, is called as general recursion.

It is the opposite of primitive type recursion.

These are the different types of recursion in C.

More about it:

Types of Recursion
Recursive functions can be classified on the basis of :
a.) If the functions calls itself directly or indirectly. – Direct / Indirect
b.) If an operation is pending at each recursive call. – Tail Recursive/ Not
c.) based on the structure of function calling pattern. – Linear / Tree

a.) Direct Recursion:


If a function explicitly calls itself it is called directly recursive.

When the method invokes itself it is direct.

Example:

int testfunc( int num)


{
if (num == 0)
return 0;
else
return (testfunc(num-1));
}
Here, the function ‘testfunc’ calls itself for all positive values of num.

b.) Indirect Recursion:

This occurs when the function invokes other method which again causes the original function to be called again.

If a method ‘X’ , calls method ‘Y’, which calls method ‘Z’ which again leads to ‘X’ being invoked is called indirect
recursive or mutually recursive as well.

Example:

int testfunc1( int num)


{
if (num == 0)
return 0;
else
return (testfunc2(num-1));
}
int testfunc2(int num2)
{ return testfunc1( num2-1); }

Tail / Bottom Recursion:

A function is said to be tail recursive, if no operations are pending when the recursive function returns to its
caller.

Such functions, immediately return the return value from the calling function.

It is an efficient method as compared to others, as the stack space required is less and even compute overhead
will get reduced.
Recollect the previously discussed example, factorial of a number. We had written it in non tail recursive way, as
after call operation is still pending.

int fact (int n)

{
if (n==1)
return 1;
else
return (n*fact(n-1));
}
In order to make it tail recursive, information about pending tasks has to be tracked.

Tail recursion:

int fact (int n)

{return (n*fact2(n-1));}

int fact2(int n, int result)


{
if (n==1)
return result;
return fact2(n-1, n*result);}

If you observe, the ‘fact2’ has similar syntax to the original fact. Now, ‘fact’ in tail recursion case does not have
pending calculations / operations to perform on return from recursive function calls.
The value computed by fact2 is simply returned. Thus, amount of space required on stack reduces considerably .
( just for value of n and result , space required.)

Linear and Tree Recursion:

Depending on the structure the recursive function calls take, or grows it can be either linear or non linear.
It is linearly recursive when, the pending operations do not involve another recursive call to the function. Our
Factorial recursive function is linearly recursive as it only involves multiplying the returned values and no further
calls to function.
Tree recursion is when, pending operations involve another recursive call to function.
For example – Fibonacci series ; the pending operations have recursive call to the fib() recursive function to
compute the results.

When not to use recursion ?


Essentially, any problem that can be solved by recursion can be also solved by iteration. Although for certain
applications like Tower of Hanoi, certain artificial intelligence problems etc recursion is used since it defines the
problem naturally, still there are certain times when recursion should not be used.

Iterations are faster than their recursive counterparts. So, for speed we would normally use iteration.
If the stack limit is constraining then we will prefer iteration over recursion.

Some problems are naturally programmed recursively, here recursion would suit better.

The overhead involved in recursion in terms of time and space consumed both discourages to use recursion
often.

Array in c
An array is a series of elements of the similar type placed in contiguous memory locations that can be
accessed individually by adding an index or subscript to a unique identifier. An array is made up of a key and a
value pair, and the key points to the value. Arrays may be of any variable type.

Types of an Array

One / Single Dimensional Array

Multi dimensional array ( Example : Two dimensional array )

Single / One Dimensional Array :

A one-dimensional array is a structured collection of array elements that can be accessed individually by
specifying the position of a element with a single index value.

Declaring Single Dimensional Array


<data-type> <array_name> [size];

//total size = length of array * size of data type

Example:

int a[100];

Initializing an Array
int arr[5] = {10,20,30,40,50};

Accessing Array’s Elements

An array elements can be accessed easily by index or subscript like array_name[index]. Indexing for an array
starts from zero (0) to the last element of an array is array_name[size- 1] where size is the number of
elements of the array.

Example program for one/single dimension C array:


#include<stdio.h>
int main()

{
int i;

int arr[5] = {10,20,30,40,50};

// declaring and Initializing array

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

// Accessing each variable

printf("value of arr[%d] is %d \n", i, arr[i]);

Output:

value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

Multi dimensional array ( Example : Two dimensional array )

Multidimensional arrays is nothing just an array of arrays. We can declare a multidimensional array, as below:

<data-type> <array_name>[size][size2][size3]…

Example program for two/multi dimension C array:

#include<stdio.h> int
main()

int i,j;

// declaring and Initializing array int arr[2][2]


= {10,20,30,40};
for (i=0;i<2;i++)

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

// Accessing variables

printf("value of arr[%d][%d] is %d\n",i,j,arr[i][j]);

Output:

value of arr[0][0] is 10

value of arr[0][1] is 20

value of arr[1][0] is 30

value of arr[1][1] is 40

C Programming Strings
In C programming, a string is a sequence of characters terminated with a null character \0. For example:
1. char c[] = "c string";
2. When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends
a null character \0 at the end by default.

How to declare a string?


Here's how you can declare strings:

1. char s[5];

2.

Here, we have declared a string of 5 characters.


How to initialize strings?

You can initialize strings in a number of ways.

1. char c[] = "abcd";


2.
3. char c[50] = "abcd";
4. char c[] = {'a', 'b', 'c', 'd', '\0'};
5.
6. char c[5] = {'a', 'b', 'c', 'd', '\0'};

Let's take another example:

1. char c[5] = "abcde";


2. Here, we are trying to assign 6 characters (the last character is '\0') to a char array having 5 characters. This is
bad and you should never do this.

Read String from the user


You can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab etc.).

Example 1: scanf() to read a string


1. #include <stdio.h>
2. int main()
3. {
4. char name[20];
5. printf("Enter name: ");
6. scanf("%s", name);
7. printf("Your name is %s.", name);
8. return 0;
9. }

Output

Enter name: Dennis Ritchie

Your name is Dennis.

Even though Dennis Ritchie was entered in the above program, only "Ritchie" was stored in the name string. It's
because there was a space after Dennis.

How to read a line of text?


You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

Example 2: fgets() and puts()


1. #include <stdio.h>
2. int main()
3. {
4. char name[30];
5. printf("Enter name: ");
6. fgets(name, sizeof(name), stdin); // read string
7. printf("Name: ");
8. puts(name); // display string
9. return 0;
10. }
Output

Enter name: Tom Hanks


Name: Tom Hanks

Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of
the name string.
To print the string, we have used puts(name);.
Note: The gets() function can also be to take input from the user. However, it is removed from the C standard.

It's because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.

Passing Strings to Functions


Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to a function.

Example 3: Passing string to a Function


1. #include <stdio.h>
2. void displayString(char str[]);
3.
4. int main()
5. {
6. char str[50];
7. printf("Enter string: ");
8. fgets(str, sizeof(str), stdin);
9. displayString(str); // Passing string to a function.
10. return 0;
11. }
12. void displayString(char str[])
13. {
14. printf("String Output: ");
15. puts(str);
16. }

Strings and Pointers


Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to manipulate elements
of the string. We recommended you to check C Arrays and Pointers before you check this example.

Example 4: Strings and Pointers


1. #include <stdio.h>
2.
3. int main(void) {
4. char name[] = "Harry Potter";
5.
6. printf("%c", *name); // Output: H
7. printf("%c", *(name+1)); // Output: a
8. printf("%c", *(name+7)); // Output: o
9.
10. char *namePtr;
11.
12. namePtr = name;
13. printf("%c", *namePtr); // Output: H
14. printf("%c", *(namePtr+1)); // Output: a
15. printf("%c", *(namePtr+7)); // Output: o
16. }

Commonly Used String Functions


 strlen() - calculates the length of a string
 strcpy() - copies a string to another
 strcmp() - compares two strings
 strcat() - concatenates two strings

C pointer
Pointers is one of the most powerful feature available in C Programming Language . Pointer is a special type of
variable that refers to the address of other data object or variable.Variable can be of any data type i.e int,
float, char, double, short etc.Pointer is used for dynamic memory allocation.

Syntax to declare pointer variable:

<data_type> *pointer_name;

data_type specifies the type of pointer, then asterisk (*) followed by the pointer name.

Example:

Example Program to demonstrate pointer

int *ptr;

#include <stdio.h>

int main()

{
int *ptr; int
var1; var1 =
20;

/* address of var1 is assigned to ptr*/

ptr = &var1;

/* display var1's value using ptr variable */

printf("%d", *ptr);

return 0;

Output:

20

Pointer Expressions

We can use pointer variables in expression.

Example:
int x = 10, y = 20, z;
int *ptr1 = &x;
int *ptr2 = &y;
z = *ptr1 * *ptr2 ;
Will assign 200 to variable z.

We can perform addition and subtraction of integer constant from pointer variable.

Example:
ptr1 = ptr1 + 2;
ptr2 = ptr2 – 2;

We can not perform addition, multiplication and division operations on two pointer variables.
For Example:
ptr1 + ptr2 is not valid

However we can subtract one pointer variable from another pointer variable.
We can use increment and decrement operator along with pointer variable to increment or decrement the
address contained in pointer variable.

Example:
ptr1++;
ptr2--;

We can use relational operators to compare pointer variables if both pointer variable points to the variables of
same data type.

Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know
that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be
a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an
integer value. Following arithmetic operations are possible on the pointer in C language:

o Increment
o Decrement
o Addition
o Subtraction
o Comparison

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by the size of
the data type to which the pointer is pointing.

We can traverse an array by using the increment operation on a pointer which will keep pointing to every
element of the array, perform some operation on that, and update itself in a loop.

The Rule to increment the pointer is given below:

1. new_address= current_address + i * size_of(data type)

Where i is the number by which the pointer get increased.


32-bit

For 32-bit int variable, it will be incremented by 2 bytes.

64-bit

For 64-bit int variable, it will be incremented by 4 bytes.

Let's see the example of incrementing pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+1;
8. printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 bytes.
9. return 0;
10. }

Output

Address of p variable is 3214864300


After increment: Address of p variable is 3214864304

Traversing an array by using pointer


1. #include<stdio.h>
2. void main ()
3. {
4. int arr[5] = {1, 2, 3, 4, 5};
5. int *p = arr;
6. int i;
7. printf("printing array elements...\n");
8. for(i = 0; i< 5; i++)
9. {
10. printf("%d ",*(p+i));
11. }
12. }

Output

printing array elements...


1 2 3 4 5

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to the
previous location. The formula of decrementing the pointer is given below:

1. new_address= current_address - i * size_of(data type)


32-bit

For 32-bit int variable, it will be decremented by 2 bytes.

64-bit

For 64-bit int variable, it will be decremented by 4 bytes.

Let's see the example of decrementing pointer variable on 64-bit OS.

1. #include <stdio.h>
2. void main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-1;
8. printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate previous locati
on.
9. }

Output

Address of p variable is 3214864300


After decrement: Address of p variable is 3214864296

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

1. new_address= current_address + (number * size_of(data type))

32-bit

For 32-bit int variable, it will add 2 * number.

64-bit

For 64-bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+3; //adding 3 to pointer variable
8. printf("After adding 3: Address of p variable is %u \n",p);
9. return 0;
10. }
Output

Address of p variable is 3214864300


After adding 3: Address of p variable is 3214864312

As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312, i.e.,
4*3=12 increment. Since we are using 64-bit architecture, it increments 12. But if we were using 32-bit
architecture, it was incrementing to 6 only, i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.

C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a
pointer will give an address. The formula of subtracting value from the pointer variable is given below:

1. new_address= current_address - (number * size_of(data type))

32-bit

For 32-bit int variable, it will subtract 2 * number.

64-bit

For 64-bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from the pointer variable on 64-bit architecture.

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-3; //subtracting 3 from pointer variable
8. printf("After subtracting 3: Address of p variable is %u \n",p);
9. return 0;
10. }

Output

Address of p variable is 3214864300


After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address value.

However, instead of subtracting a number, we can also subtract an address from another address (pointer).
This will result in a number. It will not be a simple arithmetic operation, but it will follow the following rule.

If two pointers are of the same type,

1. Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points

Consider the following example to subtract one pointer from an another.


1. #include<stdio.h>
2. void main ()
3. {
4. int i = 100;
5. int *p = &i;
6. int *temp;
7. temp = p;
8. p = p + 3;
9. printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
10. }

Output

Pointer Subtraction: 1030585080 - 1030585068 = 3

Illegal arithmetic with pointers

There are various operations which can not be performed on pointers. Since, pointer stores address hence we
must ignore the operations which may lead to an illegal address, for example, addition, and multiplication. A
list of such operations is given below.

o Address + Address = illegal


o Address * Address = illegal
o Address % Address = illegal
o Address / Address = illegal
o Address & Address = illegal
o Address ^ Address = illegal
o Address | Address = illegal
o ~Address = illegal

Pointer to function in C

As we discussed in the previous chapter, a pointer can point to a function in C. However, the declaration of
the pointer variable must be the same as the function. Consider the following example to make a pointer
pointing to the function.

1. #include<stdio.h>
2. int addition ();
3. int main ()
4. {
5. int result;
6. int (*ptr)();
7. ptr = &addition;
8. result = (*ptr)();
9. printf("The sum is %d",result);
10. }
11. int addition()
12. {
13. int a, b;
14. printf("Enter two numbers?");
15. scanf("%d %d",&a,&b);
16. return a+b;
17. }

Output

Enter two numbers?10 15


The sum is 25

Pointer to Array of functions in C

To understand the concept of an array of functions, we must understand the array of function. Basically, an
array of the function is an array which contains the addresses of functions. In other words, the pointer to an
array of functions is a pointer pointing to an array which contains the pointers to the functions. Consider the
following example.

1. #include<stdio.h>
2. int show();
3. int showadd(int);
4. int (*arr[3])();
5. int (*(*ptr)[3])();
6.
7. int main ()
8. {
9. int result1;
10. arr[0] = show;
11. arr[1] = showadd;
12. ptr = &arr;
13. result1 = (**ptr)();
14. printf("printing the value returned by show : %d",result1);
15. (*(*ptr+1))(result1);
16. }
17. int show()
18. {
19. int a = 65;
20. return a++;
21. }
22. int showadd(int b)
23. {
24. printf("\nAdding 90 to the value returned by show: %d",b+90);
25. }

Output

printing the value returned by show : 65


Adding 90 to the value returned by show: 155

Structure in C
In C Programing Language we can use arrays when we want hold multiple element of the homogeneous data
type in single variable, but what if we want to hold heterogeneous data type element, using structure you can
wrap one or more variables that may be in different data types into one.

Syntax: struct struct_name{ structure_member };

To define a structure, you use the struct keyword followed by structure name. The variables which are declared
inside the structure are called as ‘members of structure’.

Example:

struct student

int id;

char name[20];
float percentage;

};

The student structure contains id as an positive integer, name as a string, percentage code as a
float.

Declaring structure:

The above example only defines an student structure without creating any structure variable. To declare a
structure variable, you can do it in two ways:

Declaring structure with variable together:


struct struct_name {

structure_member;

...

instance_1,instance_2 instance_n;
Declaring the structure variable after you define the structure:

struct struct_name instance_1,instance_2 instance_n;

Note :– When declaring structure following points need to be keep in mind –

Structure is always terminated with semicolon (;).

Structure name as struct_name can be later used to declare structure variables of its type in a program.

Accessing structure members

Member operator ‘.’ is used to access the individual structure members. It is also known as ‘dot operator’ or
‘period operator’.

Syntax:

structure_var.member;

addr[100];

Example Program:

#include <stdio.h>

#include<conio.h>

struct student

char name[20];

char addr[100];

} student;

void main()

clrscr();

printf("\n Enter Student Name : ");


gets (student.name);

printf("\n Enter student address: ");

gets(student.addr);

printf (“\n\n student name=%s”,student.name);

printf (“\n\n student addr=%s”,student.addr);

getch();

}
UNIONS

A union is a special data type available in C that allows to store different data types in the same memory location. You
can define a union with many members, but only one member can contain a value at any given time. Unions provide an
efficient way of using the same memory location for multiple-purpose.A union is a user- defined type similar to structs in C
programming. We recommend you to learn C structs before you check this tutorial.

How to define a union?


We use the union keyword to define unions. Here's an example:
1. union car

2. {

3. char name[50];
int price;
4.
};
5.

The above code defines a derived type union car.

Create union variables


When a union is defined, it creates a user-defined type. However, no memory is allocated. To allocate memory for a
given union type and work with it, we need to create variables.

Here's how we create union variables.


1. union car

2. {

3. char name[50];
int price;
4.
};
5.

6.
int main()
7.
{
8.
union car car1, car2, *car3;
9. return 0;

10. }

11.
Another way of creating union variables is:

1. union car

2. {

3. char name[50];
int price;
4.
} car1, car2, *car3;
5.

6.

In both cases, union variables car1, car2, and a union pointer car3 of union car type are created.

Access members of a union


We use the . operator to access members of a union. To access pointer variables, we use also use the -
> operator.
In the above example,
 To access price for car1, car1.price is used.
 To access price using car3, either (*car3).price or car3->price can be used.
Difference between unions and structures
Let's take an example to demonstrate the difference between unions and structures:

1. #include <stdio.h>

2. union unionJob

3. {

4. //defining a union
char name[32];
5.
float salary;
6.
int workerNo;
7.
} uJob;
8.

9.

10.

11. struct structJob

12. {

13. char name[32];


float salary;
14.
int workerNo;
15.
} sJob;
16.

17.
int main()
18.
{
19.
printf("size of union = %d bytes", sizeof(uJob));
20.
printf("\nsize of structure = %d bytes", sizeof(sJob));
21. return 0;

22. }

Output
size of union = 32 size of
structure = 40
Why this difference in the size of union and structure
variables?
Here, the size of sJob is 40 bytes because
 the size of name[32] is 32 bytes
 the size of salary is 4 bytes
 the size of workerNo is 4 bytes
However, the size of uJob is 32 bytes. It's because the size of a union variable will always be the size of its largest element. In
the above example, the size of its largest element, (name[32]), is 32 bytes.

Differences
Only one union member can be accessed at a time
You can access all members of a structure at once as sufficient memory is allocated for all members. However, it's not
the case in unions. You can only access a single member of a union at one time. Let's see an example.

1. #include <stdio.h>

2. union Job

3. {

4. float salary;
int workerNo;
5.
} j;
6.

7.

8.
int main()
9.
{
10.
j.salary = 12.3;
11.
j.workerNo = 100;
12.

13.

14. printf("Salary = %.1f\n", j.salary);


15. printf("Number of workers = %d", j.workerNo);
return 0;
16.

Output

Salary = 0.0

Number of workers = 100

Notice that 12.3 was not stored in j.salary.

You might also like