You are on page 1of 70

Computer Concepts and C Programming

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.

Computers for Individual Users:


Modern computers can be classified in a number of ways. The Computers meant for Individual users can be
classified as follows:
1. Desktop Computers
The most common type of personal computer is desktop computer, a PC that is designed to sit on a desk or
a table. They are far more powerful and are used for amazing array of tasks ranging from word processing
to video editing and playing games. The main component of a desk top computer is system unit, which
houses the computer’s critical parts such as processor and storage devices.
2. Workstation Computers
A workstation is a specialized, single user computer that typically has more power and features than a
Desktop computer. These are popular among scientists, engineers, and animators who need a system with
greater than average speed and power to perform sophisticated tasks. They have large, high resolution
monitors making them suitable for advanced CAD, modeling and animation applications.
3. Laptop or Notebook computers
It approximates the size of notebook and easily fit inside a briefcase. They can be operated by special
batteries. They weigh less than three pounds. They are fully functional computers for portable applications.
4. Tablet PCs
It is the newest development in the portable, full featured computers. They offer all the functionality of a
notebook PC, but they are lighter and can accept input from a special pen called stylus or digital pen. They
have built in microphone to accept voice commands.
5. Handheld computers
These are computing devices small enough to fit in the hand. A popular one is a PDA(Personal Digital
Assistant). A PDA is no larger than a small appointment book and is normally used for special applications
such as taking notes, displaying telephone numbers and addresses, etc. They also allow the user to access
internet.
6. Smart phones
Some cell phones work as miniature PCs. They include features such as web and email access and can be
used as digital cameras or music players.

Computers for organization


Computers for organizational uses can be categorized as
1. Network Servers
A network server is a powerful personal computer with special software and equipment that enable it to
function as the primary computer in the network. It gives flexibility to the users to do different kinds of
tasks. This is because PCs are general purpose machines designed to be used in many ways. For example,
some users in the network may use the server for accessing internet and others may use it for centralized
accounting tasks. The server can support these processes from different networked computers, while storing
information and programs for many people to use.
2. Mainframe computers

Notes prepared by Shylaja B., CIT, gubbi Page 1


Computer Concepts and C Programming

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.

Characteristics of a digital computer:


a. High speed: A computer is a fast information processing electronic device. It carries out all sorts of
computations within a fraction of a second. It can execute millions of instructions per second.
b. Accuracy: Computer gives accurate results for correct input data. Errors do occur in computer systems, but
they are not directly attributed to the computer. The errors may be due to program logic errors, a procedural
erros, or erroneous data. These are human errors. The hardware errors are usually detected and corrected by
the computer itself. Computers rarely make mistakes and can accurately perform all kinds of complex
computations.
c. Reliability: Computer systems are particularly adept at repetitive tasks. They are capable of operating under
most adverse conditions for extended periods of time without showing any signs of fatigue. They provide
consistently accurate results under all operating conditions.
d. Memory capability: Computer has total and important recall of data and almost unlimited capacity to store
these data
e. Versatility: It can be used for various purposes such as scientific calculations, business processing,
computer games, teaching, training, music, etc.

The Basic Functional Units of a Digital Computer


A computer is really a collection of separate items working together as a team. Some of these components
are essential; others simply make working more pleasant and efficient. Adding extra items expands the variety of
tasks you can accomplish with your machine. Basic Components are System unit, Monitor, Keyboard, Floppy disk
drive and Hard disk drive. Optional components are Mouse and printers.

Notes prepared by Shylaja B., CIT, gubbi Page 2


Computer Concepts and C Programming

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.

Notes prepared by Shylaja B., CIT, gubbi Page 3


Computer Concepts and C Programming

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.

Stored Program Concept


Since a computer can perform arithmetic operations, it may seem to be just a calculator. But there is at least
one important difference. With a calculator, it is necessary to enter instructions one at a time. With a computer, the
complete set of instructions to be performed is stored in the primary memory of the computer. The idea of storing
the program in the memory is called the stored program concept and is fundamental to all modern computers. This
stored program concept was first proposed by John Von Neumann in the year 1945.

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.

The Parts of a Computer System


A complete computer system contain following four parts
1. Hardware
The mechanical, electromechanical, electrical and electronic components, I/O devices, and other physical
components of the computer are collectively called as computer Hardware.
2. Software
The logical counterpart of physical hardware is software, which represents the intangible and invisible part
of the computer system. A software is a collection of computer programs or a set of instructions.
3. Data

Notes prepared by Shylaja B., CIT, gubbi Page 4


Computer Concepts and C Programming

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.

The Information Processing Cycle:


The key task of computers is to accept discrete and disjoint sets of data, store it and process it to convert them to
useful information. All such activities or operations of a computer are part of a process known as information
processing cycle.
The Information processing cycle can be defined as a sequence of steps that the computer follows to accept data as
input, process it according to the stored program’s instructions and finally display the resulting information to its
users as output and store these results at the end.
In essence, the information processing cycle consists of four distinct parts. They are
1. Input
2. Processing
3. Output
4. Storage

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.

Essential Computer Hardware


The minimum hardware requirements of a computer can be categorized as follows:
1. Processor
2. Memory
3. Input and Output Devices
4. Storage Devices
Notes prepared by Shylaja B., CIT, gubbi Page 5
Computer Concepts and C Programming

1. The processor or Processing Devices


The process of transforming the raw data into useful information is called processing. Every digital computer
consists of a processing unit called a processor. This processor is a microprocessor which is an integrated circuit
containing the ALU(Arithmatic and Logic Unit) and Control Unit which are integrated in a single chip. The
Processor is also called a CPU(Central Processing Unit). The CPU acts like the brain of a computer. It organizes
and processes the data and instructions received from the input unit such as keyboard. The CPU consists of two
parts. ALU and Control Unit.
The Processor is plugged into the motherboard of the computer using a special slot. The motherboard is a rigid
rectangular circuit board containing the different electronic circuits that connects processor to the other
hardware devices.
The speed of the processor is measured in MHz or GHz. The typical speed of a Pentium 4 processor is 2.8GHz.
There are processors from other companies such as AMD, Motorola, etc.
2. Memory
The term memory in a computer mainly refers to primary memory or main memory. The main memory consists
of one or more IC chips that store data and instructions either temporarily or permanently. There are two
important memories called RAM which is temporary memory and ROM which is a permanent memory.
RAM (Random Access Memory)
RAM is a short-term memory or volatile memory i.e. when the computer is switched off all the
information stored will disappear. It is a read write memory. The data and instructions typed by the user will be
stored in this memory. It is made up of metal oxide semi conductor, therefore any memory location can be
randomly accessed for reading and writing. There are two kinds of RAM viz. Static RAM, and Dynamic RAM.
ROM (Read Only Memory)
This is permanently in-built into the computer at the time of its production. It is also called as firmware.
It stores instruction permanently, which instructs the computer how to work and permanent data and programs
like trigonometric, logarithmic function are also stored. The data stored in ROM doesn’t change and it doesn’t
need power to retain it. Hence it is called non-volatile memory. There are different kinds of ROM viz. PROM,
EPROM, EEPROM,etc.
PROM : Programmable Read Only Memory is a variation of ROM. The contents of this memory are
decided by the user. It is initially empty. Later the user can store programs, data or any other information
permanently in this memory. However, these data cannot be erased once they are written.
EPROM: Erasable PROM whose contents can be erased by exposing it to an ultra violet light source for
about 10-20 minutes. Then it is programmed.
EEPROM: Electrically Erasable PROM. The contents stored in this memory can be erased electrically.

3. Input and Output Devices


There are several types of Input and output devices which can be connected to the computer for specific
purposes. The most common input device is the keyboard and is used to input text, numbers and commands.
The mouse, joystick, trackball, scanner, optical readers, microphone, digital camera, etc are other input devices.
The output device is used to display the processed data to the users. The most commonly used outpuit devices
are monitors and printers. The output displayed on the monitor is called softcopy output and that printed on a
paper is called hardcopy output. The Plotters, Speakers, are other output devices.
There are some other devices which acts as both input and output devices. Such devices are called I/O devices.
Examples: touch screen, modem, etc.
4. Storage Devices
Data and instructions can be permanently stored using storage devices. There are two types of storage devices –
magnetic storage devices and optical storage devices. The magnetic storage devices are made of magnetic
material while the optical storage devices use the laser technology to read and write the data. Hard Disk, Floppy
disk, etc are magnetic storage devices. CDROM, DVD, etc are optical storage devices.

