Ca Merged Compressed 1650254421
Ca Merged Compressed 1650254421
GOVERNMENT POLYTECHNIC,
ROURKELA-12
LECTURE NOTES
ON
COMPUTER APPLICATION
SEM-1ST/2ND
BRANCH-COMMON TO ALL
INTRODUCTION TO COMPUTER
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;
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.
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:
Advantages -
Disadvantages -
Uses -
Minicomputer:
Advantages -
Disadvantages -
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.
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.
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.
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.
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.
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 −
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.
The CPU consists of two main unit including Control Unit and Arithmetic and Logic Unit..
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.
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.
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.
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).
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.
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:
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
HARDWARE SOFTWARE
Hardware can not perform any task software can not be executed without
devices, we can see and touch We can see and also use the software
It has four main categories: input device, It is mainly divided into System
Ex: Keyboard, Mouse, Monitor, Printer, Ex: Ms Word, Excel, Power Point,
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.
The purpose of an operating system is to provide an environment in which a user can execute
programs in convenient and efficient manner.
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.
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.
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.
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.
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.
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:
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 −
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.
a) Directory 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 :
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
Windows XP 2001
Elements of Windows OS
Following are the significant element of Windows Operating System (WOS) −
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.
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.
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.
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.
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.
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.
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.
6. DOS does not share time. While window can share time.
DOS operating system is less preferred than While windows are more preferred by
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
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
It has graphical user interface along with It only has command line
Different version of Linux are Ubuntu, Linux Different version of Unix are
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,
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.
There have been many programming language some of them are listed below:
C Python C++
C# R Ruby
Matlab F F#
TCL D CPL
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
Impact of Virus
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.
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.
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.
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.
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.
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 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.
o Internetworking: An internetworking is the main responsibility of the network layer. It provides a logical
connection between different devices.
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 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 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.
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.
TCP/IP model
Here, hierarchical means that each upper-layer protocol is supported by two or more lower-level protocols.
Internet Layer
IP Protocol: IP protocol is used in this layer, and it is the most significant part of the entire TCP/IP suite.
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
ICMP Protocol
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.
Application Layer
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): 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 popular protocols act as co-functioning protocols associated with these primary protocols for core
functioning. These are:
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.
A computer network can be categorized by their size. A computer network is mainly of four types:
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.
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.
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".
Ring Topology
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.
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.
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.
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.
Reliable: The mesh topology networks are very reliable as if any link breakdown will not affect the
communication between connected computers.
Easier Reconfiguration: Adding new devices would not disrupt the communication between other devices.
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.
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.
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.
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.
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.
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.
Instant communications
Most inexpensive mail services, 24-hours a day and seven days a week
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.
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
(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
Quit.
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)
Quit.
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.
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.
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:
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.
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-
ALGORITHM
Characteristics of algorithm
Examples
Write an algorithm to add numbers.
Step1-Read the numbers x,y
Step2-sum=x+y
Step3-print sum
Step-4-end
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
Characteristics of an Algorithm
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).
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.
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 condition
then process1/statement1
Else
Process2/statement 2
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 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 :
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 5: end
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.
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:
In Pseudocode, they are used to indicate common input-output and processing operations. They
are written fully in uppercase.
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 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
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.
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.
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.
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 and output symbols show where and how data is coming in and out throughout your
process.
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
Flowchart
Q2. Find the sum of 5 numbers
Flowchart
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
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.
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.
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.
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
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.
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.
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.
In the C language, we break the program into parts using functions. It makes the program
easier to understand and modify.
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.
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.
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.
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
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 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.
Linux: For Linux, gcc comes bundled with the linux, Code Blocks can also be used with Linux.
Flow of C Program
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.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
1) C const keyword
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:
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. }
2) C #define preprocessor
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
6. String Constants
Constant Definition in C
Syntax:
Example:
#include<stdio.h>
main()
int area;
area = SIDE*SIDE;
, SIDE, area);
}
Program Output:
or
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
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.
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:
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:
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:
\a beep sound
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ 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"
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
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;
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
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
3. Variable Assignment
Variable Definition in C
Syntax:
type variable_name;
or
char letter='A';
double d;
age = 26.5;
Variable Assignment
Variable assignment is a process of assigning a value to a variable.
Example:
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.
#include<stdio.h>
void main()
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.
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.
float 4 byte
double 8 byte
Basic types
Here's a table containing commonly used types in C programming for quick access.
char 1 %c
float 4 %f
double 8 %lf
signed char 1 %c
unsigned char 1 %c
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;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -
2147483648 to 2147483647.
float salary;
double price;
Keyword char is used for declaring character type variables. For example,
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.
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;
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.
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.
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.
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.
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).
Additive +- Left to
right
Shift << >> Left to
right
Equality == != Left to
right
Bitwise OR | Left to
right
Logical OR || Left to
right
Conditional ?: 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
#include <stdio.h>
void main()
Program Output:
i--
Operator Description
++ Increment
−− Decrement
void main()
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
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)
Bitwise Operators
C provides a special operator for bit operation between two variables.
Operator Description
| 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
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
* Pointer to a variable.
#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.
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:
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
The type conversion performed by the programmer by posing the data type of the expression
of specific type is known as explicit type conversion.
(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:
int main()
{
double x = 1.2;
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
#include <stdio.h>
main ()
int a;
a = 15/6;
printf("%d",a);
Program Output:
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
Step4: end
Set sum=a+b
Print sum
end
start
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
Else
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.
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
#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
#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:
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.
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.
#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
#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;
default: statement 1;
statement 2;
...........
statement n;
}
All the expressions should have a result of an integer value or the character value.
#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
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:
The specified condition determines whether to execute the loop body or not.
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;
}
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.
#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.
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.
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 (;)
#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.
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:
#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.
In C, the for loop can have multiple expressions separated by commas in each part.
For example:
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
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
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
Return a;
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.
Types of Functions
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.
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.
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 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
The sum is 34
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
The sum is 34
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
The sum is 34
Output
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
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.
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.
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
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.
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
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
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
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:
int sum;
int main ()
b = 20;
sum = a + b;
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.
the C Variable.
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:
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:
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:
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:
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.
... .. ...
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;
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
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.
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.
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
Example:
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:
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.
{
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:
{return (n*fact2(n-1));}
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.)
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.
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
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.
Example:
int a[100];
Initializing an Array
int arr[5] = {10,20,30,40,50};
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.
{
int i;
for (i=0;i<5;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
Multidimensional arrays is nothing just an array of arrays. We can declare a multidimensional array, as below:
<data-type> <array_name>[size][size2][size3]…
#include<stdio.h> int
main()
int i,j;
for (j=0;j<2;j++)
// Accessing variables
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.
1. char s[5];
2.
Output
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.
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.
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.
<data_type> *pointer_name;
data_type specifies the type of pointer, then asterisk (*) followed by the pointer name.
Example:
int *ptr;
#include <stdio.h>
int main()
{
int *ptr; int
var1; var1 =
20;
ptr = &var1;
printf("%d", *ptr);
return 0;
Output:
20
Pointer Expressions
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.
64-bit
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
Output
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:
64-bit
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
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
32-bit
64-bit
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
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:
32-bit
64-bit
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
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.
1. Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points
Output
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.
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
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
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.
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:
structure_member;
...
instance_1,instance_2 instance_n;
Declaring the structure variable after you define the structure:
Structure name as struct_name can be later used to declare structure variables of its type in a program.
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();
gets(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.
2. {
3. char name[50];
int price;
4.
};
5.
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.
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.
12. {
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.
Output
Salary = 0.0