BasicC Notes
BasicC Notes
BasicC Notes
PART -A
UNIT – I : INTRODUCING COMPUTER SYSTEMS
Computer is an electronic data processing machine which accepts and stores large volume of data in the form of
binary digits, and processes them at a high speed as per the instructions of a stored program and produces the result
as output with pre-selected degree of accuracy. The term computer is derived from the latin word which means to
calculate or to manipulate.
In the above definition, data are the recorded facts and figures, concepts or discrete information as well as
instructions and commands too. A program is a finite set of instructions given to the computer in a precise notation
in order to solve the given problem. Instructions for computer, in a precise notation can be developed using high
level languages such as C, C++, java, etc.
They are used in large organizations such as insurance companies and banks, where many people frequently
need to use the same data. In a traditional environment, each user accesses the mainframe computer using a
device called a terminal. There are two types of terminal. A dumb terminal doesnot process or store the
data; it is simply an input/output device that function as a windows into a computer located somewhere lese.
An Intelligent terminal can perform some processing operations, but it usually does not have storage.
Mainframes are large, powerful systems that can handle the processing needs of thousands of users at any
given moment. But they lack flexibility. They are designed to perform only a specific set of tasks.
3. Mini computers
First released in 1960s, the minicomputers got their name because of their small size to other computers of
that age. The capabilities of the mini computers are between those of mainframes and PCs. They can handle
much more input and output than PCs.
4. Super computers
These are the most powerful computers and physically largest. They can process huge amounts of data and
the fastest super computers can perform trillion instructions per second. Some supercomputers can have
thousands of processors. They are ideal for handling large and highly complex problems that require
extreme calculating power. For example, weather forecasting and modeling nuclear fission, etc.
Capabilities of a Computer
Computer being an electronic machine, is capable of doing arithmetic calculations at electronic speeds. Few
milliseconds are sufficient for the computer to process a series of instructions. Computer has the following
capabilities.
1. Input / Output : The computer can accept the data and instructions into the machine from the outside world
and displays the computed result to the user.
2. Huge storage: A computer can store huge amount of data and instructions in its memory and it can store it
in temporary or permanent basis. It has storage capability to store the input data, the intermediate results
and final output information.
3. Processing: Computer has both arithmetic computational power and logical decision making.
Input devices
The devices that are used to feed data and instructions are known as Input devices. Examples for input
devices are keyboard, mouse, scanners, light pen, digitizers, track ball, microphone, etc.
Output devices
The devices that are used to get the desired output are known as Output devices and examples are monitor,
printers, plotters, speakers, etc
Central Processing Unit
It is sometimes referred to as brain of the computer. It is the part of the computer that contains electronic
circuitry and actually process the data. CPU also controls the flow of data through the system, directing the data to
enter the system, placing data in the memory and retrieving them when needed, and directing the output of
information.
The CPU consists of
1) Arithmetic and Logic Unit (ALU) and
2) Control unit
ALU: Arithmetic and Logic unit performs all arithmetic calculations and takes logical decisions. It operates on the
data available in the main memory and sends data back to the memory after processing it.
Control Unit : The control unit directs all the operations inside the computer. It contains the necessary electronic
circuits to control and co-ordinate all the activities among different units such as ALU, Memory, Input output unit,
etc.
Control unit is mainly concerned with the establishment of systematic timing and control over the
instruction execution and concerned operations. In fact, control unit analyses each instruction in the program and
sends relevant timing and control signals to all other units that are contributing to the work of instruction execution.
The control unit performs the following functions
1. It can get instructions out of the memory unit
2. It can decode the instructions
3. It sets up the routing through the internal wiring of data to the correct place at the correct time
4. It can determine the storage from where it is to get the next instruction after the previous
instruction has been executed.
5. It can transfer data between ALU & Memory and Input devices and Memory.
Microprocessor is a chip containing ALU and Control unit. The performance of microprocessor mainly depends on
Data bus ( the interface connecting the memory unit and processor) and Clock frequency of the computer.
Clock frequency: When an instruction gets executed inside a processor, thousands of components are at work. All
these varied components need to perform their respective operations at the proper time in the proper sequence. This
timing is maintained by a crystal oscillator clock connected to the processor. This crystal clock operates at a
particular frequency. This is called clock frequency of the processor. It is measured in MHz or GHz. Typical clock
frequencies are as follows:
Pentium processors - 300 MHz
Pentium III - 450 MHz – 1GHz
Pentium IV - 1 GHz – 3 GHz and above
Memory
Memory unit stores the program of instructions to be executed, the input data to be processed, the intermediate
results obtained during the program execution and also the final results or the output of the computations. It
basically consists of storage cells or memory cells. There are two types viz. Primary (electronic) memory and
Secondary memory.
Primary Memory
It is also called internal memory or main memory of the computer. It operated at electronic speeds. It holds
the data and processing instructions of programs only during their execution. It is made out of large number of semi
conducting materials. It is considered as fast memory whose contents can be accessed in short amount of time. But
it is a costly memory and hence capacity is less. Examples of primary memory are
RAM (Random Access memory):
In this type of memory, when the computer is turned off, the information stored is lost.
ROM (Read Only Memory):
In this type of memory the information are stored only once and they will not be erased even computer is
turned off. So this memory is also known as permanent memory. In this memory BIOS (basic input and output
system) instructions are stored which are needed when computer is switched on.
Secondary Memory
When large amount of storage is required at considerably cheaper cost, then auxiliary or secondary memory
is used. It is permanent memory which retains its content permanently until we erase it. Ex: Floppy disk, Hard disk,
CDROM, DVD, Magnetic tape, etc.
With the introduction of stored program concept, the operation of such computers is more or less automatic.
Because there will be little or no human intervention during program execution once after loading the data and
program.
Data refers to the recorded facts and figures: such as numbers, characters, pictures, numeric readings etc. Data by
themselves need not make much sense but when it is endowed with relevance it makes sense and called as
information.
4. Users
It is said that computer will not be a complete one without its authorized users. Therefore End users are also
part of the Complete Computer System.
PROCESSING
INPUT OUTPUT
STORAGE
1. Input
The cycle begins with accepting data from the input devices such as keyboard, input file or program file etc. for
its subsequent processing
2. Processing
In this stage, CPU in association with the main memory carry out necessary actions on the input data using the
stored programs or specified programs to produce the desired output.
3. Output
In this third stage, the processes result from the previous stage is displayed to the user using proper output
devices such as monitor, printer, etc.
4. Storage
The final stage of the cycle directs the computer to store the results of computations on secondary storage
devices such as hard disk, CDs, Floppy Disks.
When a key is pressed, the corresponding key switch is activated. The keyboard electronic circuit makes use of
"matrix scanning" technique in order to determine which key has been pressed. Then a standard 8-bit binary code
(called as scan code) is generated for corresponding key and another code is also generated which is the ASCII code
and it is send as the second byte. So for every key depression, two bytes of code are generated. The first byte
contains the unique scan code and second byte has the equivalent ASCII code of the character. But for the special
keys such as arrow keys, Home, End, Page Down, Ctrl etc the ASCII code is zero's only.
The keyboard control electronic circuitry not only just senses the pressed key but it also keep track that when the
operator or user releases the key, so that they can be identified very easily. Each separate key action is recorded by
the keyboard electronic circuit and sent to the computer as combination of unique scan and ASCII codes.
KEY SWITCHES
Keyboard
control and
encoder
electronic
circuit.
CPU
Mouse
The mouse is a hand held device connected to the computer by a small cable. As is the mouse is rolled
across the desktop, the cursor on the screen moves. When the cursor reaches the desired location, the user usually
pushes a button on the mouse once or twice to signal a menu selection or a command to a computer. There are
different varieties of mouse like two button mouse, three button mouse, scroll mouse, optical mouse, card less
mouse, etc.
The construction of a mechanical mouse consists of two rollers one for translating x movements and the other for
translating y movements. An electronic circuitry built in the mouse senses these movements of rollers and sends
them to the computer. A Tracker ball is placed underneath the mouse and as the mouse is moved over a flat surface,
the ball rotate and in turn the rotation of the ball is translated into x and y movements using the rollers.
A mouse consists of 2 or 3 buttons on its top-front. They are used to indicate mouse events such as clocking, double
clicking, dragging, right clicking etc.,
An optical mouse uses a LED to illuminate the flat surface on which it is placed and a light sensitive device senses
the light reflected from the surface, thus measuring the movement of the mouse in x and y directions.
Following operations can be performed by a mouse
1. Pointing, move the mouse pointer anywhere on the screen
2. Clicking, press the left mouse button once and release it
3. Double clicking, press twice the left mouse button in succession
4. Dragging, hold the left mouse button and move the mouse
5. Right clicking
Variants of Mouse
Mouse variants are the supplements to the mouse, that imitate the actions of a mouse. The primary benefits of these
devices is to offer ease-of-use and occupy lesser desk space for mouse movement operations. Trackball and
touchpad are the examples of mouse variants.
1. Trackball: It is like a mouse turned upside down. It provides the functionality of a mouse by simply
rotating the ball with the forefinger.
2. Touchpad: It is a touch sensitive tiny rectangular surface/pad, usually found in laptops. It also provides
the functionality of a mouse. With a finger tip, slide on the surface of the touchpad to move the pointer
on the screen. Touchpads may have buttons to perform clicking ooperations.
3. Pointers in Keyboard: Many portable computers provide a joy-stick like pointing device in the keyboard
at the centre, typically between G and H keys. So a pointer movement on the screen can be performed
with the help of these devices.
Modern PCs come with built-in multimedia capabilities. Using these features users can input the audio and video
data to the computer. There are several audio-visual input devices such as microphone, digital audio recorder,
MIDI, etc.
A microphone is a basic audio input device. It is used to record speech and convert the spoken input data into digital
data and can be stored in the computer. A sound card is used for digitizing the audio input and connecting a
microphone.
MIDI(Musical Instrument Digital Interface) allows variety of different musical instruments to connect to the
computer.
Video can be recorded and transferred to the computer using Web cams or Camcorders. Using a Video capture card,
it is possible to connect any other video devices such as VCRs, Digital Camcorders to a computer.
Output Devices
Hard copy output :
The data consisting of text or graphics that is obtained as printouts or microfilm using
printers or plotters is known as hardcopy. For example, the hardcopy of an engineering
drawing is obtained using plotters. Some hardcopy devices include dot matrix printer, laser
printer, inkjet printer , flatbed pen plotter and drum type inkjet plotter. A combination of
printing, scanning, copying and/or faxing can also obtain a hardcopy. A hardcopy can be
used for business correspondence and documentation. A copier machine also comes under
hardcopy devices.
Soft copy output:
The data that is stored in a storage device such as floppy disk, hard disk, CD-ROM
magnetic tape and so on is called softcopy. The data in a softcopy may be modified using
the relevant software. A few softcopy devices are monitor and floppy disk. The Monitor and
Data projectors are Soft copy output devices.
Monitors
Monitor is the most commonly used output device. Two important hardware devices determine the quality of the
image on the monitor. They are the monitor itself and the Video Controller or Video Card.
Two types of monitors are used with PCs. They CRT Monitors and Flat panel displays or LCD Monitors. All
monitors can be categorized by the way they display colors:
1. Monochrome Monitors: Display only one color against a contrasting background such as black. These
monitors are used for text only displays where the user does not need to see color graphics.
2. Gray scale monitors: display varying intensities of gray against a white or off-white background and are
essentially a type of monochrome monitors.
3. Color monitors: can display 16 colors to 16 million colors.
CRT Monitors:
A CRT monitor consists of phosphor coated screen at the front and an electron gun which can shoot a beam of
electrons through a magnetic coil(some times called yoke). The phosphor element will glow when it is striked by
an electron beam. The screen’s phosphor coting is organized into a grid of dots. The number of dots that a gun can
focus is called a pixel (Picture element). Each pixel has a unique address, which the computer uses top locate the
pixel and control its appearance. Some electron guns can focus pixels as small as a single phosphor dot.
Electron beam
Magnetic Yoke
Electron Gun
Actually, the electron gun does not just focus on a spot and shoot electrons at it. It systematically aims at every
pixel on the screen, starting at the top left corner and scanning to the right edge. Then it drops down a tiny distance
and scans another line. Like human reading the letters on a page, the electron beam follows each line of pixels
across the screen until it reaches the bottom of the screen. Then it starts over again. As the electron guns scans, the
circuitry driving the monitor adjusts the intensity of each beam. In a monochrome monitor, the beam’s intensity
determines whether a pixel is on or off. In the case of a gray scale monitor, the beam’s intensity determines how
brightly each pixel should glow.
A color monitor works like a monochrome monitor except that there are three electron beams representing three
colors Red, Green and Blue. In a color monitor, each pixel includes three phosphors –red, green and blue – arranged
as a triangle. When the beams of each of these guns are combined and focused on a pixel, the phosphors lights up
and glows in a particular color.
CRT monitors have long been the standard for use with desktop computers because they provide a bright, clear
picture at a relatively low cost. There are two major disadvantages of CRT monitors. They are
1. CRT monitors are big and take up more desk space can be difficult to move.
2. CRT monitors require a lot of power to run
Comparing Monitors:
Following specifications are used for comparing monitors:
1. Size
Monitors are measured diagonally, in inches, across the front of the screen. A 17” monitor measures 17
inches from the lower left corner to the upper right corner.
2. Resolution
It refers to the sharpness or clarity of an image. A monitor’s resolution is determined by the number of
pixels on the screen. The more pixels a monitor can display, the higher is its resolution and the clearer its
images. For ex: 640 x 480 resolution is less clearer than 800 x 600 resolution. Other resolutions supported
by monitor are 1024 x 768, 1152 x 864 and 1280 x 1024.
3. Refresh rate
It is the number of times per second that the electron guns scan every pixel on the screen. It is important
because phosphor dots fade quickly after the electron gun charges them with electrons. If the screen is not
refreshed often enough, it appears to flicker, and flicker is one of the main causes of eye strain. Refresh rate
is measured in Hertz. The high refresh rate typically of the order of 85Hz and more avoids eye strain.
4. Dot Pitch
It is the distance between the like colored phosphor dots of adjacent pixels. Dot pitch is measured as a
fraction of millimeter. Typically it is of the order 0.15 mm to 0.40 mm or higher. Smaller the dot pitch, the
finer and more detailed images will appear on the monitor.
Video Cards:
The quality of the images that a monitor can display is defined also by the video card or video adapter. The video
card is an intermediate device between the CPU and the monitor. It contains the video dedicated memory and other
circuitry necessary to send information to the monitor for display on the screen. It is separate device that can be
plugged to the mother board of the computer in a slot called PCI slot. In new computers, the video card is in built in
the mother board.
Video Controllers also feature their own built in video RAM or VRM. VRAM is dual ported, meaning that it can
send a screen full of data to the monitor and at the same time receive the next screen full of data from the CPU.
Today’s video cards may have up to 256 MB of VRAM,
Data Projectors
A data projector plugs into one of the computer’s ports and then projects the video output onto an external surface.
Most projectors use LCD technology to create images. LCD projectors require the room to be darkened. They
display blurry images in less than optimal lighting conditions. Newer model use Digital Light Processing(DLP)
technology to project brighter, crisper images. DLP devices use a special microchip called a digital micro mirror
device, which actually uses mirrors to control the image display. DLP projectors can display clear images in normal
lighting conditions.
Sound Systems
Microphones and Speakers are the common devices used in PCs to record and produce sound. The speakers used in
computers are smaller and may contain their own amplifiers. They transfer a constantly changing electric current to
a magnet which pushes the speaker cone back and forth. The moving speaker cone creates pressure vibrations in the
air which is a sound.
Sound Card : A sound card is a circuit board that converts sound from analog to digital and vice versa. A sound
card actually has both input and output functions.
Printers
A printer is an output device. Whenever a hardcopy or paper copy of output is required then printer can be used to
print them on sheet of paper.
Printer is connected to a computer via a 32 pin flat ribbon that carries signals from computer to printer and vice-
versa. Through this connection computer sends control commands and data to be printed on the paper. In response
to the commands issued by computer, the printer also sends its response indicating whether it is already busy with
printing. Sometimes printer may have to inform its status like busy or free any error condition sensed or at last
while printing if paper is exhausted etc to the computer.
Characteristics of printers
1. Speed :The speed of the printer is a measure of number characters / line printed per unit time. It is measured
in CPS (Characters Per Second) or LPM (Lines Per Minute).
2. Quality : The quality of output is associated with the shape of characters. The commonly used qualities are
Draft quality, Near letter quality or Letter Quality. The quality of printing is usually measured in DPI (dots
per inch). the more dots per inch a printer can produce, the higher its image quality. For example, most
medium quality inkjet and laser printers can print at 300 or 600 dpi.
3. Memory: Printer’s memory is a temporary memory. It is also called as the print buffer. It varies from 1 kb
to Several MB like 16 MM or 32MB
4. Cost of Operation : The cost of ink or toner and maintenance varies with the type of printer. An inkjet
printing cost around Rs. 2.00 per page whereas Dot Matrix printing costs just 15 paise per page.
5. Initial cost: The cost of new printers has fallen dramatically in the recent years. An inkjet printer can be
obtained just for Rs. 2,000.00 whereas a laser printer starts from Rs. 8,000.00. Color printers always cost
more than black and white printers and this is especially true for laser printers.
6. Type: Based on the printing mechanism, printers are classified as impact printers and non-impact printers.
Different kinds of printer are available in the market with varying print mechanism, speed in number of characters
printed per second, and quality of printing. Some examples of printers are dot matrix printers, line printers, daisy
wheel printers, laser printers, thermal printers, inkjet printers, drum printers, band printers etc.
The printers are classified in two categories a) impact printers and b) non-impact printers.
Impact Printers
An impact printer makes contact with the paper. It usually forms the print image by pressing an inked ribbon against
the paper with a hammer like mechanism. In impact printers the printing assembly is an electromechanical device
which does the impacts on the ribbon. So, a large amount of noise is generated and process is very slow. Examples:
dot matrix printers, line printers, chain printer (band printers) etc.
Dot matrix printers
Dot matrix printers are one of the most popular serial printers used in all general purpose printing applications. In
dot matrix printer, the character is formed by a set of small dots arranged in matrix form normally a matrix pattern
of 9 rows and 7 columns are used to create the character pattern of dots. Characters to be printed are sent one
character at a time from the memory to the printer. The character code is decoded by the printer electronic circuit
and activates the appropriate pins in the print head. These pins are moved to form a character and they hit the
carbon ribbon in front of the paper there by printing that character. Many dot matrix printers are bi-directional i.e.
they print from right to left on return. This speeds up printing. The speed of dot matrix printers ranges from 30 to
300 cps (character per second). The advantage dot matrix printer is the possibility of converting them to print
alphabets other than English. Dot matrix printers are less expensive as compared with line printers they cannot be
used continuously for more than an hour or so and are thus called “light duty” printers.
Line printers
The line printers, prints one full line of characters at a time, advances the line and then prints next line and so on. So
the printing speed is very fast in line printers.
The speed of printing for line printers is specified as lines per minute (l.p.s.). Speed of line printers varies from 300
lpm to 2000 lpm whereas the fastest serial printer (character printer or commonly known as dot matrix printers)
could print only about 60 cps. But the main disadvantage of line printers is that the quality of printing is very poor.
Line printers are used for producing thousands number of reports, results in massive data processing applications.
Whenever there is heavy printing of bulk amount of data, intermediate results, census data etc, where quality of
printing is of less importance then the line printers are used.
There are two types in line printers : 1) Drum printers 2) Chain printers (band printers)
Drum printers
A drum printer consists of a cylindrical drum. The characters to be printed are embossed on its surface. One
complete set of characters is embossed for each and every print position on a line. Thus a printer with 132
characters per line and a 96 characters will have on its surface 132 X 96 = 12692 characters. The printer drum
rotated at a high speed. A set of print hammers, one for each character in a line, are mounted in front of the drum. A
carbon ribbon and paper are interposed between the hammer and the drum. As the drum rotates, the hammer waits
and is activated when the character to be printed at that position appears in front of the hammer. So in one
revolution of the drum, a line is printed. Printer drums are very expensive and cannot be changed often. So the drum
printers have a fixed font.
NON-IMPACT PRINTERS
In non-impact printers, the printing is done by spraying the ink on paper or with the help of electrostatic charges
generated in the paper. So there is very less amount of noise or sometimes no noise at all and printing is very fast.
Ex: Inkjet printers and laser printers.
Inkjet Printers
These are the non-impact type of printers. They use ink filled cartridges and tiny nozzles to spray ink onto
the paper in a series of dots that make the characters and graphics. A print head scans the paper left to right and
back as the paper rolls in vertical steps. Colour inkjet printers are also available. The speed of inkjet printers will be
usually referred in pages per minuter (PPM). The quality of prints will be specified in dpi(dots per inch). Though
the inkjet printer can print on ordinary papers, its printing quality increases with good quality paper. The cost of
inkjet printers were now drastically reduced and are being used in the home segment.
Laser printers
The basic limitations of line and serial printers are the need for a head to move and impinge on a ribbon to print
characters. This mechanical movement is relatively slow due to the high inertia of mechanical elements. These
disadvantages are eliminated in the new laser technology based printers known as “laser printer”.
Laser printers are fastest type of non impact electrostatic printers. They produce high quality prints at high speeds.
It operates like a copier machine. In these printers, the controlled beam of intense laser forms images on an
electrically charged rotating drum. The drum is rotated near the fine black powder called the toner. These charged
images which sticks to the paper due to pressure and heat. The toner consists of oppositely charged ink particles
which stick to the drum in the places where the laser has charged.
The light beam strikes a multi-sided rotating mirror. As the mirror rotates, the side currently in the path of the light
beam sweeps the beam across the surface of the drum. As the beam sweeps across the drum, the light is modulated
and a single line is drawn after a line has been drawn, the next side of the mirror is in place and a new line is drawn
below the previous line.
The quality of the printout is measured by the number of dots per inch (dpi). Since the dots are printed closely, the
text or graphics appears very smooth and elegant. The speed is measured in number of pages printed per minute
(PPM) which varies between 5 and 25.
The advantage of laser printers in that it prints excellent graphics output. At present high-resolution laser printer
prints 1200 dots per inch. The speed of printing is also considerably greater than other printers i.e. 10,000 lines per
minute. But the disadvantage of laser printer is that it is very expensive.
Plotters:
It is another type of output device used to produce graphical output. They are employed for plotting graphs,
charts and other designs on paper. The plotter draws the picture on the paper with a pen. Colored pens are also used
with plotter to draw the coloured drawings. There are two types of plotters viz. flat bed plotter and drum plotter.
The flat bed plotter has flat bed over which the paper is laid flat. An arm carrying a pen is moves parallel to
the width of the flat bed and can reciprocate along the length of the plotter bed. Thus the pen is given x-y
movement. While drawing a drawing, the pen holder can select the pens of different colours. These plotters can
draw the drawings with greater accuracy since the paper remains stationery. The limitation of these plotters is that
they can accept only smaller sized papers.
The drum plotter can draw picture of larger size. In this case the paper as well as the pen will have the
movement, while drawing. The pen moves across the width of the paper whereas the paper rolls over the drum.
UNIT – II
PROCESSING DATA
Difference between Data and Information:
Data Information
1. Data is collection of facts and figures. 1. Information is the result of processing of data.
2. Data is unstructured, lacks context, and may not 2. Data endowed with context is called information.
be relevant to the recipient It is organized, processed and filtered data.
3. Taken individually, data does not have any 3. Grouped data i.e. information convey specific
meaning meaning
4. The letters, digits and symbols represent data 4. The program obtained from letters, digits and
symbols represent information
Computers like clocks, have their own numbering system, called the binary number system. To
computers, everything is numbers. Letters, punctuation marks, sounds, pictures, etc are all represented as
numbers in computers. Even the computer’s own instructions are also numbers.
In computer, all data is represented by the state of the computer’s electronic switches. A switch has only
two possible states – on and off , so it can represent only two numeric values. To a computer, when is
switch is off, it represents 0 and when it is on, it represents 1. Because there are only two values,
computers are said to function in base 2, which is known as the binary number system.
Text Codes
There are four standard code for representing text in computers. They are
1) EBCDIC : stands for Extended Binary Coded Decimal Interchange Code. It is an 8 bit code that
defines 256 symbols. It is still used in IBM mainframe and midrange systems.
2) ASCII: stands for American Standard Code for Information Interchange. It is an 8 bit code that
specifies the characters from 0 to 127.
3) Extended ASCII: It is an 8 bit code that specifies the characters for values from 0 to 255. The first
40 symbols represent pronunciation and special punctuations. The remaining symbols are graphic
symbols.
4) Unicode: It provides upto 4 bytes – 32 bits to represent each character. It can represent 4 billion
different characters or symbols. The first 256 characters are identical to the ASCII & Extended
ASCII codes.
How Computers Process Data
Two components handle processing in computer: CPU and the memory. Both are located in the
motherboard of the computer.
CPU:
The CPU is the brain of the computer, the place where the data is manipulated. It consists of two basic
parts: Control unit and ALU.
Control Unit : All the computer’s resources are managed from the control unit. It is the logical hub
of the computer. The CPU’s instructions for carrying out commands are built into the control unit. The
instructions or instruction set, lists all the operations that the CPU can perform. Each instruction in the
instruction set is expressed in microcode, a series of basic directions that tell the CPU how to execute
more complex operations.
ALU: It is responsible for carrying out all Arithmetic and logical calculations in a computer. When a
control unit encounters an instruction that involves arithmetic or logic, it passes that instruction to the
ALU. The ALU includes a group of registers – high speed memory locations built directly into the CPU
that are used to hold data currently being processed. The ALU will use
Control Unitthe register to hold the data
currently being used for calculations. Instruction 1
Instruction 2
RAM System Bus
Instruction 3
Each time the CPU executes an instruction, it takes a series of steps. The completed series of steps of is
called a machine cycle. A machine cycle can be broken down into two smaller cycles: instruction cycle
and execution cycle. At the beginning of the machine cycle, the CPU takes two steps:
1. Fetching : Before the CPU can execute an instruction, the control unit must retrieve a command or
data from the computer’s memory.
2. Decoding : Before a command can be executed, the control unit must break down(decode) the
command into instructions that correspond to those in the CPU’s instruction set.
At this point, the CPU is ready to begin the execution cycle.
3. Executing: When the command is executed, the CPU carries out the instructions in order by
converting them into microcodes.
4. Storing: The CPU may be required to store the results of an instruction in memory.
Although the process is complex, the computer can accomplish it at an incredible speed, translating
millions of instructions every second. In fact, the performance of CPU is often measured in Million
Instructions Per Second(MIPS).
Memory:
The CPU contains the basic instructions needed to operate the computer, but it cannot store entire
programs or large set of data permanently. The CPU needs to have millions of bytes of space where it can
quickly read or write programs and data while they are being used. This area is called memory and it
consists of chips either on the motherboard or on a small circuit boards attached to the motherboard. This
electronic memory allows the CPU to store and retrieve data quickly.
There are two types of memory : Permanent and nonpermanent. Some memory chips retain the data they
hold, even when the computer is turned off. This type of memory is called non-volatile memory. Volatile
memory loses its contents when computer’s power is off.
Non-Volatile Memory(ROM) :
They hold the data even when the computer is unplugged. During normal use data in these chips is
read-only and not changed. So the memory is called Read Only Memory. Specifically they Programmable
ROM(PROM). PROM chips are often found on hard drisks and printers. They contain the instructions that
power the devices. These instructions once set, never need to be changed.
When a computer is turned on, it must know how to start. ROM contains a set of start up
instructions called BIOS(Basic Input Output System). BIOS also contains another set of routines which
ensure that the system is functioning properly and all expected hardware devices are present. This routine
is called POST (Power On Self Test).
Flash Memory:
It is a special type of non-volatile memory. It is often used in portable digital devices for storage.
Digital Cameras, USB thumb drives and game consoles all use flash memory. It works by having switches
store the binary values that make up the data.
changes. The computer uses these vibrations to time its processing operations. The first PC operated
with 4.77 MHz. The computer’s operating speed is tied with the system clock. A clock cycle is single
tick, or the time it takes to turn a transistor off and back on again. A processor can execute an
instruction in a given number of clock cycles. As the system’s clock speed increases, so does the
number of instructions it can carry out each second. For example Pentium IV with 3.0GHz are now a
days common.
4. Bus Speed
A bus is a path between the components of a computer. There are two main buses in a computer: the
internal ( or system) bus and external ( or expansion) bus. The system bus resides on the motherboard
and connects the CPU to other devices that reside on the motherboard. An expansion bus connects
external devices such as keyboard, mouse, modem, printer, etc. The system bus has two parts : Data
bus and Address bus.
The Data bus is an electrical path that connects the CPU, memory and other hardware devices on the
motherboard. The number of wires in the bus affects the speed at which the data can travel between
hardware components. Because each wire can transfer one bit of data at a time, an eight-wire bus can
transfer one byte per second. Newer models of computers have 64 bit data bus called Front Side
Bus(FSB). Like the processor, bus speed is also measured in MHz because it has its own clock speed.
For example 100MHz bus speed in older PCs and 800Mhz bus in newer PCs.
The Address bus is a set of wires similar to the data bus but it connects only the CPU and memory and
carries only memory addresses.
5. Cache Memory
Moving data between RAM and CPU’s registers is one of the most time consuming operations a CPU
must perform because RAM is much slower than CPU. A partial solution to this problem is to include
a cache memory in the CPU. Cache memory is similar to RAM but is extremely fast and placed
between CPU and memory. The CPU resident cache memory is called Level 1 (L1 cache). The cache
memory in the motherboard is called L2 cache. The cache memory is faster for the CPU to access,
resulting in a quicker program execution.
Microcomputer Processors
The performance of a processor is determined by the internal design or architecture of the processor.
Various processors used in the computers are as follows:
1. Intel processors
Intel is the first company who invented microprocessors. Intel processors are widely used in almost all
IBM compatible computers. For ex:
Celeron - 500 MHz - 28 to 44 million transistors used.
P3 - 650MHz+ - 28 to 44 million
P4 - 1.4GHz+ - 42 to 55 million
Itanium 2 - 1.3 GHz+ - 410 million
2. AMD (Advanced Micro Devices) Processors
Duron - 600 MHz+ - 25 million
Athlon - 1.0 GHz+ - 37 million
Athlon XP - 2.2 GHz+ - 54.3 million
3. Free scale processors
These are processors from Motorola. They are used by Apple Macintosh computers.
4. IBM processors
Expansion Slots
In addition to the standard collections of ports, many PCs include specialized ports. These ports allow the
connection of special devices, which extend the computer’s bus in unique ways.
SCSI:
The Small Computer System Interface takes a different approach from standard parallel or serial
ports. The SCSI adapter extends the bus outside the computer by way of a cable. Many device use the
SCSI interface. Fast, high end hard disk drives often have SCSI interfaces. Scanners, tape drives and CD-
ROMs can also use SCSI interface.
USB:
The Universal Serial Bus has become the most popular external connection for PCs. USB is hot
swappable bus meaning that users can switch USB devices without rebooting the PC. Simply plugging the
device to the computer through USB makes the device ready to use.
IEEE 1394 (Firewire):
Firewire standard extends the computer’s bus to many peripheral devices through a single port.
Because its technology is so expensive, it is not a dominant bus technology. It is used as standard for
plugging video and other high data throughput devices to the system bus.
MIDI:
The Musical Instrument Digital Interface allows the group of electronic musical instruments to
communicate. Many sound cards are MIDI complaint and feature a MIDI port. Using a MIDI port, wide
variety of musical instrument and other MIDI-controlled devices can be connected to a PC. MIDI systems
are widely used in recording and performing music to control setting for electronic synthesizers, drum
machines, light systems, amplification and more.
STORAGE DEVICES
The purpose of a storage device is to hold data even when the computer is turned off, so the data can be
used whenever it is needed. Storage involves two processes.:
• Writing or recording, the data so it can be found later for use.
• Reading the stored data , then transferring it into the computer’s memory
The physical material on which data is stored is called storage media. The hardware components that write
data to, and read data from storage media are called storage devices.
The main categories of storage technology are
1. Magnetic storage ex: Floppy disk, hard disk, etc
2. Optical storage ex: CD-ROM, DVD, etc
3. Solid state storage ex: Flash memory, memory stick etc
During reading, no current flows through the read/write head. But the storage medium has
magnetic spots representing the data. The data in the form of magnetic spots can be read from storage
devices as follows: Whenever the data has to be read, the CPU instructs the read/write head to move over
the disk. As the head moves over the disk surface, the magnetic spots in the media charges the magnet in
the head producing variations in current. These electrical variations are transferred to the CPU. A high
current represent bit 1 and low current represents bit 0. Thus the data in the form of magnetic spots are
converted into electrical pulses and are transferred to the CPU. The processor then reads these pulses and
identifies them as data bits zero or one.
to innermost starting from zero. Outermost tracks are longer than the inner tracks. After tracks are created,
they are divided into sectors. Sectors are the smallest units with which any magnetic disk drive can work.
The drive can read or write only whole sectors at a time. If the computer needs to change just one byte out
of 512, it must rewrite the entire sector.
If a diskette has 80 tracks on each side, and each track contains 18 sectors, then the disk has 1440 sectors
per side. Regardless of physical size, all sectors hold the same number of bytes. If sector size is 512 bytes,
SECTOR TRACK
KS
R/W
head
2. FAT : It is a log that records the location of each file and the status of each sector. When a
program needs to write to or read data from a disk, it checks the FAT to see where that location
is. During formatting two copies of the FAT are created, both are always maintained to keep
their information current.
3. Root Folder: It is the master folder on any disk. A folder is a tool for organizing files on a disk.
The folder can contain files and subfolders in it. The topmost folder is called the root folder. It
holds all the information about other folders in the disk.
4. Data area: It is the part of the disk that remains free after the boot sector, the FAT and the root
folder have been created. This is where the data and program files are actually stored on the
disk.
During logical formatting, the OS also groups sector together, into storage units called clusters. A cluster
is simply a group of sectors that the OS see as a single unit. It is the smallest space a OS can allocate for a
single file. Cluster size vary depending on the size of disk and type of disk but they can range from four
sectors to 64 sectors.
Floppy Diskettes
Floppy disks were invented by IBM as a means of loading programs into a computer. It is a storage
media consisting of a thin flexible circular plastic material coated with a magnetic material and enclosed
in a rigid rectangular plastic case. They were useful to transfer the data between computers and store data.
When the disk is placed in a disk drive, the data are recorded magnetically on one or both sides of
the disk surface. The data is stored in the form of magnetic spots. The presence of a magnetic spot
represents a binary value 1 and the absence of it represents binary value 0. Floppy disks spin at about 300
revolutions per minute.
The various parts of the floppy disk are:
1. Circular plastic coated magnetic material: It is the medium on which the data is recorded in the
floppy disk.
2. Central Hub: When the floppy disk is inserted into the drive unit, the hub fits over the spindle and
the record medium
3. Circular metal disk at the center: It is used to rotate the disk.
4. Read/Write Access Door: Used to allow the read/write mechanism to access the data.
5. Index hole : used as a reference and used to count the number of sectors on the disk.
6. Write protect notch: If this hole is closed, the floppy is write protected.
7. High density hole : indicates high density disk is used.
The floppy disks are very cheap and portable media for data transfer and storage. The disadvantages of the
floppy disks are they are prone physical damage very easily and relatively slow to access.
Hard Disk
The size of the floppy disk is limited. If the application requires more secondary memory, then
hard disks are used. A hard disk is a group of round metal plates which are coated with magnetic material.
A magnetic hard disk unit is an electromechanical assembly containing flat metal plates (disks) coated on
both sides with magnetic material. Many such disks are mounted on one spindle with r/w heads available
for both surfaces of all the disks. The disk assembly is mounted on a disk drive. The disk drive consists of
a motor to rotate the disk assembly at high speed of about 3600 to 10000 rpm. The speed at which the hard
disk spins determines the performance of the hard disk.
The r/w heads mounted on arm can move in and out radial on the disk surfaces for reading and
writing operation. Data is stored and read on the magnetic recording surface of the disks rotates at high
speed at about its axis.
Data bits 0’s and 1’s are stored in the magnetized recording surface of the disks along concentric circles
known as tracks. A track is furthur divided into sectors as shown in figure. The above figure shows the
organization of tracks and sectors in magnetic disk surface. Each sector is capable for storing 512 bytes of
information.
The magnetic disk assembly is connected to and controlled by an electronic circuit called as hard disk
controller (HDC). The disk controller when it receives the control signals for reading or writing operations
by the computer, it positions the r/w heads on the specified disk and at the specified track and sector.
There by r/w heads can either read or write when disks rotate at high speed.
Hard disks have high storage capability. The capacity of the hard disks now ranges from 10GB to even
200 GB and above. The data access rate is very fast. More reliable when compared to floppy disks. The
only disadvantage of the hard disks is that they are not portable.
Tape Drives
A magnetic tape is secondary storage device consisting of a thin tape coated with magnetic material. This
tape is used for recording both analog and digital data. It used the same principle as that used in audio-
cassettes. It is a sequential access device used for storing bulk data for back up purposes.
number of sectors of equal length. The data in the form of 1’s and 0’s is written into the disk in spiral
manner. Laser beam is used to burn the CDs forming pits and lands. A pit is hollow or depression caused
during burning and will not reflect light. The non-burnt area is called land and represent 1. Thus the data is
stored in the CDs as pits and lands.
• De-fragmenting a disk
The contents of the files will not be stored in contiguous memory locations on the disk. The pieces or
contents of the file will be scattered throughout the disk. So, data accessing is slower and hence
performance of the PC decreases. So, using disk de-fragmentation utilities, the contents of the files are
stored contiguously so the data accessing is faster.
• File compression
If there are larger files on the disks, they take up more space on the disk. So, it is not possible to store
more files on the disk. This problem can eliminated by disk compression or file compression utilities
which drastically decreases the size of files.
The OS performs the following functions. (a) Displays the onscreen elements with which you interact –
the user interface (b) Loads programs into memory (c) Coordinates with how program works with
hardware and other software (d) Manages the storage and retrieval.
Since it allocates memory, loads other software program to memory and removes it from memory after
execution so operating system is known as the link between the hardware and other software. Examples
for operating systems are : MS-DOS, PC-DOS, Novell-DOS, Windows 98, SCO-UNIX, OS/2 WARP,
SYSTEM-8, HP-UX, Sun Solaris etc.
Some older operating system like MS-DOS and some current versions of UNIX and LINUX
feature a command line interface which uses typewritten commands- rather than graphical objects. Users
interact with command line interface by typing strings of characters at a prompt on the screen.
Running Programs
The OS provides a consistent interface between application programs and the user. It is also the
interface between those programs and other computer resources such as memory, printer or other
programs. Programmers write computer programs with built-in instructions – called system calls – that
requests service from the operating system. The services provided by the OS include
>> listing files
>> saving the contents of the files to disk
>> reading the contents of a file from disk to memory
>> sending a document to printer and activating the printer
>> allocating RAM among the running programs
>> recognizing keystrokes and mouse clicks and displaying characters on the screen
Sharing Information
Many application shares certain data or data may be copied/moved from one file to another. The
clipboard is a temporary holding space for the data being copied or moved ( using cut, copy, paste
functions, object linking and embedding).
Managing Hardware
The OS is the intermediary between programs and hardware. In a network the OS mediates
between your computer and other devices on the network.
Processing Interrupts
The operating system uses Interrupt Requests (IRQs) from other devices to help CPU coordinate
processes or activities carried out by various devices.
PC OPERATING SYSTEMS
PC Operating systems are DOS, Windows 9x, Macintosh, Linux etc.
DOS
DOS stands for disk operating system. This uses command line interface, single user – single
tasking operating system. It supports 16 bit programs. IBM released PC-DOS and Microsoft released MS-
DOS for IBM compatible PCs or clones. DOS does not require much memory or storage space and it does
not require a powerful computer. Hence DOS was the popular OS during 1980s.
Windows NT Workstation
This was released in 1993 by Microsoft to replace DOS however it was too large to run on smaller
machines. Hence it was used only for powerful machines like mainframe or network servers. Windows
NT is a 32 bit OS.
Windows 9x
The Windows 9x is used for the threesome windows 95, windows 98 or windows Me. These are
widely used. In 1995, Windows 95 was released by Microsoft as a complete operating system that does
not require MS-DOS. More features were added and maintained Graphical User Interface (GUI). This
supported 32 bit applications.
Microsoft also came up with Windows 98 considered as an update of Windows 95 and then
Windows Me (Millennium edition) in 2000 which had many multimedia and internet features.
Windows XP
Released in 2001, it is the latest in the Windows suite of PC operating system families. The various
versions are Windows XP Home, Windows XP Media Center Edition, Windows XP Embedded. Microsoft
also created 64 bit Windows XP for use with AMD’s processors. Windows XP supports Digital Media
Support, Advanced networking and communications, and advanced Mobile computing.
COMPUTER NETWORKS
A computer network is defined as connecting different computers to share the data using various technologies such
as Hardware, Software and communication media. Computer network helps the user to communicate, exchange
information and share various devices that are connected to the network. When the data and programs are stored on
a network and are shared, individual users can substantially reduce the need for programs on their own computers.
Networks open up new ways to communicate, such as email and instant messaging. By allowing users to share
expensive hardware resources such as printers, networks reduce the cost of running an organization.
Uses of Networks
1. Simultaneous Access
When the data is stored in the central server called network server and number of users are connected to
them using networking concepts, the users can have simultaneous access to the server’s resources. A
network server can have number of programs loaded in it and can serve many networked computers at a
time. If the server stores data files for the user to access, it is commonly called a file server. In an
environment where PCs are not networked, a separate copy of each program must be installed on every
computer. This setup can be costly for two reasons. First, the software can be expensive. Second, installing
and configuring on many different computers can take a lot of time and labour and maintaining many
separate installations of a program is an ongoing process. With networking these problems can be solved by
installing a single copy of the program on the network server and individual users can run those programs
on the nodes.
2. Shared Peripheral Devices
The ability to share the peripheral devices is one of the best reasons for small businesses to set up a
network. When several people can share a printer on a network, printing becomes less expensive and easier
to manage. There are two common ways to share a printer. A printer can connect directly to the network or
it can be attached to a print server, which is a computer that manages one or more printers.
3. Personal Communications
Using networking, personal communication becomes easier. We can use email facilities, video
conferencing, audio conferencing or data conferencing facilities of the network. Even Voice Over Internet
Protocol(VoIP) can be used wherein the internet can be used as an alternative to telephone services.
4. Easier Data Back up
Since data is extremely important in the business, the users have to back up the data. This is done by simply
moving the files to the server in a common shared area in a computer network. Often the network manager
makes regular backups of the data on the shared storage device. Managers can also use special software to
back up files stored on employees hard drives from a central location.
3. Hybrid Networks
a. Campus Area Networks
A CAN follows the same principle as a LAN but only on a larger and diversified scale. With a CAN,
different campus offices and organizations can be linked together.
b. Metropolitan Area Networks
A MAN is a large scale network that connects multiple corporate LANs together. MANs are usually not
owned by a single organization. Their communication devices and equipments are usually maintained
by a group or single network provider.
c. Home Area Networks
A HAN is a network contained within a user’s home that connects a person’s digital devices, from
multiple computers and their peripheral devices such as printer, telephones, VCRs, DVDs, television,
video games, etc.
d. Intranets and extranets
Intranet is a company wide network and limits access to employees and selected contractors having on-
going business with the company. It uses the web server software for providing the services which is
similar to internet. An extranet is a partially accessible internal company website for authorized users
physically located outside the organization. Whereas an intranet resides completely within the
company’s internal network and is accessible only to the people that are members of the same company
or organization, an extranet provides various levels of accessibility to the users.
PC PC PC PC
Printer PC PC Scanner
Advantages
- Short cable length is sufficient, since all the nodes are connected to a common bus.
- Additional nodes can be connected at any required point on the length of the bus.
- It is simple in its architecture which makes it reliable from hardware point of view.
Disadvantages
- It is not centralized at any node. Hence the entire network has to be inspected for detecting
the fault.
- Rectification of any node requires disconnecting the entire bus segment.
2. Star topology
It has a central wiring concentrator called hub to which several nodes( work stations) are
connected. Then all the messages are passed through the central hub. It permits any node to interact
with any other node through the hub.
PC
PC PC
Hub
PC
PC
PC
Advantages
- Failure of one node leads to disconnection of that node from the network. The rest of the
system works without any disturbance
- Maintenance is simple. Faults can be easily located and corrected.
- Access protocol is also very simple
Disadvantages
- Expansion of network adding few more nodes requires large quantity of cable, since every
node has to be connected from the central hub.
- The cabling cost is large
- The entire network is dependant on the central hub. If the hub fails, all the nodes in the entire
network will not operate
3. Ring topology
It connects all the nodes in circular wiring arrangement. Each node is directly connected to its two
neighboring nodes. Data travels in only one direction passing through each node.
PC
Advantages PC PC
- The cable requirement is less
- Optical fibre cables can be used
- Allows high speed data transfer
Disadvantages PC
- Failure of one node leads to failure of entire network PC
- Fault diagnosis is difficult
- For adding new nodes, the entire network has to be shut down. PC
4. Mesh topology
It is the least used network topology and the most expensive to implement. In this environment, a cable runs from
every computer to every other computer. The big advantage of this arrangement is that the data can never fail to be
delivered, if one connection goes down, there are other ways to route the data to its destination.
PC PC
PC PC
Network Hardware
4. Switch
It is similar to a hub. It inspect the data as and when they arrive, determine the source address and
destination address of the data. Based on the destination address, forward the data to the appropriate device.
5. Routers
A router is a device that is used to connect two or more networks. The responsibility of the router is to
select the best path for fast data transmission. As and when the network traffic changes, the router can
redirect the data to less congested routes. They are expensive and difficult to maintain.
6. Gateway
A gate way is a device which is used to connect two or more dissimilar networks that use different
communication protocols.
Network Protocol
Each LAN is governed by a protocol, which is an agreed upon format for transmitting data between two devices.
There are many standard protocols, each having its own advantages and disadvantages. To effectively communicate,
a user must have a same protocol installed on the local PC and remote PC to make a connection. Protocols using
their own methods, break data down into small packets in preparation for transmission. Linking devices pass these
packets to the various pieces of equipment. A packet is data segment that includes a header, payload, and control
elements that are transmitted together. The receiving computer reconstructs the packets into their original structure.
A single LAN may utilize more than one protocol. Some of the most common protocols in use today are:
1. TCP/IP (Transmission Control Protocol/Internet Protocol) : It is originally associated with UNIX hosts. It is
the protocol of the internet and required on any computer that must communicate across the internet. It is
also the default networking protocol of Win 2000, Win XP and Win 2003 Server.
2. IPX/SPX: It is a proprietary protocol from Novel Netware for its Netware operating system.
3. NetBIOS/NetBEUI: It is a simple protocol that has no real configurable parameters. It sends messages to
every computer that can receive them. It is suitable for small offices or homes.
INTERNET
What is Internet?
Internet is a network of networks – a global communication system that links together thousands
of individual networks. As a result, virtually any computer on any network can communicate with any
other computer on any other network. These connections are allow users to exchange messages, to
communicate in real time, to share data and programs and to access limitless stores of information.
History of Internet
The seeds of the internet were planted in 1969, when Advanced Research Projects Agency(ARPA) of the US
department of Defense began connecting at different universities and defense contracts. The resulting network was
called ARPANET. The goal of this early project was to create a large computer network with multiple paths that
could survive a nuclear attack or a disaster such as an earthquake. If one part of the network were destroyed, other
parts of the network would remain functional and data could continue to flow through the surviving lines. It also
allow people to share scarce computing resources. ARPANET’s host computers provided file transfer and
communication services and gave connected systems access to the network’s high speed data lines. The system
grew quickly and spread widely as the number of hosts grew.
The network jumped across the Atlantic to Europe in 1973. In the mid- 1980s, another federal agency, the
National Science Foundation(NSF) joined the project. NSF established super computing centers that were available
to anyone who wanted to use them for academic research purposes. NSF created a new high capacity network called
NSFnet. NSFnet made internet connections widely available for academic research, but NSF did not permit users to
conduct private business over the system. Therefore, several private telecommunication companies built their own
network backbones. These private portions of the internet were not limited by NSFnet’s restrictions, so it became
possible to use the internet to distribute business and commercial information.
The original ARPANET was shutdown in 1990, but the commercial internet backbone services replaced
them. By the early 1990s, interest in the internet began to expand dramatically. Today internet connects thousands
of networks and hundreds of millions of users around the world. Internet is open to anyone who can access it.
Internet access was available to nearly 1.5 billion people worldwide in 2001.
The first page of a Web site is often called the home page. To support hypertext
documents, web uses a special protocol called HTTP (Hypertext transfer protocol). A hypertext document
is a specially coded file that uses HTML (Hypertext markup language). This language allows a
document’s author to embed hypertext links in the document. HTTP and hypertext links are the
foundations of WWW.
The HTTP uses internet addresses in a special format called uniform resource locator or URL. An URL
looks like
type://address/path
Example:
http://www.cittumkur.org/index.html
where type specifies the type of the server in which the file is located, address is the address of the
server and path is the location within the file structure of the server.
Email (Electronic-mail)
Electronic mail was the earliest internet service which brought in the initial communication
revolution by allowing users across the world to exchange messages on the internet within minutes.
Email facility allows the users to send and receive messages from anyone anywhere with an identifiable
e-mail address. It serves as the personal connection to the world of net.
E-Mail system is basically used for sending message electronically to individuals or group of
individuals in an inter and intra office environment. It requires networks to connect them. In the world of
information technology E-Mail is considered to be first experience and exposure to the field of data
communication and networking.
But an E-Mail system can do more than just send message back and forth. Applications that will
be built on the messaging infrastructure include multimedia mail, database access, document sharing,
fax routing, scheduling etc. The most promising areas are workflow, task automation, information routing
etc.
Every day E-Mail vendors coming up with their new version of E-Mail system. The E-Mail system
contains the feature to compose and send messages easily. Message editing and the ability to easily
send attachments that can be quickly opened and read by the recipient are important to improve
productivity and use of an E-Mail system.
An e-mail system provides support for OLE object linking and embeddings which allows user to
incorporate graphics, sound and text into in message. Attaching a file or object to an E-Mail message is
the faster way to route information to a workgroup.
One of the advantages of E-Mail is that it gives users the ability to review, respond to a file, and
discard incoming message quickly. E-Mail is fast becoming more than just a way to route electronic
notes. It is becoming an important communication medium and infrastructure for workgroup applications
that make it easier for people to work together. Using E-mail a user can send text, pictures, sounds,
programs or even movies to any other person on the internet anywhere in the world.
It is easier to send email than paper mail : no stamps, no searching for an envelope – just type
and send!. An example email address : myname@sancharnet.in
Advantages of using email over SNAIL MAIL
Speed – almost instantaneously.
Cost – costs same regardless of the distance
Email Software - Outlook Express, Eudora, Microsoft Exchange, Netscape Mail, Pine etc.
Algorithms:
The finite set of procedural steps, where as each step is precise, SUM A+B+C
unambiguous and capable of being carried out by a machine in a finite time is
known as Algorithm.
As computer expects unambiguous, precise and definite instructions or
command to solve a problem so the algorithm must be expressed in a ‘precise AVG SUM/3.0
notation’.
An algorithm when it is expressed in one of the precise notation is
called as a computer program. Before writing the computer program from PRINT
algorithm an intermediate step i.e. flow-charting is used. SUM,AVG
Flow-chart:
A flow-chart is the pictorial representation of algorithmic steps to be END
performed sequentially to arrive at the result. Actually the computer program is
written only after writing the flow-chart.
Ex 1) Problem Statement: - Find sum and average of three numbers and print the result
Redefined problem: - Write a program to find the sum and average of 3 float number. Accept 3 numbers
from standard input device and display the result on monitor
Outcome of process is sum and average of three numbers given from input device.
Characteristics of Algorithms
1. Input
Algorithm starts with a procedural step to accept input data. The subsequent steps in the algorithm
process these data elements. But this input step is optional and is used only when the algorithm needs
data at the time of execution.
2. Definite
Each operational step must be definite i.e. it should specify what should be done. In other words there
should not be any confusing instruction.
For example: 1) “Compute 5/0”
2) “Add 5 or 10 to 5”
Above statements are not allowed in algorithms because in first statement result of 5/0 is infinity which is
not defined in Computers and also in all branches of Mathematics. The second statement, which of the
two number 5 or 10 should be added to 4, is not clear.
3. Effective
Each operation must be effective to carry out. Effectiveness property of an algorithm says that each
operational step can be at least in principle, being carried in a minimum amount of time.
A = log (B2/C2)
A = log (B/C) 2
A = 2log(B/C)
In C: A = 2*log (B/C)
The above statement is more efficient because logarithmic function is called only once and only one
multiplication. This statement takes very less time for execution as only one call for logarithmic function.
4. Terminate
After some minimum number of operations, algorithm must come to an end i.e. the total time to carry out
all the steps in algorithm must be limited (finite).
5. Output
An algorithm is written to solve the problem therefore it must produce one or more computed results.
In order to incorporate the definiteness property of the algorithm, algorithms will be expressed using a
precise notation called programming languages. Such computer programming languages are designed to
assign clarity, definiteness and effectiveness to each of the instructions of the algorithm. The languages
actually consist of all necessary features to support the characteristics of an algorithm.
1. Sequencing
2. Branching (selections)
3. Repetitions (looping)
These are also called as program structures used in developing structured programs.
1. Sequencing
The sequence structure indicates the sequential flow of program logic i.e. step by step execution program
statement in the algorithm,
For example:
1) In algorithm:
Step 1: [Input the three numbers]
Notes prepared by Shylaja B., CIT, gubbi Page 39
Computer Concepts and C Programming
Input n1,n2,n3
Mul n1*n2*n3
Sum n1+n2+n3
3) In C program:
.
.
scanf(“%d%d%d”,&n1,&n2,&n3);
mult=n1*n2*n3;
sum=n1+n2+n3;
.
.
The step-by-step execution of statements in the algorithm (or in flowchart, programs) is known as
sequencing and sequential execution.
2. Branching (Selections)
Execution of a group of statements depending upon the given condition is known as branching or
selection. In algorithm if-then-else statement is used for branching (selection). Its syntax is as below: -
if (condition) then
statement-1
statement-2
-
-
else
statement-a
statement-b
-
Here the condition is evaluated first and if the condition is true, the statements after “then” is executed
and if condition is false the statements after “else” part is executed. Here the “else” part is optional and
this is used only when it is required. For examples:
In Algorithm:
a) if ( a>0 ) then
write “A is greater than 0”
else
write “A is not greater than 0”
x x+A
b) if ( a>0) then
write “A is +ve number”
x x + a2) In Flowchart:
Yes conditio No
n condti No
on
Yes
3. Repetitions (looping)
The repetitive execution of a group of statements or program segment takes place as long as the loop
condition is true and when the loop condition became false the loop or repetition will be terminated. This
process is known as repetition or looping.
1)In algorithms, repeat, for, do-while etc are used for looping.
Ex: Algorithm for finding sum and numbers from 1 to N
END
Computer Concepts and C Programming
6 Comment.
9 Manual task.
11 Punched cards
Magnetic drum.
12
Notes prepared by Shylaja B., CIT, gubbi Page 42
Computer Concepts and C Programming
13 Magnetic tape
14 Magnetic disk
The symbols from 11 to 15 are known as system symbols and all other symbols are knows as activity symbols.
System Flowcharts:
A system flowchart is a flowchart which given over all view of computer system in addition to the pictorial
representation of the flow of operations of an algorithm.
In other words as the name itself indicate, system flowcharts are drawn to show diagrammatically, the total
environment of computer system on which the given algorithm or program is to be solved. System flowcharts
provide us a list of special symbols for indicating input-output devices on which data transactions are read/printed.
There by one will get a clear picture of input/output devices connected to a computer system. Therefore system
flowchart will further improve and assist the computer programming. Because system flowchart not only specify the
operations to be performed pictorially but the computer system environment at which all these data processing
activities are handled.
To summarize, a system flowchart is a graphical representation that gives the complete view of a data
processing system. It has flowchart symbols to show the following:
The activities (either manual or computing) carried out within such a data processing system
The I/O devices and storage media used to store/handle the data file, transactions etc, which are involved in data
processing activities.
PRINT CENTI
2) Write an algorithm to find biggest of three numbers and
draw the flowchart.
Algorithm: Finding the biggest of three numbers
Step 1: [Input three numbers from input device] END
Input a,b,c
Step 2: [Store the first number in variable big assuming it as the biggest number]
Big a
Step 3: [Compare second value with big]
Notes prepared by Shylaja B., CIT, gubbi Page 43
Computer Concepts and C Programming
START
READ A,B,C
BIG A
PRINT BIG
STOP
3) Write an algorithm to find the factorial of a number and also draw the flowchart.
START
READ N
FACT 1
FOR I = 1 TO N
FACT FACT * I
NEXT
I
PRINT FACT
STOP
4) Write an algorithm to find the area of a triangle given its three sides
Algorithm: To find area of triangle given its three sides
Step 1: [Input the three sides of triangles]
Input A,B,C
Step 2: [Check the validity of given inputs and compute the area if the inputs valid]
IF ( (A+B)>C OR (B+C)>A OR(C+A)>B) then
S (A+B+C)/2
AREA = SQRT(S*(S-A)*(S-B)*(S-C))
Write “Area of triangle is “,AREA
ELSE
Write “Given inputs are invalid”
Introduction to C
High Level Languages have been developed to facilitate easy programming of the computers by any
ordinary person. One such HLL is the C Language. It is becoming so popular that the languages like
BASIC, FORTRAN, and PASCAL are becoming obsolete. This is because C being a High Level
language satisfies the varying requirements of programmers. It can be used for application program
development as well as system program development.
History of C
The history of C starts with a language called BCPL (Beginners Combined Programming
Language) developed by Martin Richards. In 1970, Mr. Ken Thompson, a System Engineer at AT & T
Bell Laboratories, USA, wrote an earlier version of C language for the UNIX operating system. It is a
modified version of the BCPL. Therefore to distinguish his language from BCPL, he called the language
as B language, the first letter of BCPL. The B language was modified to a greater extent by Mr. Dennis
Ritchie at Bell Labs. This modified version of B is called as the C language, the second letter of BCPL.
C was originally designed for UNIX operating system. But, later the whole UNIX operating system
itself was almost rewritten in C language. C is a powerful, general purpose, procedure oriented,
structured programming language.
sum = a + b;
Sub program Section printf(“Sum = %d”, sum);
Or }
User Defined Function Section
1. The Documentation Section : It consists of a set of comment lines giving the name of the
program, the author and other details which the programmer would like to use later. The
comments are enclosed in a C program using /* and */ .
2. The Preprocessor directive or Link section : It provides instruction to the compiler to link some
functions or do some processing prior to the execution of the program. It is also used to define
symbolic constants of the program.
3. Global Declaration Section : There are some variables that are used in more than one function.
Such variables are called global variables and are declared in this section that is outside of all
other functions.
4. main() function section : Every C program must have one main() function. This section contains
two parts, declaration part and executable part. The declaration part declares all the variables
used in the executable part. There is atleast one statement in the executable part. These two
parts must appear between the opening and closing braces. The program execution begins at the
opening brace and ends at the closing brace. The closing brace of the main function is the logical
end of the program. All statements in the declaration part and executable parts must end with a
semicolon.
5. Sub program Section : It contains all the user defined functions that are called in the main()
function. User defined functions are generally placed immediately after the main function,
although they may appear in any order.
All sections except the main() function may be absent when they are not required in any C program.
Executing a C program
Executing a C program involves a series of following steps.
1. Creating a program
2. Compiling the program
3. Linking the program with functions that are needed from the C library.
4. Executing the program
System Ready
Compile Source
C Compiler program
Syntax
Errors
?
Object Code
Logic Error
Data Error Logic &
Data
Errors?
Correct Output
Stop
In MS DOS :
For Compiling press Alt-F9.
For Compiling & Running the program press Ctr-F9.
For viewing the results press Alt-F5.
3. C programs are written in lowercase letters. However uppercase letters may be used for symbolic
names and constants.
4. All the words in a program line must be separated from each other by atleast one space or a tab,
or a punctuation mark.
5. Every statement must end with a semicolon.
6. All variables must be declared for their type before they are used in the program.
7. Compiler directives such as define and include are special instructions to the compiler, so they do
not end with a semicolon.
8. When braces are used in the program make sure that the opening brace has corresponding
ending brace.
9. C is a free form language and therefore proper form of indentation of various sections would
improve the legibility of the program.
10. A comment can be inserted almost anywhere a space can appear. Use of appropriate comments
in proper places increases the readability of the program and helps in debugging an testing.
Like any other High level language, C provides a collection of basic building blocks, symbolic words
called lexical elements of the language. Each lexical element may be a symbol, operator, symbolic name
or word, a special character, a label, expression, reserve word, etc. All these lexical elements are
arranged to form the statements using the syntax rules of the C language. Following are the lexical
elements of the C language.
C Character Set
Every language has its own character set. The character set of the C language consists of basic symbols
of the language. A character indicates any English alphabet, digit or special symbol including arithmetic
operators. The C language character set includes
1. Letter, Uppercase A ….. Z, Lower case a….z
2. Digits, Decimal digits 0….9.
3. Special Characters, such as comma, period. semicolon; colon: question mark?, apostrophe‘
quotation mark “ Exclamation mark ! vertical bar | slash / backslash \ tilde ~ underscore _ dollar $
percent % hash # ampersand & caret ^ asterisk * minus – plus + <, >, (, ), [,], {, }
4. White spaces such as blank space, horizontal tab, carriage return, new line and form feed.
C Tokens
In a passage of text, individual words and punctuation marks are called tokens. Similarly, in C program,
the smallest individual units are known as C tokens. C has following tokens
1. Keywords or Reserve words such as float, int, etc
2. Constants such 1, 15,5 etc
3. Identifiers such name, amount etc
4. Operators such as +, -, * etc
5. Separators such as :, ;, [, ] etc and special characters
6. Strings
Keywords
Key words or Reserve words of the C language are the words whose meaning is already defined and
explained to the C language compiler. Therefore Reserve words can not be used as identifiers or variable
names. They should only be used to carry the pre-defined meaning. For example int is a reserve word. It
indicates the data type of the variable as integer. Therefore it is reserved to carry the specific meaning.
Notes prepared by Shylaja B., CIT, gubbi Page 50
Computer Concepts and C Programming
Any attempt to use it other than the intended purpose will generate a compile time error. C language has
32 keywords. Following are some of them
auto break case char const continue default
do double else enum extern float for
goto if int long register return short
signed sizeof static struct switch typedef union
unsigned void volatile while
Constants
A constant can be defined as a value or a quantity which does not change during the execution of a
program. Meaning and value of the constant remains unchanged throughout the execution of the
program. These are also called as literals. C supports following types of constant.
1. Integer Constants
An integer constant refers to a sequence of digits. There three types of integer constants, namely
decimal, octal and hexadecimal.
Decimal integer constant consists of set of digits from 0 to 9 preceded by an optional + or – sign.
Ex: 123, -321, 0, 4567, + 78
Embedded spaces, commas and non-digit characters are not permitted between digits.
An octal integer constant consists of any combination of digits from 0 to 7 with a leading 0(zero). Ex :
037, 0435, 0567
A sequence of digits preceded by 0x or 0X is considered as hexadecimal digit. They may also include
alphabets A to F or a to f representing numbers from 10 to 15.
The largest integer value that can be stored is machine dependant; It is 32767 for 16 bit computers. It is
also possible to store larger integer constants by appending qualifiers such U, L and UL to the constants.
4. String constants
A string constant is a sequence of characters enclosed in double quotes. The characters may be
alphabets, numbers special characters and blank space. Ex: “Hello”, “2002”, “Wel Come”, “5+3”
Identifiers
An identifier is a sequence of letters, digits and an underscore. Identifiers are used to identify or name program
elements such as variables, function names, etc. Identifiers give unique names to various elements of the program.
Some identifiers are reserved as special to the C language. They are called keywords.
Variables
A variable is a data name that may be used to store data value. A value or a quantity which may vary
during the program execution can be called as a variable. Each variable has a specific memory location
in memory unit, where numerical values or characters can be stored. A variable is represented by a
symbolic name. Thus variable name refers to the location of the memory in which a particular data can
be stored. Variables names are also called as identifiers since they identify the varying quantities.
For Ex : sum = a+b. In this equation sum, a and b are the identifiers or variable names representing the
numbers stored in the memory locations.
Data Types
Data refers to any information which is to be stored in a computer. For example, marks of a student,
salary of a person, name of a person etc. These data may be of different types. Computer allocates
memory to a variable depending on the data that is to be stored in the variable. So it becomes necessary
to define the type of the data which is to be stored in a variable while declaring a variable. The different
data types supported by C are as follows:
It is similar to the float type. It is used whenever the accuracy required to represent the number is more.
In others words variables declared of type double can store floating point numbers with number of
significant digits is roughly twice or double than that of float type. It uses 64 bits i.e. 8 bytes of memory
giving a precision of 14 decimal digits.
Declaration : double variableName;
Further, applying qualifiers to the above primary data types yield additional data types. A qualifier alters
the characteristics of the data type, such as its sign or size. There are two types of qualifiers namely, sign
qualifiers and size qualifiers.
signed and unsigned are the sign qualifiers
short and long are the size qualifiers.
Declaring the variable volatile qualifier tells the compiler explicitly that the variable’s value may be changed at any
time by some external source and the compiler has to check the value of the variable each time it is encountered.
Ex;
volatile int date;
Defining Symbolic Constants
We often use certain unique constants in a program. These constants may appear repeatedly in number of places
in a program. Such constants can be defined and its value can be substituted during the preprocessing stage itself.
Syntax:
#define symbolic-name value of constant
ex:
#define PI 3.14
#define MAX 100
Operators in C
An operator is a symbol which acts on operands to produce certain result as output. For example in the
expression a+b; + is an operator, a and b are operands. The operators are fundamental to any
mathematical computations.
Operators can be classified as follows:
1. Based on the number of operands the operator acts upon:
a. Unary operators: acts on a single operand. For example: unary minus(-5, -20, etc), address
of operator (&a)
b. Binary operators: acts on two operands. Ex: +, -, %, /, *, etc
c. Ternary operator: acts on three operands. The symbol ?: is called ternary operator in C
language. Usage: big= a>b?a:b; i.e if a>b, then big=a else big=b.
2. Based on the functions
a. Arithmetic operators
b. Relational operators
c. Logical Operators
d. Increment and Decrement operators
e. Assignment operators
f. Bitwise operators
g. Conditional Operators
h. Special operators
Arithmetic operators:
C provides all the basic arithmetic operators. The operators +,-,* and / all work the same way as they do in other
languages. These can operate on any built-in data type allowed in C. The unary minus operator, in effect,
multiplies its single operand by -1. Therefore, a number preceded by a minus sign changes its sign.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
Integer division truncates any fractional part. The modulo division produces the remainder of an integer division
and can be used only on integer operands.
Examples:
1) If a and b are integers and a =14 2) -14 / 3 = -4
and b = 3, then -14 / -3 = 4
a + b = 14 + 3 = 17 14 / -3 = -4
a – b = 14 – 3 = 11 -14 % 3 = -2
a * b = 14 * 3 = 42 -14 % -3 = -2
a / b = 14 / 3 = 4 14 % -3 = 2
a % b = 14 % 3 = 2 2%3=2
2/3=0
Here a and b are variables and are known as operands. The modulo divison operator % cannot be used on
floating point data.
Arithmetic expressions:
Notes prepared by Shylaja B., CIT, gubbi Page 55
Computer Concepts and C Programming
An arithmetic expression is a combination of variables, constants and operators arranged as per the syntax of the
language. Expressions are evaluated using an assignment statement of the form
Variable=expression;
The table below shows the algebraic expression and C language expression
Algebraic expression C expression
a b-c a*b-c
(m + n) (x + y) (m + n) *(x + y)
(a b)/c a*b/c
3x2+2x+1 3*x*x+2*x+1
Variable is any valid C identifier. When the statement is encountered, the expression is evaluated first and the result
then replaces the precious value of the variable on the left-hand side. All variables used in the expression must be
assigned values before evaluation is attempted.
x=a*b-c;
y=b/c*a;
z=a-b/c+d;
The blank space around an operator is optional and adds only to improve readability. When these statements are
used in a program, the variables a ,b ,c and d must be defined before they are used in the expressions.
Modes of expression:
There are three different modes of expressions.
1. Integer Arithmetic
2. Real Arithmetic
3. Mixed-mode Arithmetic
Integer Arithmetic
When both the operands in a single arithmetic expression such as a+b are integers, the expression is called an
integer expression, and the operation is called integer arithmetic. This mode of expression always yields an integer
value. The largest integer value depends on the machine, as pointed out earlier
Example:
If a and b are integers then for a=14 and b=4
We have the following results:
a - b=10
a + b = 18
a * b = 56
a / b=3
a %b=2
During integer division, if both the operands are of the same sign, the result is truncated towards zero. If one of
them is negative, the direction of truncation is implementation dependent. That is,
6/7=0 and -6/-7=0
but -6/7 may be zero or -1 (Machine dependent)
Similarly, during modulo division, the sign of the result is always the sign of the first operand(the dividend)
That is
-14 % 3 =-2
-14 % -3= -2
14 % -3=2
Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand may assume values
either in decimal or exponential notation. Since floating point values are rounded to the number of significant digits
permissible, the final value is an approximation of the correct result. If x, y, and z are floats, then we will have:
x=6.0/7.0=0.857143
y= 1.0/3.0 =0.333333
z= -2.0/3.0= -0.666667
Multiplication(*) SECOND
Division(/) and (%)
All the expressions are evaluated from left to right. All the unary negations are done first. After completing this the
expression is scanned from left to right; now all *, / and % operations are executed in the order of their appearance.
Finally all the additions and subtractions are done starting from the left of the expression..
Z=a + b* c
Initially b*c is evaluated and then the resultant is added with a. Suppose if want to add a with b first, then it should
be enclosed with parenthesis, is shown below
Z = (a + b) * c
Use of parentheses:
Parentheses are used if the order of operations governed by the precedence rules are to overridden.
In the expression with a single pair of parentheses the expression inside the parentheses is evaluated FIRST. Within
the parentheses the evaluation is governed by the precedence rules.
For example, in the expression:
a * b/(c+d * k/m+k)+a
the expression within the parentheses is evaluated first giving:
c+dk/m+k
After this the expression is evaluated from left to right using again the rules of precedence giving
ab/c+dk/m+k +a
If an expression has many pairs of parentheses then the expression in the innermost pair is evaluated first, the
next innermost and so on till all parentheses are removed. After this the operator precedence rules are used in
evaluating the rest of the expression.
((x * y)+z/(n*p+j)+x)/y+z
xy, np+j will be evaluated first.
In the next scan
xy+z/np+j +x
Will be evaluated. In the final scan the expression evaluated would be:
(xy+ z/np+j+x)/y +z
We use the increment and decrement statements in for and while extensively.
Consider the following example
m=5;
y=++m;
In this case, the value of y and m would be 6. Suppose, if we rewrite the above statements as
m=5;
y=m++;
then the value of y would be 5 and m would 6. A prefix operator first adds to 1 to the operand and then the
result is assigned to the variable on left. On the other hand, a postfix operator first assigns the value to the
variable on left and then increments the operand.
Similar is the case, when we use ++(or--) in the subscripted variables. That is, the statement a[i++]=10;
is equivalent to
a[i]=10;
i=i+1;
The increment and decrement operators can be used in complex statements. Example
m=n++ -j+10;
Old value of n is used in evaluating the expression. n is incremented after the evaluation.
Relational operators:
We often compare two quantities and depending on their relation, to take certain decisions. For example, we
may compare the age of two persons, or the price of two items, and so on. These comparisons can be done with
the help of relational operators.
C supports six relational operators in all. These operators and their meanings are shown below Relational
Operators
Operator Meaning
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and has the following form:
ae-1 relational operator ae-2
ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or combination of them. Given
below are some examples of simple relational expressions and their values:
4.5 <= 10 TRUE
Notes prepared by Shylaja B., CIT, gubbi Page 58
Computer Concepts and C Programming
When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions will be
evaluated first and then the results compared. That is, arithmetic operators have a higher priority over relational
operators. Relational expressions are used in decision statements such as, if and while to decide the course of action
of a running program.
Logical operators:
In addition to the relational operators . C has the following three logical operators.
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used when we want to test more than one condition and make decisions.
Example: a>b && x == 10
An expression of this kind which combines two or more relational expression is termed as a logical expression or a
compound relational expression. Like the simple relational expressions , a logical expression also yields a value of
one or zero, according to the truth table shown below. The logical expression given above is true only if a>b is true
and x==10 is true. If either (or both) of them are false, the expression is false.
Truth Table
Op-1 op-2 Value of the expression
Op-1 && op-2 op-1 || op-2
Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0
{
int roll_no, physics_marks, chem_marks;
while(scanf(“%d %d %d”, &roll_no, &physics_marks, &chem_marks)!=EOF)
{
If(((chem_marks>=50 && (physics_marks>=35)) || ((chem_marks>=40)) &&
(physics_marks>=50)))
printf(“%d %d %d Pass\n”, roll_no, chem_marks, physics_marks);
else
if (( chem_marks>=60)) && physics_marks<35))
printf(“%d %d %d Repeat Physics\n”, roll_no,physics_marks,chem_marks);
else
printf(“%d %d %d Failed \n”, roll_no, physics _marks, chem_marks);
}
}/*End while*/
}/*End main*/
In the above example, the expressions within the parentheses are evaluated first. The arithmetic operations are
carried out before the relational operations. Thus b*5 is calculated and after that a is compared with it. Similarly
y+6 is evaluated first and then x is compared with it .
Bitwise operators:
All data items are stored in the computer’s memory as sequence of bits (i.e. 0s and 1s) and some applications need
the manipulation of bits. C has a distinction of supporting special operators known as bitwise operators for
manipulation of data at bit level. These operators are used for testing the bits, or shifting them right or left. Bitwise
operators may not be applied to float or double.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ One’s Complement
The result of bitwise AND operator is 1 when both the bits are 1, otherwise it is 0. Similarly the result of bitwise
OR is one if any one of the bit is 1, otherwise it is 0. The result of bitwise XOR is 1 when the bits are different. The
bitwise complement operator reverses the state of each bit. i.e. if the bit is zero, complement of it will 1 and vice
versa.
Ex: int a =5, b=3;
Then equivalent binary representation of a = 5 = 0000 0101 and b=3= 0000 0011
Therefore
a = 0000 0101
b = 0000 0011
a&b = 0000 0001 = 1
a|b = 0000 0111 = 7
a^b = 0000 0110 = 6
~a = 1111 1010
a << 1 = 0000 1010 = 10 equivalent to multiplying a by 2
a >> 1 = 0000 0010 = 2 equivalent to dividing a by 2
Special Operators
1) Comma Operator
C has some special operators. The comma operator is one among them. This operator can be used to link the related
expressions together. A comma-linked list of expressions are evaluated left to right and the value of right-most
expression is the value of the combined expression.
For example, the statement
Value=(a=2, b=6 ,a+b);
First assigns the value 2 to a, then assigns 6 to b, and finally assigns 8(i.e 2+6) to value. The comma operator has
the lowest precedence of all operators,hence the parentheses are necessary.
Some examples are given below:
In for loops:
for(a=1, b=10;a<=b; a++, b++)
In while loops:
while(c=getchar(), C!=’10’)
Exchanging values:
t=x, x=y, y=t;
2) sizeof operator
The sizeof operator returns the memory size (in bytes) of the operand. The operand may be a constant, variable or a
data type. It is normally used to determine the size of arrays and structures. Its syntax is as follows:
sizeof(operand);
Example : x = sizeof(int); will return 2
y = sizeof(10.2) will return 4 since a float point constant requires 4 bytes of memory
z = sizeof(x) will return 2
Example program:
main()
{
int x;
double y;
char ch=’y’;
clrscr();
printf(“Size of x = %d\n”, sizeof(x));
printf(“Size of y = %d\n”, sizeof(double));
printf(“Size of char = %d\n”, sizeofch));
getch();
}
Mathematical Functions:
In c there are no built-in mathematical functions. The table below shows the mathematical functions.
Function Meaning
Trigonometric
1. acos(x) Arc cosine of x
2. asin(x) Arc sine of x
3. atan(x) Arc tan of x
4. atan2(x,y) Arc tangent of x/y
5. cos(x) cosine of x
6. sin(x) sine of x
7. tan(x) tangent(x)
Hyperbolic
1. cosh(x) Hyperbolic cosine of x
2. sinh(x) Hyperbolic sine of x
3. tanh(x) Hyperbolic tangent of x
Other functions
ceil(x) x rounded up to the nearest integer
exp(x) e to the power x
fabs(x) Absolute value of x
floor(x) x rounded down to the nearest integer
fmod(x,y) Remainder of x/y
log(x) Natural log of x, x>0
log 10 (x) Base 10 log of x, x>0
pow(x,y) x to the power y
sqrt(x) Square root of x, x>=0
Note:
1. x and y should be declared as double
2. In trigonometric and hyperbolic functions, x and y are in radians
3. All the functions return a double.
Preprocessor directives:
There are different preprocessor directives. The table below shows the preprocessor directives.
Directive Function
#define defines a macro substitution
#undef Undefines a macro
#include Specifies the files to be included.
#ifdef Tests for a macro definition
#endif Specifies the end of #if
#ifndef Tests whether a macro is not defined
#if Tests a compile-time condition
#else Specifies alternatives when #if tests fails
#define statement:
One of the uses of the #define statement is for assigning symbolic names to program constants.
The general syntax is :
#define TRUE 1
defines the name TRUE and makes it equivalent to the value 1. The name TRUE can subsequently be used
anywhere in the program where the constant 1 could be used. Whenever this name appears, its defined value of 1
will be automatically substituted into the program by the preprocessor. For example, we might have the following C
statement that uses the defined name TRUE
count=TRUE;
This statement would assign the value of TRUE to count.
The preprocessor statement
#define FALSE 0
would define the name FALSE and would make its subsequent use in the program equivalent to specifying the
value 0. Therefore, the statement
count=FALSE;
would assign the value of FALSE to count and the statement
If (count = = FALSE)
……
would compare the value of count against the defined value of FALSE.
#define TRUE 1
#define FALSE 0
/*Function to determine if an integer is even*/
main()
{
int number,ans;
printf(“enter the number:”);
scanf(“%d” , &number);
if (number%2==0)
{
ans=TRUE;
else
ans=FALSE;
}
}
Some more examples of definition constants:
#define COUNT 100
#define SUBJECTS 6
#define PI 3.1415
#define CAPITAL “BANGALORE”
#include statement:
C preprocessor enables you to collect all your definitions into a separate file and then include them in your program
using the #include statement.
The general statement for this preprocessor directive is:
#include “filename”
The #include directive can take the form
#include<filename>
without double quotation marks. In this case, the file searched only in the standard directories.
#include <stdio.h>
#include “SYNTAX.C”
#include “STAT.C”
#include “TEST.C”
Header files:
C language offers simpler way to simplify the use of library functions to the greatest extent possible. This is done
by placing the required library function declarations in special source files, called header files. Most C compilers
include several header files, each of which contains declarations that are functionally related. stdio.h is a header
file containing declarations for input/ouput routines; math.h contains declarations for certain mathematical functions
and so on. The header files also contain other information related to the use of the library functions, such as
symbolic constant definitions.
The required header files must be merged with the source program during the compilation process. This is
accomplished by placing one or more #include statements at the beginning of the source program.
The other header files are:
<ctype.h> character testing and conversion functions
<stdlib.h> utility functions such as string conversion routines , memory allocation routines, random number
generator, etc
<string.h> String manipulations functions
<time.h> time manipulation functions
Specifies that an integer is to be stored into a, float is to be stored in b and a float written using the exponent format
in c. The appropriate sample data line is:
485 498.762 6.845e-12
printf function:
The general format of an output function is
printf(format-string, var1,var2…..varn);
Where format-string gives information on how many variables to expect, what type of arguments they are, how
many columns are to be reserved for displaying them and any character string to be printed. The printf() function
may sometimes display only a message and not any variable value. In the following example:
printf(“Answers are given below”);
The format-string is:
Answers are given below
And there are no variables. This statement displays the format-string on the video display and there are no variables.
After displaying, the cursor on the screen will remain at the end of the string. If we want it to move to the next line
to display information on the next line, we should have the format-string:
printf(“Answers are given below\n”);
In this string the symbol \n commands that the cursor should advance to the beginning of the next line.
In the following example:
printf(“Answer x= %d \n”, x);
%d specifies how the value of x is to be displayed. It indicates the x is to be displayed as a decimal integer. The
variable x is of type int. %d is called the conversion specification and d the conversion character .
In the example:
printf(“a= %d, b=%f\n”, a, b);
the variable a is of type int and b of type float or double. % d specifies that a is to be displayed as an integer and %f
specifies that, b is to be displayed as a decimal fraction. In this example %d and %f are conversion specifications
and d, f are conversion characters.
Output:
1,2,3,4,5,6,7,8,9,0
45,67,45.78,34.90
{
int a,b,c,d;
float x,y,z,p;
scanf(“%d %o %x %u”, &a, &b ,&c ,&d);
printf(“the first four data displayed\n”);
printf((“%d %o %x %u \n”, a,b,c,d);
scanf(“%f %e %e %f”, &x, &y, &z, &p);
printf(“Display of the rest of the data read\n”);
printf(“%f %e %e %f\n”, x,y,z,p);
printf(“End of display”);
}
Input:
-768 0362 abf6 3856 -26.68 2.8e-3 1.256e22 6.856
Output:
The first four data displayed
-768 362 abf6 3856
Display of the rest of the data read
-26.680000 2.800000 e-03 1.256000e+22 6.866000
End of display
scanf stops when it exhausts its format string, or when some input fails to match the control specification. It
returns as its value the number of successfully matched and assigned input items. This can be used to decide
how many items were found . On end of file EOF is returned; note that this is different from 0, which means
that the next input character does not match the first specification in the format string. The next call to scanf
resumes searching immediately after the last character already converted.
A conversion specification directs the conversion of the next input field. Normally the result is placed in the
variable pointed to by the corresponding argument. If assignment suppression is indicated by the * character,
however, the input field is skipped; no assignment is made. An input field is defined as a string of non-white
space characters; it extends either to the next white space character or until the field width, if specified, is
exhausted. This implies that scanf will read across line boundaries to find its input, since new lines are white
space. (White space characters are blank, tab, new line, carriage return, vertical tab and form feed).
The format string contains two types of objects: ordinary characters, which are copied to the output stream, and
conversion specifications each of which causes conversion and printing of the next successive argument to
printf. Each conversion specification begins with a % and ends with a conversion character. Between the % and
the conversion character there may be in order:
• A minus sign, which specifies left adjustment of the converted argument.
• A number that specifies the minimum field width. The converted argument will be printed in a field at least
this wide. If necessary it will be padded on the left or right, to make up the field width.
• A period, which separates the field width from the precision.
• A number, the precision, that specifies the maximum number of characters to printed from a string, or the
number of digits after the decimal point of a floating point value, or the minimum number of digits for an
integer.
• An h if the integer is to be printed as a short, or l if as a long.
e,E double; [-] m.dddddd e+/-xx or [-] m.dddddd E+/- xx, where the number of d’s is given by
the precision(default 6)
g,G double; use %e or %E if the exponent is less than or equal to the precision; otherwise use
%f. Trailing zeros and a trailing decimal point are not printed.
A width or precision may be specified as * , in which case the value is computed by converting the next
argument(which must be an int). For example, to print at most max characters from a string s.
Printf (“%.*s”, max, s);
Most of the format conversions have been illustrated in earlier . One exception is precision as it relates to strings.
The following example shows the effect of a variety of specifications in printing “hello world”.
C programs:
1) Program to demonstrate printf statement
#include<stdio.h>
main()
{
printf(“hello, world\y”);
printf(“hello, world\7”);
printf(“hello, world\?”);
}
2) Program to convert farenheit to Celsius
Notes prepared by Shylaja B., CIT, gubbi Page 69
Computer Concepts and C Programming
#include<stdio.h>
main()
{
float fahr, Celsius;
printf(“ enter the value for farenheit\n”);
scanf(“ %f”, &fahr);
Celsius=(5.0/9.0)*fahr-32.0;
printf(“%f %f \n”, fahr,Celsius);
}
3) Program to depict interactive computing using scanf function.
#include<stdio.h>
main()
{
int number;
printf(“enter an integer number\n”);
scanf(“%d”, &number);
if (number<100)
printf(“Your number is smaller than 100\n\n”);
else
printf(“Your number contains more than two digits\n”);
}
4) Program to convert days to months and days
#include<stdio.h>
main()
{
int months,days;
printf(“enter days \n”);
scanf(“%d”, &days);
months=days/30;
days=days%30;
printf(“Months = %d Days= %d”, months,days);
}