Notes prepared by Shylaja B., CIT, gubbi Page 6


Computer Concepts and C Programming

Interacting with the Computer


The devices that accept data from the user and communicate it to the CPU are called input devices. Ex: Keyboard,
Mouse, Scanner, etc. Since the CPU understands only binary information, the input devices and circuitry must
eventually communicate with the CPU in binary form only.
The device which produces the processed data on a monitor or a paper is called an output device. Both the
input and output devices are basically electromechanical devices. All the electromechanical devices that are
connected to the CPU are called peripheral devices. Today’s peripheral devices will have wired or wireless
connectivity with the CPU.
Keyboard
It is the most common input device. Keyboard is the more or less similar to job-typewriting machine's keyboard. It
is used to enter both numerical and character type data. The keyboard has few additional keys, some function keys
and control keys. The keyboard layout used here is called QWERTY layout named after the letters in the top-left
second row of the keyboard. The QWERTY layout is maintained just to make it easy for the trained typists to use
the computer keyboard for faster typing operations. The present keyboard has 101 keys. The standard layout of the
commonly used keyboard has six types of keys. Each type of keys is used to perform a specific task. The six types
of keys are
1. Alphanumeric keys
These are used to enter the text and numbers. In this area, there are other keys such as Tab, Caps Lock,
Back space and Enter keys which are meant for specific purpose. The Tab key moves the cursor to
predefined location or next tab stop position. The Caps Lock key used to lock the alphabets to display only
uppercase letters. The Backspace key is used to delete a character in the backward direction. The Enter key
is used to perform the tasks like running the programs, execute commands, and transfer the control to the
next lines, etc.
2. Modifier keys
These are Shift, ALT and CTRL keys. All these keys are used to modify the input of other keys. The
simultaneous press of Shift key along with an alphabet would result in capital letter or symbol. The Alt key
is used to display menus in some applications. The Ctrl key will initiate certain action when it is pressed
with another specific alphabet. For Ex: Ctrl-S will save the file most applications.
3. Function keys
They appear as a separate row on the topmost portion of the keyboard. They are numbered as F1, F2, ---
F12. Each function key performs a specific function in the application. For ex: F1 key is used for displaying
help.
4. Cursor movement keys
These are used to mover the cursor from one position to another on the screen..
5. Numeric Keypad
It used to enter numbers. It acts as a calculator keypad. This can be enabled by pressing the NUM Lock key.
When Num Lock is off, the Numeric key pad will work as navigational keypad.
6. Special purpose keys
There are special keys in the keyboard such as windows keys. They will perform some special functions
depending on the operating system or application.
Working of the Keyboard:
The keyboard consists of an electronic circuit to decide which key has been pressed. Thus the keyboard control
electronic circuit has to perform the following functions. Sensing a key pressed, Encode the sensed key, Send the
encoded data to the computer
Key Board
System
Keyboard Keyboard Software
Controller Buffer (Operating
System)
CPU
Notes prepared by Shylaja B., CIT, gubbi Page 7
Computer Concepts and C Programming

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

KEYBOARD 8-bit scan code and equivalent


ASCII code sent in parallel.

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

Notes prepared by Shylaja B., CIT, gubbi Page 8


Computer Concepts and C Programming

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.

Inputting Data in other ways: Devices for the Hand


These devices are designed to interact with the computer using Hand.
Light pen
It is a pencil like device used to select screen coordinates by detecting the light coming from illuminated
points on the CRT Screen. It uses light sensitive photo electric cells to signal screen position to the computer. These
are frequently used by the graphic designers, illustrators and drafting engineers.
Touch Screens:
This technology replaces the keyboards and mouse which would require more desk space and become dirt
eventually with frequent use. The touch screens are very easy to operate and do not require much skill. They are
based on either pressure sensitivity, electrical sensitive or photo sensitive materials. The user can directly touch the
screen with his/her finger tip. When the user touches the screen, the sensors detects the touch of the screen. These
are widely used in ATMs and other public Kiosks.
Game Controllers
The game controllers are input devices used to play computer games. There are two basic game controllers:
1. Joystick : It consists of a small lever or stick mounted on a rolling ball. This lever is used
control the movement of the objects on the screen similar to a mouse.
2. Game Pad: It is a small and flat hand held pad with several control buttons on it. It is
connected to the computer by a special port. They are most frequently used in computer or
video games.

Optical Input Devices


They use optical technology to input data to the computers. The bar code readers, image scanners and Optical
Character Recognizers are examples of Optical input devices.
Bar Code Readers:
A bar code is made up of vertical lines and spaces. The sequence of bars and spaces of different thickness
represents a sequence of numbers. A bar code reader is used to read the bar code. The reader uses the laser beam
that is sensitive to the different reflections from the lines and spaces. The reader translates the reflected light into
digital data that is transferred to a computer for immediate action. They are fast and reliable method of inputting
data. They can be read even when they are on curved surfaces or on materials such as clothe.
Image Scanner:
It is used to acquire graphical image of the object. It can be used to scan both text as well as pictures. It
scans the image of a photograph, or written information for character recognition. Sensors are used in scanners. Flat
bed scanner is the most commonly used scanner. Drum scanner or roller scanner is also used
Optical Character Recognition (OCR)
An OCR system consists of a scanner and some software. The scanner is used to scan an image of a page of text and
the software system converts the image into readable text.

Audio-Visual Input Devices

Notes prepared by Shylaja B., CIT, gubbi Page 9


Computer Concepts and C Programming

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

Notes prepared by Shylaja B., CIT, gubbi Page 10


Computer Concepts and C Programming

Electron Gun

Phosphor coated screen

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

Flat Panel Monitors


The most common flat panel monitor is like Liquid Crystal Display(LCD) monitor . The LCD monitor creates
images with a special kind of liquid crystal that is normally transparent, but becomes opaque when charged with
electricity. One disadvantage of LCD monitors is that their images are difficult to see in bright light and their
viewing is limited by the viewing angle.
There are two categories of LCDs they are,
1. The passive matrix LCD, which uses transistors for each row and each column of pixels thus creating a grid
that defines the location of each pixel. The colour displayed by a pixel is determined by the electricity
coming from the transistors at the end of the row and at the top of the column. These are in expensive to
manufacture , but they have narrow viewing angle.
2. The active matrix LCD technology assigns transistors to each pixel and each pixel is turned on and off
individually. These have a wider viewing angle and use TFT technology (Thin film film transistor), which
employ as many as 4 transistors per pixel, thus improving the image quality.
Other types of monitors
1. Paper white displays: Used by document designers such as DTP specialists for high quality printed
documents.
2. Electroluminescent displays which are similar to LCD monitors but use a phosporoscent film held between
2 sheets of glass. A grid of wires sends current through the film to create an image.
3. Plasma displays : are created by sandwiching a special gas between two sheets of glass. When the gas is
electrified via a grid of small electrodes, it glows. By controlling the amount of voltage applied at various
points on the grid, each point acts as a pixel to display an image.

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

Notes prepared by Shylaja B., CIT, gubbi Page 11


Computer Concepts and C Programming

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.

Notes prepared by Shylaja B., CIT, gubbi Page 12


Computer Concepts and C Programming

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

Notes prepared by Shylaja B., CIT, gubbi Page 13


Computer Concepts and C Programming

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.

Chain or Band printers


A chain printer has a steel band on which the character sets are embossed. For a 64 character set printers, 4 sets of
64 characters each would be embossed on the band. For printing a line all the characters in the line are send from
the memory to the printer buffer register. The band is rotated at a high speed. As the band rotates a hammer is
activated when the desired characters specified in the buffer register comes in front of it. For printer with 132
characters per line, 132 hammer will be positioned to strike the carbon ribbon, which is placed between the chain,
paper and the hammer. The main advantage of chain or band printer is that the chains can be replaced easily. Since
the chains are cheaper, so different fonts and different scripts may be used with same printer.

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.

Notes prepared by Shylaja B., CIT, gubbi Page 14


Computer Concepts and C Programming

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.

High Quality Printers:


The high quality printers are used by publishers and small print shops to create high quality output, especially
colour output.
1. Photo Printers
With digital cameras and scanners becoming increasingly popular, users want to be able to print the
images they create or scan. While the average color ink jet printer or laser printer can handle this job,
but the quality is not good. To get high quality color outputs photo printers are used. The best photo
printers can create images that look nearly as good as a photograph printed using traditional methods.
2. Thermal wax printers
These are used primarily for presentation graphics and hand outs. They create bold colors and have a
low per page cost for print outs with heavy color requirements, such as posters or book covers. The
process creates vivid colors because the inks do not bleed into each other or soak the specially coated
paper. They operate with a ribbon coated with panels of colored wax that melts and adheres to plain
paper as colored dots when passed over a focused heat source.
3. Dye-Sublimation printers
Desktop publishers and graphic artists get realistic quality and color for photo images using dye-
sublimation printers. In this, a ribbon containing panels of color is moved across a focused heat source
capable of subtle temperature variations. The heated dyes evaporate from the ribbon and diffuse on
specially coated paper or another materials, where they form areas of different colors. These printers
produce extreme sharp images, but they are slow and costly.

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.

Notes prepared by Shylaja B., CIT, gubbi Page 15


Computer Concepts and C Programming

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

How Computers Represent Data:


Computers recognize two distinct physical states produced by electricity, magnetic polarity, or reflected
light. Essentially they understand whether a switch is on or off. In fact, the CPU, which acts like the brain
of the computer, consists of several million tiny electronic switches, called transistors. A computer
understands information only because it operates on at such phenomenal speeds, grouping its individual
on/off switches into patterns that become meaningful to us.

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.

Bits and Bytes


When referring to computerized data, the value represented by each switch’s state is called a bit(a
combination of binary digit). A bit is the smallest possible unit of data a computer can recognize or use. A
group of 8 bits is called a byte. With one byte computer can represent one of 256 different symbols or
characters because the eight 1s and 0s in a byte can be combined in 256 different ways.
bit = Binary digit ( either 0 or 1)
4 bits = 1 nibble
8 bits = 1 byte
1024 bytes = 1 kilo byte ( KB)
1024 KB = 1 MB
1024 MB = 1 GB

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.

Notes prepared by Shylaja B., CIT, gubbi Page 16


Computer Concepts and C Programming

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

Play sound Instruction 1

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).

Notes prepared by Shylaja B., CIT, gubbi Page 17


Computer Concepts and C Programming

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.

Volatile Memory (RAM):


Volatile memory requires power to store data. It is also called Random Access Memory. Physically, RAM
consists of chips on a small circuit board. Single Inline Memory Modules (SIMM) and Dual In-lne
Memory Modules(DIMM) chips are found computers. RAM is designed to be instantly accessible by the
CPU. A memory address is a number that indicates a location on the memory chips, just as post office box
number indicates a slot into which mail is placed. Memory addresses start at zero and go upto one less
than the number of bytes of memory in the computer.

Factors Affecting Processing Speed:


Following are the factors affecting processing speed of a CPU:
1. Registers.
The size of the register affects the processing speed. Older PCs have 16bit registers. Now we have
32bit and 64bit register CPUs. The size of the register, called word size indicates the amount of data
with which the computer can work at any given time. The bigger the word size, the more quickly the
computer can process a set of data. If all other factors are kept equal, a CPU with 32 bit register can
process data twice as fast as one with 16 bit register
2. Memory
The amount of RAM in a computer can have a profound effect on the computer’s power. More RAM
means the computer can use bigger, more powerful programs and those programs can access bigger
data files. More RAM also make the computer run faster.
3. Internal Clock or Clock frequency of CPU
Every computer has a system clock to keep the time. The clock is driven by quartz crystal. When the
electricity is applied, the molecules in the crystal vibrate millions of times per second, a rate that never

Notes prepared by Shylaja B., CIT, gubbi Page 18


Computer Concepts and C Programming

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

Notes prepared by Shylaja B., CIT, gubbi Page 19


Computer Concepts and C Programming

Extending Processor’s Power To Other Devices


The external devices such as keyboard, mouse, speakers, etc. can be connected to the CPU using ports. A
port is an interface through which data can be sent to CPU and data can be received from CPU. Various
ports that are commonly supported by any computer are:
Mouse port: used to connect mouse to CPU.
Keyboard port : used to connect keyboard to CPU.
Network port: used for networking with different other computers
USB port : These ports can accept any of the devices such as digital cameras, printers, memory
sticks, etc.
Parallel port : older printer are connected using this port.
Serial port : External modems are connected.
Audio Input and output port : used for recording and connecting to speakers.
Monitor port : used to connect monitor

Serial and Parallel ports:


The serial ports are used to connect a device that can send or receive the data bit-by-bit on a single
wire. Only one bit can be passed at a time. So the data bytes are sent one bit at a time serially and hence
these ports are called serial ports. Inside the computer, a chip called a Universal Asynchronous Receiver
Transmitter(UART) converts the parallel data from the data bus into serial data that flow through a serial
cable.
The parallel port is used to connect a device that can send or receive the data by allowing 8 or 16
bits of data to be transmitted at a time. So, it requires 8 or 16 wires to send or receive the information
simultaneously. Since 8 bits or 16 bits of data is sent or received at a time, these ports are called parallel
ports. Data transfer rate is more as compared to serial ports. It is used for handling high volume of data.

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.

Notes prepared by Shylaja B., CIT, gubbi Page 20


Computer Concepts and C Programming

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

Magnetic Storage Devices


Magnetic storage devices are widely used to store the data permanently. All magnetic disks are
made of thin, circular plate made of metal or plastic usually coated with magnetizing material such as iron
oxide on both sides. The data can be stored both sides of the disk and each side has its own read-write
head. These disks are enclosed in a protective casing or cartridge. The data on these devises can be erased
and reused any number of times.

Storage of Data in Magnetic Disks


The data is represented in the form of magnetized spots on the magnetic disk or magnetic tape.
Since, the disk is coated with magnetic particles, each particle can act as a magnet under the influence of
magnetic field. The data in the form of electrical impulses ( i.e. low current and high current) is sent to the
storage devices. When the current passes through the coil inside read/write head, the head acts as an
electromagnet and induces a magnetic field. This magnetic field creates a magnetic spot on the media. In
the absence of electric current, the coil inside read/write head do not act as an electromagnet and hence do
not induce any magnetic field. Hence, a magnetic spot will not be created on the media. Thus as the head
passes over storage media, the data sent by the CPU in the form of electrical impulses are converted into
magnetic spots on the media to represent data.

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.

Data organization in a Magnetic Disk


Before the computer can use a magnetic to store data, the disk’s surface must be magnetically mapped so
that the computer can go directly to a specific point on it without searching through data. The process of
mapping a disk is called formatting or initializing. Formatting is done in two stages:
• Tracks are created in first stage of formatting
• Sectors are created in second stage
Tracks are the concentric circles created by the disk drive during formatting. Each circle represents a track
and most diskettes have 80 tracks on each side of the disk. The tracks are numbered from outermost circle

Notes prepared by Shylaja B., CIT, gubbi Page 21


Computer Concepts and C Programming

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

Fig. Organization of tracks and sectors on disk surface

the size of the disk is calculated as follows:


= 2 x 80 x 18 x 512
= 1440 KB = 1.44 MB

How the Operating System Finds Data on a Disk:


A computer’s operating system can locate data on a disk because each track and each sector are
labeled, and the location of all data is kept in a special log on the disk. The labeling of tracks and sectors is
called logical formatting.
Different operating systems can format disks in different ways such as FAT(File Allocation
Table), FAT 32, NTFS(New Technology File System), NTFS 5, HPFS(High Performance File System),
etc. Each formatting method configures the disk’s surface in a different manner, resulting in a different
file system – a logical method for managing the storage of data on a disk’s surface.
When a disk is formatted with standardized FAT (File Allocation Table) file system, four areas are
created on the disk. They are
1. Boot Sector : contains program that runs when the computer is started. This program
determines whether the disk has basic components that are necessary to run the operating
system successfully. If the program determines that the required files are present and the disk
has valid format, it transfers control to one of the operating system programs that continues the
process of starting up. This is process is called booting. The boot sector also contains
information that describes other disk characteristics such as the number of bytes per sector and
number of sectors per track.

Notes prepared by Shylaja B., CIT, gubbi Page 22


Computer Concepts and C Programming

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.

Notes prepared by Shylaja B., CIT, gubbi Page 23


Computer Concepts and C Programming

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.

Comparison of Hard Disk and Floppy disk


Floppy disk Hard disk
1. Capacity is limited 1.44 MB 1. Capacity range from 20 to 200+GB
2. The disk spins at 360 rpm 2. The disk spins at 3000 to 10000 rpm
3. Data access is slow 3. Fast data access
4. Very cheap 4. Expensive
5. Portable 5. Non-portable and non-removable

Removable High capacity Magnetic Disks


These combine the speed and capacity of hard disks with the portability of the floppy disks. There are
basically two types of removable high capacity magnetic disks. They are:
1. High capacity Floppy disks: also called zip disks. Have capacities ranging from 100MB to 700MB
2. How swappable Hard disks: used on high end workstations or servers that large amounts of storage.
They allow the user to remove and insert in another while the computer is still running.

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.

Optical Storage Devices


An optical storage device is a flat, circular storage media which is coated with a thin metal on which bits
may be stored in the form of highly reflective area or less reflective area. The data is read when the disc is
illuminated with a laser beam. These devices are capable of storing large amount of data in a limited
amount of space. Examples CD-ROM, DVD, Blue-Ray disks, etc.

CD-ROM(Compact Disk- Read Only Memory)


A CD-ROM is a small optical disk on which data can be stored digitally. They have shiny silver
coloured metal disk of 12 cm in diameter. The capacity of CDs ranges from 650MB to 700MB. They are
portable and handy to use.
A CD is made up of plastic polycarbonate and coated with highly reflective material. It has only
one tract the spirals from the center to the outside edge of the disk. This single track is divided into
Notes prepared by Shylaja B., CIT, gubbi Page 24
Computer Concepts and C Programming

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.

DVD-ROM( Digital Video Disk – Read Only Memory)


The DVDs look like CDs and have capable of storing full length movies on a single disk. This high
density is achieved by using both sides of the disk, special data compression technology and extremely
small tracks to store the data. Capacity of the DVDs ranges from 4.7GB to 17GB

Recordable Optical Technologies


The various popular CD and DVD technologies are
1. CD-Recordable: It allows you to record the data on CDs using CD writers.
2. CD-Re-writable (CD-RW) : these can be overwritten 100 times using CD writers
3. PhotoCD: Kodak developed this system to store digital photos in a CD.
4. DVD-R :
5. DVD-RAM: Rewritable DVDs

Solid State Storage Technologies:


These are the devices that use integrated circuits to store data. They do not have moving parts and do not
use disks or tapes. So the data access is fast. Example flash memory and smart cards.

Measuring Drive Performance


The drive performance is measured in terms of the following
1. Average access time:
Average access time is the amount of time the device takes to move its read or read/write heads to any
spot on the medium. It is an important measure of performance of storage devices and memory. It is
measured in milliseconds. For memory devices it is measured in nanoseconds. In a disk access time
depends on a combination of two factors: the speed at which a disk spins and time taken to move the
heads from one track to another. Average access times for hard disks vary from 6 to 12 ms. For CDs it
is 80 to 800ms.
2. Data Transfer rate (Throughput):
It is speed at which the device can transfer the data i.e. amount of time it takes for one device to send
data to another device. It is measured in KB per second or MB per second. For hard disks it is
15Mbps to 80Mbps. CDs have 900Kbps access time for 6x drive.

Improving Drive performance


PCs performance can slow down over a time. To improve the disk performance following disk
maintenance activities can be undertaken:
• Cleaning up unneeded files
Hundreds of temporary files will be created and used by the OS and those files will not be deleted. By
deleting these unneeded files using disk cleanup utilities the drive performance can be increased.
• Scanning a disk for errors
Due to disk error also the PC slows down. So to optimize the disk performance it is necessary to scan
the disk for errors, fix errors and recover the data lost if any. This can be done by disk scanning
utilities.

Notes prepared by Shylaja B., CIT, gubbi Page 25


Computer Concepts and C Programming

• 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.

Notes prepared by Shylaja B., CIT, gubbi Page 26


Computer Concepts and C Programming

Unit III PC OPERATING SYSTEMS


An operating system is a collection of system programs that together control the operation of computer
systems. It makes the hardware to function properly and to respond properly to the user's enquiry and
commands. Operating system manages and schedules the operation of hardware. It is the first software
layer that controls the computer's different parts.

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.

Types of Operating Systems


1. Real Time OS
These are very fast and relatively small OS. These are often embedded operating systems when
they are built into the circuitry of a device and are not loaded from the disk. A real time application is
an application which responds to certain inputs extremely quickly. These are required to run medical
diagnostic equipment, life support systems, scientific instruments etc.
2. Single User / Single Tasking OS
An OS that allows a single user to perform only one task at a time. Ex: MS-DOS and Palm OS
3. Single User / Multitasking OS
This allows a single user to perform more than one task at a time. Example: Microsoft Windows or
Macintosh operating system. With such OS productivity is increased since a number of functions are
performed simultaneously. You can run more than one application, printing, scanning etc at the same
time.
4. Mutli user / Multi tasking OS
This allows multiple users to use programs that are simultaneously running on a single network
server, called a terminal server. Examples are UNIX, VMS and mainframe operating systems such as
MVS. The disadvantage is that if the connection to the network server is broken, the user can not do
any work.

Providing a User Interface


Two types user interfaces are available (1) Graphical User Interface (2) Command line

Graphical User Interface


Most current systems such Windows, Macintosh OS and some versions of UNIX and LINUX
provide a Graphical User Interface (GUI). Graphical User Interface allows you to work with pointing
devices like mouse with graphical objects such as windows, menus, icons, buttons, tool bars and other
tools. GUI enables you to issue commands to the computer using visual objects instead of typing
commands.

Command Line Interface

Notes prepared by Shylaja B., CIT, gubbi Page 27


Computer Concepts and C Programming

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.

Working with Device Drivers


In addition to providing Interrupts, the OS often provides programs for working with special
devices such as printers. These programs are called drivers because they allow the operating system and
other programs to activate and use i.e. drive the hardware.

Enhancing an OS with Utility Software


The Utility programs enhance or extend the operating system’s capabilities or simply offer new
features not provided by the operating system itself. The most popular utilities are (1) Backup utilities (2)
Antivirus (3) Firewall (4) Intrusion detection (5) Screen savers etc.

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-

Notes prepared by Shylaja B., CIT, gubbi Page 28


Computer Concepts and C Programming

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 2000 Professional


Released in 2000, Windows 2000 combines the user friendly interface and features of Windows 98
with the file system, networking, power and stability of Windows NT.

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.

Macintosh Operating System


This works only Macintosh machines. Though this is a disadvantage it is popular among
publishers, multimedia developers, and graphic artists. The latest is called Mac OS system X.
UNIX for the Desktop
UNIX is used in some high power workstations. Not so popular due to its command line interface
in spite of its power and stability.
Features of UNIX:
o Multi user and multi tasking OS
o It is a layered OS with multiple levels of security and access control
Linux for the Desktop
Linux is considered as a free ware operating system and hence cheap. It has impressed industry
experts by its power, capabilities and rich feature set. It is a full 32 bit Multi tasking operating system that
supports multiple users and multiple processors. Linux uses a command line interface but windows based
GUI is also available. Red Hat and Novell are popular vendors who offer Linux with many utilities.
Features of Linux:
o It is a multi user, multi tasking and multi processing o.s.
o It is a full 32 bit o.s. and can run on any computer

o It supports both command line and graphical user interface


o Freely available to use, modify and redistribute
o Has good security features and reliable

Notes prepared by Shylaja B., CIT, gubbi Page 29


Computer Concepts and C Programming

Network Operating Systems


A network operating System is an OS that is designed to run on a network server dedicated to
providing various services to other computers (client) on the network. The various OSs for network
servers are (1) Windows NT Server (2) Windows 2000 server (3) Windows server 2003 (4) Novell
Netware (5) Unix for servers (6) Linux for servers.

Embedded Operating System


An embedded operating system is one that is built into the circuitry of an electronic device, unlike
PCs operating system which resides on a magnetic disk. Now these are available in wide variety of
devices like appliances, automobiles, bar code scanners, cell phones, medical equipment and PDAs. The
popular embedded operating systems are Windows XP embedded, Windows CE .NET, Palm OS, Pocket
PC OS and Symbian.

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

Notes prepared by Shylaja B., CIT, gubbi Page 30


Computer Concepts and C Programming

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.

Common Types of Networks


1. LAN (Local Area Network)
LAN is a network of computers confined to a small area such as a building or a campus consisting of
group of buildings. The computers that are part of the network are basically meant for exchanging
information. The maximum distance between two computers in LAN is around d 10 Kms. The error rate
involved in LAN is lower and they operate at high speeds. Major advantage of LAN is sharing resources
such as printers, modems, data storage units, etc. Another important purpose of using LAN is to transfer
data, documents and messages to several departments within an organization. LAN may have servers,
that are the computers exclusively used for providing hardware and software resources. Selecting a
suitable media for LAN is very important. Twisted pair cables, Coaxial cables, optical fibres, etc are used
as the communicating media.
Advantages:
a. Accurate and Higher data transfer
b. Device sharing
Disadvantages:
a. Cost
b. Accurate communication is not possible if the distance is more. LAN is error prone as the
distance increases more than 2KMs
2. WAN (Wide Area Network)
It is a network of computers generally across a wide geographical area. For example, a company
may have its corporate head quarters and manufacturing plant in one city and its marketing office in
another. Each site needs resources, data and programs locally but it also needs to share the data with
others sites. To accomplish this, the company can create a WAN. Communication is mostly through
telephone or satellite links.
Advantages:
a. Communication is possible over a wide geographical area
b. Data transmission is reliable
Disadvantages:
a. Have very low band width
b. Communication is slow because of large distance and low band width
c. Costlier compared to LAN

Difference between LAN and WAN


LAN WAN
a. Interconnection within a building or camps a. Interconnection across cities and countries
b. Higher data transfer rate b. Slow data transfer rate
c. Error is less c. Error rate is slightly higher
d. Reliable and less expensive d. Reliable but very expensive
e. Communication is through cables e. Through telephone lines or satellite links

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

Notes prepared by Shylaja B., CIT, gubbi Page 31


Computer Concepts and C Programming

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.

Network Topologies and Protocols


Topology is the logical layout of the cables and devices that connect the nodes of the network. Network designers
consider several factors when deciding which topology or combination of topologies to use. They include type of
computers and cabling, distance between computers, the speed at which the data must travel and the cost of setting
up the network. A network’s topology and related technologies are important for two reasons: First, a correctly
designed network using the most appropriate topology for the organization’s needs, will move the data packets
efficiently as possible. Second, the network’s topology plays a role in preventing collisions, which is what happens
when multiple nodes try to transmit data at the same time. Their packets can collide and destroy each other.

Following are the different topologies used in the computer network.


1. Bus topology
In this network, a single bus connects all the nodes. At the end of the bus, terminators are
connected to indicate the end of the network. To avoid contention problem, the corrupted data due to
collision is simply abandoned. It is the earliest data communication network used, where the host node at
one end communicates with several nodes attached.

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.

Notes prepared by Shylaja B., CIT, gubbi Page 32


Computer Concepts and C Programming

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

Notes prepared by Shylaja B., CIT, gubbi Page 33


Computer Concepts and C Programming

Network Hardware

1. Network Interface Card (NIC)


It is the first contact between the machine and the network. It is fixed to the free slot of the motherboard. It
provides a port to which the network cable can be connected. The cable in turn can be connected to various
devices in the network so that they can communicate
2. Hub
It is a small box to which various devices are connected so that they can communicate with each other. It
gathers signals from various network devices, amplify them and send them to the connecting devices.
3. Bridges
A device that connects two or more LANs is called a bridge. It regenerates the signals and then forwards the
data from one LAN to another.

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

Notes prepared by Shylaja B., CIT, gubbi Page 34


Computer Concepts and C Programming

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.

Internet’s Major Services


The internet acts as a carrier for several different services, each with its own distinct features and purposes. The
most commonly used services are
1. WWW
To visit websites and browse web
2. Email
To send and receive written messages, documents, photos, etc
3. News
To participate in public bulletin board service, send response and post articles
4. File Transfer Protocol
To perform remote file transfers from one computer to another
5. Internet Relay Chat
To participate in discussion groups with users of chat groups
6. Instant Messaging
To chat with specific users or chat privately
7. Online services
To log into internet services on subscription basis
8. Peer-to-peer services
To allow searching and sharing of files of all types by accessing each other’s computer

WWW (World Wide Web)


World Wide Web was created in 1989 at European Particle Physics Lab in Geneva, as a method for
incorporating footnotes, figures, cross references into online documents. It is a wide area hypermedia
information retrieval initiative to give universal access to a large universe of documents. The World Wide
Web is the graphical, multimedia portion of the Internet. To view files on the Web, you need Web
browsing software. The Internet Explorer browser is part of Windows 98. You use a browser to view
different locations on the Web, which are known as Web pages. A group of Web pages is a Web site.

Notes prepared by Shylaja B., CIT, gubbi Page 35


Computer Concepts and C Programming

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.

Notes prepared by Shylaja B., CIT, gubbi Page 36


Computer Concepts and C Programming

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.

Unit IV Algorithms and Flow Charts


Problem solving with Computers
As we know that the computer has no common sense, it is just an obedient servant, so a lot of
preparatory work concerned with problem solving has to be done before handing over the work to the
computer. The computer always demands unambiguous (non-confusing) definition of the problem, which
is simple to carry out and straight forward to implement in order to solve the problem. At this level the
user or programmer assumed to have certain amount of background knowledge, reasoning skills and
hints for problem solving.

Steps involved problem solving using computers


• Make a closer study of given problem and analyze it
• Redefine the problem if necessary such that it should reveal clearly what is to be done
• Specify what is expected as an outcome of processing i.e. the result
• Find a suitable solution method to solve the given problem
• Based on above analysis, formulate a set of steps or procedural steps (known as
Algorithm) of the chosen method of solution.
• Express the algorithm in precise notation and feed it to START
computer and compute the results and reevaluate it.
• Repeat the above steps till you get correct solution of given INPUT
problem A,B,C

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

Notes prepared by Shylaja B., CIT, gubbi Page 37


Computer Concepts and C Programming

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.

Algorithm to add 3 numbers and prints sum and average.


Step 1. [First input the 3 numbers]
Input a, b, c
Step 2. [Finding the sum of given numbers]
Sum <-- (a+b+c)
Step 3. [Finding the average]
Average <--- sum/3.0
Step 4. [Print the results]
Write sum, average
Step 5. [End of the algorithm]
End

Flowchart: - to find sum and average of three numbers

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.

For example, analyze the mathematical formula given below


Y = PX3 + QX2 + RX + S
The above statement can be written as C - statement as below
Y= (P*X*X*X)+(Q*X*X)+(R*X)+S;
But to execute the above statement, the computer has to do six multiplications and three additions. We
can modify the above formulas as below i.e.
===> Y=X (PX2+QX+R)+S
===> Y=X (X(PX+Q)+R)+S
In C-statement, this can be written as Y= X* (X* ((P* X) +Q) +R) +S.
Now there is only 3 multiplication and 3 additions. Therefore the above statement is more efficient and
takes less time for execution.
Let us consider another example: A = log (B2)-log (C2) ----- (1)
In C-statement: A = log (B*B)-log(C*C);
But the equation (1) can be reduced as below: -
A = log (B2)-log (C2)

Notes prepared by Shylaja B., CIT, gubbi Page 38


Computer Concepts and C Programming

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.

The computing speed decreases as we go from operations additions, subtractions, multiplication,


divisions, power( ) functions, logarithmic calculations, trigonometric functions and other mathematical
functions. Therefore one should try to replace slow operations by faster operations as far as possible.
For examples:
Replace pow (x, 3) by x*x*x
Replace 3*y by y+y+y
Replace n/2.0 by n*0.5
Also try to avoid the repetitions of operations.
For example:
Repeated operations ( slow) more efficient (fast)
sum = a + b + c + d sum = a + b + c + d
avg = ( a + b + c + d ) / 4.0 avg = sum/4.0

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.

Basic Control structures in Algorithms


Usually the algorithm consists of finite set of sequential procedural steps. The algorithm may have
conditions, which are used to take decision, and depending upon decisions, a particular group of
statements is selected for execution. There are also situations in which some of the statements have to
execute repeatedly. So to meet above situations of problem solving, algorithm uses 3 basic forms of
control structures:

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


Step 2: [Multiply given numbers and store the result in another variable]
Mult  n1*n2*n3
Step 3: [Add all numbers and store the sum in another variable]
Sum  n1+n2+n3
2) In Flowchart:

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:

Notes prepared by Shylaja B., CIT, gubbi Page 40


Computer Concepts and C Programming

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

Step 1: [Input a number]


Input N START
Step 2: [Initialize the variable sum to zero]
Sum  0
Step 3: [calculate the sum by looping]
Do INPUT N
Sum  Sum+N
N  N-1
while N>0
Step 4: [Print the sum of numbers] S0
Write Sum
Step 5:[End of the algorithm]
End S  S+N
2) In Flowchart :
3) In C programs:
main() N  N-1
{
int n,sum=0;
do
{
sum+=n; IS N>0
n--;
} while(n>0);
printf(“\n The sum is %d”,sum);
} PRINT S
Notes prepared by Shylaja B., CIT, gubbi Page 41

END
Computer Concepts and C Programming

Flow charts symbols:

Sl.No. Symbol Meaning

1 Start and End of flowchart

2 Represent input and output operations.

Assignment operations and other computational


3
operations.

Connectors for different boxes of flowchart and shows the


4
direction of execution.

Conditions tested. Based on results path is selected. Also


5
called as test box.

6 Comment.

Connectors for connecting two parts of flowcharts.


7

8 Used to indicate predefined process like to functions in C.

9 Manual task.

10 Repetitions of statements mainly for “for loop”.

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

15 Printed sheets or documents.

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.

Some examples on Algorithms and Flowcharts:


1) Write and algorithm to accept temperature in Fahrenheit scale and convert into Celsius scale
and draw a flowchart.

Formula:- C = (F-32)/1.8 where F is Fahrenheit value and C START is


Celsius value.

Algorithm : Temperature conversion from Fahrenheit value to


Celsius value. READ FARH
Step 1: [Input temperature in Fahrenheit scale]
Input F
Step 2: [Compute centigrade temperature]
C  (F-32)/1.8
Step 3: [Print the result]
Write “Equivalent temperature in Celsius scale is “,C CENTI  (FARH-32)/1.8
Step 5: [End of algorithm]
End

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

If b > big then big  b


Step 4: [Compare second value with big]
If c > big then big  c
Step 5: [Print the results]
Write “Biggest number is “,big
Step 6: [End of the algorithm]
End

Flowchart for biggest of three numbers.

Notes prepared by Shylaja B., CIT, gubbi Page 44


Computer Concepts and C Programming

START

READ A,B,C

BIG  A

IS B > BIG BIG  B

IS C > BIG BIG  C

PRINT BIG

STOP

3) Write an algorithm to find the factorial of a number and also draw the flowchart.

Algorithm : To find the factorial of a given number


Step 1: [Input the number ]
Input N
Step 2: [Initialize the factorial number to 1]
Fact  1
Step 3: [ Calculate factorial by looping]
Repeat for I=1 to N steps 1
Fact  Fact * I
Loop

Notes prepared by Shylaja B., CIT, gubbi Page 45


Computer Concepts and C Programming

Step 4: [Print the factorial value]


Write “Factorial of “,N,” is”,fact
Step 5: [End of the algorithm]
End

Flowchart to find the factorial value of given number

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”

Step 3: [End of algorithm]


End.

Notes prepared by Shylaja B., CIT, gubbi Page 46


Computer Concepts and C Programming

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.

About ANSI C Standard


For many years, the de facto standard for implementing the language has been the original C
Reference Manual by Kernighan and Ritchie published in 1978. During these years, C has undergone
many changes. Numerous different features and facilities have been developed and added. This has
resulted in minor problems in portability. Consequently, the American National Standards Institute
defined a standard for C, eliminating much uncertainty about the exact syntax of the language. This
newcomer, called ANSI C, proclaims itself the standard version of the language. As such it will inevitably
overtake, and eventually replace common C. ANSI C does incorporate a few improvements over the old
common C. The main difference is in the grammar of the language. The form of function declarations has
been changed making them rather more like Pascal procedures. The most important ANSI additions are:
1. A new format for declaring and defining functions.
2. Facility for doing floating point computations.
3. Two new type qualifiers const and volatile and two new data type enum and void have been
introduced.
4. The proprocessor includes some new macros.
5. A standard ANSI C library has been defined.

Important features of C Language


1. C is a system programming language which provides flexibility for writing compilers, operating
systems, etc.
2. It can also be used for writing the application programs for scientific, engineering and business
applications.
3. C is famous for its portability, meaning that program written in C for one computer can be easily
loaded to another computer with little or no changes.
4. C supports variety of data types like integers, float point numbers, characters, etc.
5. C is a procedure oriented language which is most suited for structured programming practice.
6. It provides a rich set of built in functions
7. Programs written in C are found to execute faster than compared to other languages.

Notes prepared by Shylaja B., CIT, gubbi Page 47


Computer Concepts and C Programming

Structure of the C Language


The general structure of the C language includes the following sections

Documentation Section Example Program

Preprocessor Directive or Link Section


/* Sample C Program */
Global Declaration Section
main()
main() Function Section {
{ int a,b;
Declaration Part
clrscr();

Executable Part printf(“Enter two numbers”);


} scanf(“%d%d”, &a,&b);

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

Notes prepared by Shylaja B., CIT, gubbi Page 48


Computer Concepts and C Programming

System Ready

Program Code Enter program


Source Program
Edit Source program

Compile Source
C Compiler program

Syntax
Errors
?
Object Code

System Library Link with System Library

Executable Object Code

Input Data Execute 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.

Important points to remember:


1. Every C program requires a main() function. Use of more than one main() is illegal. The place of
main() is where the program execution begins.
2. The Execution of the function begins at the opening brace and ends at the closing brace.

Notes prepared by Shylaja B., CIT, gubbi Page 49


Computer Concepts and C Programming

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.

LEXICAL ELEMENTS OF THE C LANGUAGE

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.

2. Floating point Constants or Real Constants


The quantities that are represented by numbers with fractional part are called floating point numbers. Ex:
0.567, -0.76, 56.78, +247.60. These numbers are shown in decimal notation , having a whole number
followed by a decimal point and the fractional part. It is possible to omit digits before the decimal point or
digits after the decimal point. Ex: 215., .95, -.76 or +.5
A real number or a floating point number can also expressed as in exponential notation. Ex: 2.15E2. The
general form of exponential notation is
mantissa e exponent or mantissa E exponent
The mantissa is either a real number or an integer. The exponent is an integer with an optional plus or
minus sign. Embedded white is not allowed in this notation.

3. Single Character constants


A single character constant contains a any valid character enclosed within a pair of single quote marks.
Ex: ‘5’, ‘A’, ‘;’ ‘ ‘. The character constants have integer values associated with them known as ASCII
values. For ex: A is having the ASCII value of 65.

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”

5. Backslash character constants or Escape sequence characters.


C supports some special backslash character constants that are used in output functions. For ex: ‘\n’
stands for new line characters. Each one of them represents a single character even though it consists of
two characters.
\a Audible alert or bell \b back space
\f form feed \n new line
\r carriage return \t horizontal tab

Notes prepared by Shylaja B., CIT, gubbi Page 51


Computer Concepts and C Programming

\v vertical tab \’ single quote


\” double quote \? Question mark
\\ backslash \0 null

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.

Rules to be followed for constructing the Variable names(identifiers)

1. They must begin with a letter and underscore is considered as a letter.


2. It must consist of single letter or sequence of letters, digits or underscore character.
3. Uppercase and lowercase are significant. For ex: Sum, SUM and sum are three distinct variables.
4. Keywords are not allowed in variable names.
5. Special characters except the underscore are not allowed.
6. White space is also not allowed.
7. The variable name must be 8 characters long. But some recent compilers like ANSI C supports 32
characters for the variable names and first 8 characters are significant in most compilers.

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:

int Data Type


Integer refers to a whole number with a range of values supported by a particular machine. Generally
integers occupy one word of storage i.e 16 bits or 2 bytes. So its value can range from -32768 to +32767.
Declaration: int variable name;
Ex: int qty;
The above declaration will allocate a memory location which can store only integers, both positive and
negative. If we try to store a fractional value in this location, the fractional data will be lost.

float Data Type


A floating point number consists of sequence of one or more digits of decimal number system along with
embedded decimal point and fractional part if any. Computer allocates 32 bits, i.e. 4 bytes of memory for
storing float type of variables. These numbers are stored with 6 digits of precision for fractional part.
Declaration: float variableName; Ex : float amount;

double Data Type

Notes prepared by Shylaja B., CIT, gubbi Page 52


Computer Concepts and C Programming

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;

char Data Type


A single character can be defined as char data type. These are stored usually as 8 bits i.e 1 byte of
memory.
Declaration : char variableName ; Ex: char pass;
String refers to a series of characters. Strings are declared as array of char types.
Ex: char name[20]; will reserve a memory location to store upto 20 characters.

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.

Size and range of data types on a 16 bit Machine


Type Size (bits) Range
char or signed char 8 -128 to 127
unsigned char 8 0 to 255
int 16 -32768 to 32767
unsigned int 16 0 to 65535
short int or signed short int 8 -128 to 127
unsigned short int 8 0 to 255
long int or signed long int 32 -2,147,483,648 to
2,147,483,647
unsigned long int 32 0 to 4,294,967,295
float 32 3.4e-38 to 3.4e+38
double 64 1.7e-308 to 1.7e+308
long double 80 3.4 e-4932 to 1.1e+4932

Assigning Values to Variables


Values can be assigned to variables using assignment operator “=”.
Syntax:
Variablename = value;
Ex: a = 10; intialvalue = 0;
It is also possible to assign a value to a variable at the time the variable is declared. The process of
giving initial value to the variable is called initialization of the variable.
Ex:
int a=10, b=5;
float x=10.5, y=1.2e-9

Declaring a variable as constant


We may want the value of the certain variable to remain constant during the execution of the program. We can
achieve this by declaring the variable with const qualifier at the time of initialization.
Ex;
const int tax_rate = 0.30;
The above statement tells the compiler that value of variable must not be modified during the execution of the
program. Any attempt change the value will generate a compile time error.

Declaring a variable as volatile


Notes prepared by Shylaja B., CIT, gubbi Page 53
Computer Concepts and C Programming

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

Notes prepared by Shylaja B., CIT, gubbi Page 54


Computer Concepts and C Programming

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

Notes prepared by Shylaja B., CIT, gubbi Page 56


Computer Concepts and C Programming

The operator % cannot be used with real operands.

Mixed- mode Arithmetic


When one of the operands is real and the other is integer, the expression is called a mixed-mode arithmetic
expression. If either operand is of the real type, then only the real operation is performed and the result is always a
real number.
Thus 15/10.0=1.5 where as 15/10=1

Arithmetic operator’s precedence:-


In a program the value of any expression is calculated by executing one arithmetic operation at a time. The order in
which the arithmetic operations are executed in an expression is based on the rules of precedence of operators.
The precedence of operators is :
Unary (-) FIRST

Multiplication(*) SECOND
Division(/) and (%)

Addition(+) and Subtraction(-) LAST


For example, in the integer expression –a *b/c+d the unary- is done first, the result –a is multiplied by b, the product
is divided by c(integer division) and d is added to it. The answer is thus:
-ab/c+d

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..

For example, in 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

Notes prepared by Shylaja B., CIT, gubbi Page 57


Computer Concepts and C Programming

Increment and Decrement operators:-


The increment operator ++ and decrement operator – are unary operators with the same precedence as the unary
-, and they all associate from right to left. Both ++ and – can be applied to variables, but no to constants or
expressions. They can occur in either prefix or postfix position, with possibly different effects occurring. These
are usually used with integer data type.
The general syntax is:
++variable or --variable or variable++ or variable—
Some examples are
++count -kk index++ unit_one--

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

4.5 < 10 FALSE


-35 >= 0 FALSE
10 < 7+5 TRUE
a+b == c+d TRUE only if the sum of values of a and b is equal to the sum c & d.

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

Some examples of the usage of logical expressions are:


1. If(age>55 && salary <1000)
2. If (number<0 || number>100)
Relational and logical expressions:
We have seen that float or integer quantities may be connected by relational operators to yield an answer which is
true of false.
For example the expression,
Marks>=60
would have an answer true if marks is greater than or equal to 60 and false if marks is less than 60. The result of the
comparison (marks>=60) is called a logical quantity. C provides a facility to combine such logical quantities by
logical operators to logical expressions. These logical expressions are useful in translating intricate problem
statements.
Example : A university has the following rules for a student to qualify for a degree with Physics as the main subject
and Mathematics as the subsidiary subject:
(i) He should get 50 percent or more in Physics and 40 percent or more in Mathematics.
(ii) If he gets less than 50 percent in Physics he should get 50 percent or more in Mathematics.
He should get atleast 40 percent in Physics.
(iii) If he gets less than 40 percent in Mathematics and 60 percent or more in Physics he is
allowed to reappear in an examination in Mathematics to qualify.
(iv) In all the other cases he is declared to have failed.

/*This program implements above rules*/


include<stdio.h>
main()
Notes prepared by Shylaja B., CIT, gubbi Page 59
Computer Concepts and C Programming

{
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*/

Precedence of relational operators and logical operators:


Example:
(a>b *5) &&(x<y+6)

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 .

In general within parentheses:


1. The unary operations, namely, -,++,--,! (logical not) are performed first.
2. Arithmetic operations are performed next as per their precedence.
3. After that the relational operations in each sub expressions are performed, each sub expression
will be a zero or non _ zero. If it is zero it is taken as false else it is taken as true.
4. These logical values are now operated on by the logical operators.
5. Next the logical operation && is performed next.
6. Lastly the evaluated expression is assigned to a variable name as per the assignment operator.
The conditional operator:
An operator called ternary operator pair “?:” is available in C to construct conditional expressions of the form.
exp1? exp2: exp3;
where exp1,exp2, and exp3 are expressions.
The operator ?; works as follows: exp1 is evaluated first. If it is nonzero(true), then the expression exp2 is evaluated
and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the
expression. Note that only one of the expressions(either exp2 or exp3) is evaluated.
For example, consider the following statements
x=3;
y=15;
z=(x>y)?x:y;
In this example, z will be assigned the value of b. This can be achieved using the if..else statements as follows:
If (x>y)
z=x;
else
z=b;

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

Notes prepared by Shylaja B., CIT, gubbi Page 60


Computer Concepts and C Programming

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;

Notes prepared by Shylaja B., CIT, gubbi Page 61


Computer Concepts and C Programming

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();
}

Precedence and Associativity of operators:


Each operator in C has a precedence associated with it. This precedence is used to determine how an expression
involving more than one operator is evaluated. The operator at the higher level of precedence are evaluated first.
The operators of the same precedence are evaluated either from left to right or from right to left depending on the
level. This is known as the associativity property of an operator.

Operator Description Level Associativity


Parenthesis
()
Array index 1 L–R
[]
+ Unary plus
- Unary minus
++ Increment
-- Decrement
2 R–L
! Logical negation
~ One’s Complement
& Address of
sizeof(type) type cast conversion
* Multiplication
/ Division 3 L- R
% Modulus
+ Addition
4 L–R
- Subtraction
<< Left Shift
5 L–R
>> Right Shift
< Less than
<= Less than or equal to
6 L–R
> Greater than
>= Greater than or equal to
== is equal to
7 L–R
!= Not equal to
& Bitwise AND 8 L–R
^ Bitwise XOR 9 L–R
| Bitwise OR 10 L–R
&& Logical AND 11 L–R
|| Logical OR 12 L–R
?: Conditional Operator 13 R–L
=, Assignment operator
14 R–L
+=, -=, *=, /=, %= Short hand assignement
, Comma operator 15 R–L

Evaluation of expressions involving all the above type of operators:


The following expression includes operators from six different precedence groups.

Notes prepared by Shylaja B., CIT, gubbi Page 62


Computer Concepts and C Programming

Consider variables x, y , z as integer variables.


Z+=(x0>0 && x<=10) ? ++x : x/y;
The statement begins by evaluating the complex expression
(x>0 && x<=10)
If this expression is true, the expression ++x is evaluated. Other wise, the a/b is evaluated. Finally, the assignment
operation(+=) is carried out, causing the value of c to be increased by the value of the conditional expression.
If for example x, y, and z have the values 1,2,3 respectively, then the value of the conditional expression will be
2(because the expression ++a will be evaluated), and the value of z will increase to 5(z=3+2). On the other hand, if
x,y and z have the values 50,10,20 respectively, then the value of the conditional expression will be 5(because the
expression x/y will be evaluated) and the value of z will increase to 25(z=20+5).

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

Notes prepared by Shylaja B., CIT, gubbi Page 63


Computer Concepts and C Programming

#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”

Notes prepared by Shylaja B., CIT, gubbi Page 64


Computer Concepts and C Programming

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

Input and Output Functions


The C language consists of input-output statements to read the data to be processed as well as output the computed
results. C language provides a set of library functions or built in functions, in order to carry out input and output
operations. These library functions are available in a header file called stdio.h. So for using these library functions
the following preprocessor directive is essential
# include <stdio.h>
The input and output functions in C language can be broadly categorized into two types:
1. Unformatted Input Output functions : which provides the facility to read or output data as a characters
or sequence of characters. Ex: getch(), getche(), getchar(), gets(), putch(), purchar() and puts().
2. Formatted I/O functions : which allow the use format specifiers to specify the type of data to be read or
printed. Ex: scanf() and printf() functions.
scanf function:-
The function scanf() is used to read data into variables from the standard input, namely a keyboard. The general
format is:
scanf(format-string, var1,var2,………varn)
Where format-string gives information to the computer on the type of data to be stored in the list of variables
var1,var2……varn and in how many columns they will be found
For example, in the statement:
scanf(“%d %d”, &p, &q);
The two variables in which numbers are used to be stored are p and q. The data to be stored are integers. The
integers will be separated by a blank in the data typed on the keyboard.
A sample data line may thus be:
456 18578
Observe that the symbol &(called ampersand) should precede each variable name. Ampersand is used to indicate
that the address of the variable name should be found to store a value in it. The manner in which data is read by a
scanf statement may be explained by assuming an arrow to be positioned above the first data value. The arrow
moves to the next data value after storing the first data value in the storage location corresponding to the first
variable name in the list. A blank character should separate the data values.
The scanf statement causes data to be read from one or more lines till numbers are stored in all the specified
variable names. No that no blanks should be left between characters in the format-string. The symbol & is very
essential in front of the variable name. If some of the variables in the list of variables in the list of variables in scanf
are of type integer and some are float, appropriate descriptions should be used in the format-string.
For example:
scanf(“%d %f %e”, &a , &b, &c);

Notes prepared by Shylaja B., CIT, gubbi Page 65


Computer Concepts and C Programming

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.

Example to indicate how printf() displays answers.

/*Program illustrating printf()*/


# include<stdio.h>
main()
{
int a= 45, b= 67
float x=45.78 , y=34.90
printf(“Output:\n”);
printf(“1,2,3,4,5,6,7,,8,0\n”);
printf(“\n”);
printf(“%d, %d,,%f ,%f \n” , a,b,x,y);
printf(“\n”);
}

Output:

1,2,3,4,5,6,7,8,9,0

45,67,45.78,34.90

Example for illustrating scanf and printf statements:


/* Program for illustrating use of scanf and printf statements */
#include<stdio.h>
main()

Notes prepared by Shylaja B., CIT, gubbi Page 66


Computer Concepts and C Programming

{
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

Formatted input and output using format specifiers:


The function scanf is the input analog of printf, providing many of the same conversion facilities in the opposite
direction.
int scanf (char *format, …..)
scanf reads characters from the standard input, interprets them according to the specification in format, and
stores the results through the remaining arguments. The format argument is described below; the other
arguments, each of which must be a pointer, indicate where the corresponding converted input to be stored.

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).

Conversion characters are shown in the table below:

CHARACTER INPUT DATA


d decimal integer
i integer. The integer may be in octal (leading 0)
or hexadecimal (leading 0x or 0x)
o octal integer(with or without leading zero);
u unsigned decimal integer;
x hexadecimal integer (with or without leading ox or ox)
c character

Notes prepared by Shylaja B., CIT, gubbi Page 67


Computer Concepts and C Programming

s character string (not quoted)


e,f,g floating-point number with optional sign, optional
decimal point and optional exponent;
% literal %; no assignment is made.

The output function printf translates internal values to characters.


The general syntax is
int printf (char *format, arg1,arg2…………..)
printf converts, formats, and prints its arguments on the standard output under control of the format. It returns
the number of characters printed.

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.

CHARACTER ARGUMENT TYPE


d,i int; decimal number
o int; unsigned octal number(without a leading zero)
x, x int; unsigned hexadecimal number(without a
leading ox or OX), using abcdef or ABCDEF for 10….15

u int; unsigned decimal number


c int; single character.
s char *; print characters from the string until a‘\o’ or the number
characters given by the precision.
F double; [-] m.dddddd, where the number of d’s is given by the precision(default 6)

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.

P void *; pointer(implementation-dependent Representation).


% no argument is converted ; print a %

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”.

:%s: :hello, world:


:%10s: :hello, world:

Notes prepared by Shylaja B., CIT, gubbi Page 68


Computer Concepts and C Programming

:%.10s: :hello, wor:


:%-10s: :hello, world:
:%.15s: :hello, world:
:%-15s: :hello, world:
:%15.10s: : hello, wor:
:%-15.10s: :hello, wor :

The getchar( ) function


Single characters can be entered into the computer using the C library function getchar. The getchar function is a
part of the standard C I/O library. It returns a single character from a standard input device typically a keyboard.
The function does not require any arguments, though a pair of empty parentheses must follow the word getchar.

The general syntax


Character variable=getchar();
Where character variable refers to some previously declared character variable.
Example:
A C program contains the following statements
char c;
…………….
C=getchar();
The first statement declares that c is a character-type variable. The second statement causes a single character to be
entered from the standard input device and then assigned to c.
If an end-of-file condition is encountered when reading a character with getchar function, the value of the symbolic
constant EOF will automatically be returned. (This value will be assigned within the stdio.h file. Typically, EOF
will be assigned the value -1, though this may vary from one compiler to another).
The getchar function can also be used to read multi character strings, by reading one character at a time
within a multi pass loop.

The putchar( ) function:


Single characters can be displayed using the C library function putchar. This function is complementary to the
character input function getchar. The putchar function, like getchar, is a part of the standard C I/O library. It
transmits a single character to a standard output device. The character being transmitted will normally be
represented as a character type variable. It must be expressed as an argument to the function, enclosed in
parentheses, following the word putchar.
The general syntax is
putchar(character variable)
where character variable refers to some previously declared character variable.

A C program contains the following statements


Char c;
………
putchar(c);

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);
}

Notes prepared by Shylaja B., CIT, gubbi Page 70