Sei sulla pagina 1di 130

MANGALORE

COMPUTER CONCEPTS AND C


PROGRAMMING
Prepared by:
SUSHMA SHETTY
B.E.
sushma.shetty305@gmail.com

This notes is been circulated on self risk. Nobody can be held responsible if anything is wrong or any improper information or
insufficient information provided in it.

References:
Computer concepts and C programming techniques by Padma Reddy, The C Programming Language by
Brian Kernighan and Dennis Ritchie, www.tutorialspoint.com, www.programmingsimplified.com,
www.programiz.com, www.wikipedia.org.
Visit www.vtulife.com for all vtu notes, syllabus,
question papers and placement materials.


Prepared By: Sushma Shetty
1 www.vtulife.com


UNIT 1

INTRODUCTION TO COMPUTER
SYSTEMS
COMPUTER:
A computer is an electronic device that is used to accept the data, process the data and give the desired
output in human understandable language.
Computer Tasks:
Accept the data, Process or manipulate the data, Output the result in the form suitable for human
understanding, Stores the input data, instructions and results.
Example:
PC, Laptop, Desktop, PDA.
FEATURES/ CHARACTERISTICS OF COMPUTERS:
1. Speed: Measured in MIPS (Millions of Instructions Per Second). Present digital computer speed
is measured in terms of BIPS (Billions of Instructions Per Second).
2. Accuracy: Computer results are very accurate.
3. Reliability: Computer provides correct and consistent results everytime.
4. Storage Capability: hard disk, USB storage.
5. Versatility: Computers can perform many tasks based on the instructions feeded in it.
6. Diligence: Computers can continuously perform tasks without any break.
EVOLUTION OF COMPUTERS


Prepared By: Sushma Shetty
2 www.vtulife.com


ABACUS/ COUNTING FRAME:
Calculating tool used for performing various arithmetic operations such as addition, subtraction,
multiplication, division.
PASCALINE:
Pascals device Pascaline is also called as the numerical wheel calculator and is one among the worlds
first mechanical adding machines that could add/ subtract directly.
DIFFERENCE ENGINE:
Invented by Charles Babbage. It consists of a number of columns numbered from 1 to N. this is used to
perform mathematical operations.
ENIAC (Electronic Numerical Integrator And Computer):
First electronic digital computer used to solve full range of computing problems. The disadvantage is
that instructions were given to this computer by physically connecting the wires and using the switches.
EDVAC (Electronic Discrete Variable Automatic Computer):
It is used for various calculations in the preparation of hydrogen bomb. Unlike ENIAC, instead of using
wires and switches, stored program concept is used i.e storing data and instructions in memory. It does
automatic addition, subtraction, multiplication, division with fast memory. Disadvantage is that it uses
much power and has a huge size.
IBM PERSONAL COMPUTER:
IBM (International Business Machine) PC more popularly used by common people. Size of the machine
drastically reduced, less power consumption, memory was used for storing data.
BASIC PARTS OF A COMPUTER
1. Input devices
2. Output devices
3. System unit
4. Storage devices
INPUT DEVICES:
These devices allow the user to enter the data, commands, programs into the memory of the computer
ie input to the computer. Eg: Keyboard, Mouse, scanner, digital camera etc.
OUTPUT DEVICES:
These devices are used to display the information generated by the computer to the user in human
understandable language. Eg: Monitor, Printer, Speakers etc.
STORAGE DEVICES:
These are the devices which store the data, instructions and information fed to the computer. These
data can be retained even when the computer is turned off. Eg: CD, DVD, floppy disk drive, CD-ROM,
RAM, ROM, DVD-ROM etc.

Prepared By: Sushma Shetty
3 www.vtulife.com


SYSTEM UNIT:
It is a box like case which consists of a motherboard and other electronic devices. The motherboard
consists of two components namely Central Processing Unit (CPU) and memory. All these components
which reside inside the system are internal devices.
The various units are classified based on the visibility:
1. Units that are visible from the front end.
2. Units that visible from the back end.
3. Units that are inside the system unit.
Visible from front end:
1. Power switch: Used to switch on and off the computer.
2. Reset button: Using this we can restart the computer.
3. Lights: Indicates read/write operation being performed on the hard disk.
4. Floppy disk drive: a slit into which floppy disk can be inserted. We can read or write the data
into the floppy disk.
5. DVD/CD combo drive: Allows to read the data and write the data into CD.
Visible from back end:
Components of a computer are connected to the CPU using set of wires. These devices are connected
using ports. The interfaces through which data can be sent to or received from the CPU are called as
ports. The commponly used ports are:
1. Power point: It is not a port but the place where the power plug has to be connected.
2. Mouse port: where the mouse has to be connected.
3. Keyboard port: where the keyboard is connected.
4. USB ports: The devices such as camera, pen drive, printers, memory sticks can be connected.
5. Parallel port: Older printers can be connected. New printers are normally connected to the USB
port.
6. Serial port: External modems are connected.
7. Audio output: Used to connect head phones.
8. MIC (Microphone) port
9. TV Port
10. Monitor/Video port: used to connect the monitor.
11. Modem port: used to connect phone line using modem to access internet.
12. Speaker port: To connect home stereo system.
Inside the system unit:
1. Mother board: it contains computers basic circuitry and other components of the computer. It
contains connectors for attaching additional boards or cards.
2. CPU (Central Processing Unit): Looks like a chip or a mother board. It is called as the brain of the
computer and is responsible for processing the data accurately for correct input. It has ALU
(Arithmetic and Logic Unit) and Control Unit.

Prepared By: Sushma Shetty
4 www.vtulife.com


3. BIOS (Basic Input Output System): Built in software which is placed in the ROM (Read Only
Memory) and is run at the start up for the system boot up.
4. Memory: To store the data and instructions.
5. Secondary memory: The data and instructions which has to be stored permanently.
6. Cards: It is printed circuit board that can be inserted into an expansion slot of a motherboard to
give additional capabilities to our computer. Eg: video card, graphic card, network interface card
(NIC).
7. SMPS (Switch Mode Power Supply): Converts AC current to DC current. This is essential for
running various parts of the computer.
BASIC STRUCTURE OF A COMPUTER
A computer can perform the following activities:
1. Accept data
2. Process or manipulate the data
3. Output the result in the form suitable for human understanding
4. Stores the input data, instructions and results.
The above activities are performed by various units in the computer system. The communication
between various units of the computer system is as in figure below:
INPUT UNIT:
The input devices are the input unit which are
connected to the computer system. Eg:
keyboard, mouse, scanner etc.
Using this the user can perform the following
operations:
1. User can enter data/instructions to the
computer system.
2. It is the responsibility of the input device to convert the data into a form understandable by the
computer.
3. The converted data is stored in the memory in the form of binary and then sent to CPU for
further processing.
OUTPUT UNIT:
Using output unit, the processing unit can output the results in human understandable language. Eg:
monitor, printer, speaker etc.
MEMORY UNIT:
It is divided into primary memory and secondary memory. It is used to:

Prepared By: Sushma Shetty
5 www.vtulife.com


1. Store instructions and data
2. Store intermediate results.
CENTRAL PROCESSING UNIT (CPU):
It is the brain of the computer. It executes the instructions one after the other with the help of CU and
ALU.
CONTROL UNIT (CU):
It controls and co-ordinates the activities of all the units by issuing proper commands. The functions of
the CU are:
1. Fetching instructions from memory.
2. Decoding the instruction.
3. Executing the instruction.
4. Issue appropriate commands to ALU, memory, input, output devices.
ARITHMETIC LOGIC UNIT (ALU):
Performs basic arithmetic operations: addition, subtraction, multiplication, division. It also performs
logic operations.
STORED PROGRAM CONCEPT
Storing data and instructions in memory as shown in figure below:
The CPU then fetches the instructions from the memory and executes them
one after the other.




The Von Newman Architecture based on stored program concept is as in figure below:
The computer has four functional units: input, output,
memory, CPU.
If a series of instruction has to be executed without human
intervention, the CU must perform the following sequence
of operations:
1. FETCH: Obtain data or the next instruction to be
executed from the memory.
2. DECODE: Identify the action to be taken, translate it into series of commands.

Prepared By: Sushma Shetty
6 www.vtulife.com


3. EXECUTE: Issue the proper command to the ALU to perform the desired operation.
4. STORE: Results obtained after executing the program are stored in memory.
CATEGORIZING COMPUTERS
Types of computers:
1. Data handling technique/based on technology
a) Digital computers. Eg: PC
b) Analog computers. Eg: slide rule,
c) Hybrid computers.
2. Computers for individuals
a) Desktop computers
b) Workstations
c) Notebook computers
d) Tablet computers
e) Handheld PCs
f) Smart phones
3. Computers for organizations
a) Network servers
b) Minicomputers
c) Mainframe computers
d) Super computers
DATA HANDLING DEVICES:
Data handling is important in ensuring the integrity of research data since it addresses concerns related
to confidentially, security, and preservation/retention of research data.
DIGITAL COMPUTERS:
Devices capable of solving problems by processing information in discrete form. It operates on data,
including magnitudes, letters, and symbols, that are expressed in binary formi.e., using only the two
digits 0 and 1.
ANALOG COMPUTERS:
An analog computer is a form of computer that uses the continuously changeable aspects of physical
phenomena such as electrical, mechanical, or hydraulic quantities to model the problem being solved.
Eg: Speedometers, milk and food processing industries,petrol pump, thermostat of fridge
HYBRID COMPUTERS:
A hybrid computer is a type of computer that is designed to provide the features and functions that are
found by both the digital and the analog computers. Eg: ECG monitor of a patient in a hospital. It takes in
an analog signal that is the heartbeat of the patient and converts it into the digital format after
processing it.

Prepared By: Sushma Shetty
7 www.vtulife.com


COMPUTERS FOR INDIVIDUALS:
DESKTOP COMPUTERS:
A personal computer in a form intended for regular use at a single location, as opposed to a
mobile laptop or portable computer.
WORKSTATIONS:
A workstation is a high-end microcomputer designed for technical or scientific applications. Intended
primarily to be used by one person at a time, they are commonly connected to a local area network and
run multi-user operating systems. The term workstation has also been used to refer to a mainframe
computer terminal or a PC connected to a network.
NOTEBOOK COMPUTERS:
It is also called as a laptop. It is a portable personal computer with a clamshell form factor, suitable
for mobile use.

A laptop has most of the same components as a desktop computer, including a display,
a keyboard, a pointing device such as a touchpad (also known as a trackpad) and/or a pointing stick, and
speakers into a single unit.
TABLET COMPUTERS:
Tablet computers or simply tablet, is a one-piece mobile computer. Devices typically have
a touchscreen, with finger or stylus gestures replacing the conventional computer mouse. It is often
supplemented by physical buttons or input from sensors such as accelerometers. An on-screen,
hideablevirtual keyboard is usually used for typing. Tablets differentiate themselves by being larger
than smart phones or personal digital assistants.
HANDHELD PC:
A Handheld PC, or H/PC for short, is a computer built around a form factor which is smaller than any
standard laptop computer. It is sometimes referred to as a Palmtop.
SMART PHONES:
A smartphone is a mobile phone built on a mobile operating system, with more advanced computing
capability and connectivity than a feature phone. The first smartphones combined the functions of
a personal digital assistant (PDA) with a mobile phone. Later models added the functionality of portable
media players, low-end compact digital cameras, pocket video cameras, and GPS navigation units to
form one multi-use device.
Many modern smartphones also include high resolution touchscreens and web browsers that display
standard web pages as well as mobile-optimized sites.
COMPUTERS FOR ORGANIZATIONS:
NETWORK SERVERS:
A network server is a computer designed to process requests and deliver data to other (client)
computers over a local network or the Internet. Network servers typically are configured with additional

Prepared By: Sushma Shetty
8 www.vtulife.com


processing, memory and storage capacity to handle the load of servicing clients. Common types of
network servers include:
Web servers
proxy servers
FTP servers
online game servers
MINICOMPUTERS:
A minicomputer is a class of smaller computers that evolved in the mid-1960s and sold for much less
than mainframe and mid-size computers from IBM and its direct competitors.
MAINFRAME COMPUTERS:
They are computers used primarily by corporate and governmental organizations for critical
applications, bulk data processing such as census, industry and consumer statistics, enterprise resource
planning, and transaction processing.
SUPER COMPUTERS:
A supercomputer is a computer at the frontline of contemporary processing capacity--particularly speed
of calculation. Supercomputers play an important role in the field of computational science, and are
used for a wide range of computationally intensive tasks in various fields, including quantum
mechanics, weather forecasting, climate research, oil and gas exploration, molecular and physical
simulations. Throughout their history, they have been essential in the field of counter-cryptography.
DIFFERENCES BETWEEN ANALOG, DIGITAL, HYBRID COMPUTERS:

ANALOG DIGITAL HYBRID
Process the analog data which is
continuous in nature
Process digital data which is
binary in nature
Process digital data using
analog solution
Data is processed by measuring Data is processed by counting
Data is processed by combining
the methods used in digital and
analog computers.
They require very less memory
and no memory
They require memory They require less memory
Process mathematical and
scientific data which is
continuous in nature
Process mathematical and
scientific data which is binary
using complex logics
Accept analog data, process
mathematical and scientific
data and convert into digital
data


Prepared By: Sushma Shetty
9 www.vtulife.com


PARTS OF A COMPUTER SYSTEM
1. hardware
2. software
3. data
4. user
HARDWARE:
The physical components which make up the computer system are called hardware. They are
categorized as:
1. Input devices. Eg; keyboard, mouse
2. Output devices. Eg: monitor, printer
3. System unit. Eg: CPU, Video card, Sound card
4. Storage devices. Eg: CD, DVD, RAM, ROM
SOFTWARE:
A program is a set of instructions given to the computer to perform a specific task or activity. The set of
programs that perform a specific jobs are called as software.
DATA:
The data is a piece of information that we input to the computer from the input device. The computer
manipulates the data into information that we can understand and output the information.
USER:
The people who use computers are users. They are also part of computer system because they write
programs, use it and make it perform the tasks as per their requirement.
THE INFORMATION PROCESSING CYCLE
The sequence of events in processing information, which includes (1) input, (2) processing, (3)
storage and (4) output. These processes work together and repeat over
and over.
1. Input: entering data into the computer.
2. Processing: performing operations on the data.
3. Storage: saving data, programs, or output for future use.
4. Output: presenting the results.
ESSENTIAL COMPUTER HARDWARE
Hardware is the term given to the components that make up a computer. This term was derived from
the internal components of a computer which consists circuits, electronics, and in short anything that
you could touch inside your computer. Hardware can be broken up into four parts:

Prepared By: Sushma Shetty
10 www.vtulife.com


1. Processor
2. Memory
3. Input
4. Output
PROCESSOR:
The processor is the most important piece of hardware within your computer. It is the brain, the very
intellect of these electronic machines. The processor, decodes and executes instructions that are sent to
in via the many lanes within the motherboard. On a personal computer, the processor is usually a single
chip or a set of chips on top on a circuit board. In some powerful computers, such as the super
computers, they consists of many chips on a circuit board. Now in general, these chips are referenced to
as central processing unit (CPU).
MEMORY AND STORAGE DEVICES:
MEMORY: There are two types of memory that are very common. Actually, only one is very common the
- RAM or also known as the random access memory because of it is a static memory. Static memories
are memories that do not store data always (as soon as you switch off the computer) - the memory
becomes empty or resets itself. Dynamic memory or volatile memory stores data that is fixed and does
not go off even if the computer is switch off. This is read only memory (ROM) which stores critical boot
up information of the computer. An example is the BIOS chip which stores a ROM to ensure that it has
the proper instructions needed for the computer to operate.
STORAGE DEVICES: Storage devices are also known as magnetic storage devices because of the nature of
these storage devices. This is the disk drive or the hard disk as it is commonly known. Within these disks
are read/write heads like a tiny pin (like the gramaphone) this pin or head is used to read or write data
into the disk. There are also other types of storage devices such as optical storage devices. These devices
comprises of your DVD-Roms, CD-Roms, VCD, and so on.
INPUT AND OUTPUT:
These devices are known as input and output or shortly (I/O) because their purpose is to provide either
input into the computer system or to provide an output from the computer system. Typical I/O
hardware devices are Monitor, Keyboard, Mouse, Speakers, Microphone, Modem, Webcam,
Headphones, Printers, Fax Machines, Joystick, Scanner, Touchpad.
DIFFERENCES BETWEEN STORAGE DEVICES AND MEMORY:
STORAGE DEVICES MEMORY
Capacity is more Storage capacity is less
Contents are retained when computer is
turned off
Contents are not stored as permanent
memory to be retained after shut down
Accessing of data or programs are slow It is faster

Prepared By: Sushma Shetty
11 www.vtulife.com


Less expensive More expensive
Portable
Not portable since it is plugged into
motherboard

ESSENTIAL COMPUTER SOFTWARE
A program is a set of instructions given to the computer to perform a specific task or activity. The set of
programs that perform a specific jobs are called as software.
Two types:
1. System software
2. Aoolication software
SYSTEM SOFTWARE:
System software (or systems software) is computer software designed to operate and control
the computer hardware and to provide a platform for running application software. The operating
system (prominent examples being Microsoft Windows, Mac OS X and Linux), allows the parts of a
computer to work together by performing tasks like transferring data between memory and disks or
rendering output onto a display device. It also provides a platform to run high-level system software
and application software.
APPLICATION SOFTWARE:
Application software is all the computer software that causes a computer to perform useful tasks
(compare with computer viruses) beyond the running of the computer itself. A specific instance of such
software is called a software application, application or app.
SYSTEM SOFTWARE APPLICATION SOFTWARE
Collection of programs that help the user to
interact with the hardware components efficiently.
Collection of programs written for specific
application.
System software control and manage the
hardware.
Application software uses the services of the
system software to interact with the hardware
components.
To write such programs, understanding the
hardware architecture of the system is needed.
The programmer need not worry about the
hardware architecture.
Directly interact with hardware. Interact with hardware using system calls.
Development of system software is complex task.
Development of application software is relatively
easier.
Eg: compiler, assembler, operating system Eg: MS-WORD, Paint, ticket reservation etc.



Prepared By: Sushma Shetty
12 www.vtulife.com


INTERACTING WITH COMPUTER
INPUT DEVICES
1. Keyboard
2. Pointing devices
a) Mouse
b) Track ball
c) Track pad
d) Pointers in the keyboard (Track point)
3. Hand held devices
a) Pen
b) Touch screen
c) Game controllers
4. Optical devices
a) Bar code readers
b) Scanners and OCR
5. Audiovisual Input devices
a) Microphone
b) Video input
c) Digital cameras
KEYBOARD:
In computing, a keyboard is a typewriter-style device, which uses an arrangement of buttons or keys, to
act as mechanical levers or electronic switches.
A keyboard typically has characters engraved or printed on the keys and each press of a key typically
corresponds to a single written symbol. However, to produce some symbols requires pressing and
holding several keys simultaneously or in sequence. While most keyboard keys produce letters,
numbers or signs (characters), other keys or simultaneous key presses can produce actions or execute
computer commands.
Standard keyboard layout is the QWERTY layout. The other form is DWORAK.
The types of keys are:
1. Alphanumeric and character keys : A-Z, 0-9, {,} , tabs, capslock etc.
2. Numeric keypad : when numlock on or off.
3. Modifier keys : shift keys.
4. Cursor movement keys : the arrows for movement of cursor.
5. Function keys : The F1, F2, F9 keys.
6. Special purpose keys : start key, shortcut key, ESC, Print scrn.

Prepared By: Sushma Shetty
13 www.vtulife.com


POINTING DEVICES:
Input devices which can control the movement of cursor on the screen.
MOUSE:
In computing, a mouse is a pointing device that functions by detecting two-dimensional motion relative
to its supporting surface. Physically, a mouse consists of an object held under one of the user's hands,
with one or more buttons. The mouse sometimes features other elements, such as "wheels", which
allow the user to perform various system-dependent operations, or extra buttons or features that can
add more control or dimensional input. The mouse's motion typically translates into the motion of
a pointer on a display, which allows for fine control of a graphical user interface.
The various actions performed are:
1. Pointing
2. Clicking
3. Double clicking
4. Dragging
5. Scrolling
VARIANTS OF MOUSE:
1. TRACK BALL:
A trackball is a pointing device consisting of a ball held by a socket containing sensors to detect a
rotation of the ball about two axeslike an upside-down mouse with an exposed protruding ball. The
user rolls the ball with the thumb, fingers, or the palm of the hand to move a pointer. Compared with a
mouse, a trackball has no limits on effective travel; at times, a mouse can reach an edge of its working
area while the operator still wishes to move the screen pointer farther. With a trackball, the operator
just continues rolling, whereas a mouse would have to be lifted and re-positioned. Large trackballs are
common on CAD workstations for easy precision. The disadvantage is that dust accumulates in its
chamber.
2. TOUCH PAD:
It is a pointing device featuring a tactile sensor, a specialized surface that can translate the motion and
position of a user's fingers to a relative position on screen. Touchpads are a common feature of laptop
computers, and are also used as a substitute for a mouse where desk space is scarce. Because they vary
in size, they can also be found on personal digital assistants (PDAs) and some portable media
players. Wireless touchpads are also available as detached accessories.
3. TRACK POINT:
It is typically mounted in a computer keyboard on a laptop or desktop computer. Movements of the
pointing stick are echoed on the screen by movements of the pointer (or cursor) and other visual
changes. The pointing stick operates by sensing applied force, by using a pair of resistive strain gauges.
The velocity of the pointer depends on the applied force. On a QWERTY keyboard, the stick is typically
embedded between the "G", "H" and "B" keys, and the mouse buttons are placed just below the space
bar.

Prepared By: Sushma Shetty
14 www.vtulife.com


HAND HELD DEVICES:
1. PEN:
Pen computing refers to a computer user-interface using a pen (or stylus) and tablet, rather than devices
such as a keyboard, joysticks or a mouse. Pen computing is also used to refer to the usage of mobile
devices such as wireless tablet personal computers, PDAs and GPS receivers. The term has been used to
refer to the usage of any product allowing for mobile communication. An indication of such a device is
a stylus, generally used to press upon a graphics tablet or touchscreen, as opposed to using a more
traditional interface such as a keyboard, keypad, mouse or touchpad.
2. TOUCH SCREEN:
A touchscreen is an electronic visual display that the user can control through simple or multi-touch
gestures by touching the screen with one or more fingers. Some touchscreens can also detect objects
such as a stylus or ordinary or specially coated gloves. The user can use the touchscreen to react to what
is displayed and to control how it is displayed (for example by zooming the text size). The touchscreen
enables the user to interact directly with what is displayed, rather than using a mouse, touchpad, or any
other intermediate device (other than a stylus, which is optional for most modern touchscreens).
3. GAME CONTROLLERS:
A game controller is a device used with games or entertainment systems to provide input to a video
game, typically to control an object or character in the game. A controller is usually connected to a game
console or computer by means of a wire or cord, although wireless controllers are also widespread.
Input devices that have been classified as game controllers include keyboards, mice, game pads,
joysticks, etc. Special purpose devices, such as steering wheels for driving games and light guns for
shooting games, are also game controllers.
OPTICAL DEVICES (DATA SCANNING DEVICES)
The device which uses light as a source of input for detecting or recognizing various things is calles as an
optical input device.
1. BAR CODE READERS:
A barcode reader (or barcode scanner) is an electronic device for reading printed barcodes. Like
a flatbed scanner, it consists of a light source, a lens and a light sensor translating optical impulses into
electrical ones. Additionally, nearly all barcode readers contain decoder circuitry analyzing the barcode's
image data provided by the sensor and sending the barcode's content to the scanner's output port.
2. SCANNERS:
It is a device that optically scans images, printed text, handwriting, or an object, and converts it to
a digital image. Common examples found in offices are variations of the desktop (or flatbed)
scanner where the document is placed on a glass window for scanning. Hand-held scanners, where the
device is moved by hand, have evolved from text scanning "wands" to 3D scanners used for industrial
design, reverse engineering, test and measurement, orthotics, gaming and other applications.

Prepared By: Sushma Shetty
15 www.vtulife.com


3. OPTICAL CHARACTER RECOGNITION (OCR):
Optical character recognition, usually abbreviated to OCR, is the mechanical or electronic conversion of
scanned images of handwritten, typewritten or printed text into machine-encoded text. It is widely used
as a form of data entry from some sort of original paper data source, whether documents, sales receipts,
mail, or any number of printed records. It is a common method of digitizing printed texts so that they
can be electronically searched, stored more compactly, displayed on-line, and used in machine
processes such as machine translation, text-to-speech and text mining. OCR is a field of research
in pattern recognition, artificial intelligence and computer vision.

4. OPTICAL MARK READER (OMR):
The Optical Mark Reader is a device that reads pencil marks on NCS compatible scan forms such as
surveys or test answer forms. In this document The Optical Mark Reader will be referred to as the
scanner or OMR. The computer test forms designed for the OMR are known as NCS compatible scan
forms. Tests and surveys completed on these forms are read in by the scanner, checked, and the results
are saved to a file. This data file can be converted into an output file of several different formats,
depending on which type of output you desire.
AUDIOVISUAL DEVICES
1. AUDIO DEVICES:
Audio devices allow you to play or record audio, which can be sounds, music, speech, etc. These devices
can be interesting for a forensic investigator, as they can often contain not only audio files, but also text
documents, images and so on.
2. MICROPHONE:
It is an acoustic-to-electric transducer or sensor that converts sound into an electrical signal.
Microphones are used in many applications such as telephones, tape recorders, karaoke systems,
hearing aids, motion pictureproduction, live and recorded audio engineering, FRS radios, megaphones,
in radio and television broadcasting and in computers for recording voice,speech recognition, VoIP, and
for non-acoustic purposes such as ultrasonic checking or knock sensors.
3. VOICE RECOGNITION DEVICES:
Ability of a computer, computer software program, or hardware device to decode the human voice into
digitized speech that can be interpreted by the computer or hardware device. Voice recognition is
commonly used to operate a device, perform commands, or write without having to operate a
keyboard, mouse, or press any buttons. Speech recognition (SR) is the translation of spoken words into

Prepared By: Sushma Shetty
16 www.vtulife.com


text. It is also known as automatic speech recognition (ASR) or computer speech recognition, speech to
text (STT).
4. VIDEO INPUT DEVICES:
Video input is the process of capturing and storing the full-motion recording into the computer. The
various video input devices are:
1. VCR
2. Cam corder
3. Web cam
5. DIGITAL CAMERA:
A digital camera (or digicam) is a camera that takes video or still photographs by recording images on
an electronic image sensor. Most cameras sold today are digital and digital cameras are incorporated
into many devices ranging from PDAs and mobile phones (called camera phones) to vehicles.
OUTPUT DEVICES
They are electromechanical devices that accept the data from the computer and convert the data into a
form that can be readable or understood by people or the user.
Classification:
1. Soft copy devices
a) Monitors
b) Data projectors
c) Sound systems
2. Hard copy devices
a) Dot matrix printers
b) Ink jet printers
c) Laser printers
d) Plotters
SOFTCOPY OUTPUT DEVICES:
The electronic version of an output such as a document or a file which is stored on a computer disc such
as floppy disc, hard disc, CD or similar medium is called as softcopy.
The output devices which can display this information stored in the computer are called softcopy output
devices.
HARDCOPY OUTPUT DEVICES:
The physical form of output is the hardcopy. The devices which are used for creating the hard copy
output are called hardcopy output devices.


Prepared By: Sushma Shetty
17 www.vtulife.com


SOFTCOPY HARDCOPY
To see the output computer must be operating. Computer is not required to see the output.
Modifications and updates are easier and
changes are not visible.
Modifications and updates are difficult and
changes are visible.
Cannot be distributed to people without
computer.
Can be distributed to people who dont have
computer.
Requires less storage space. Requires more storage space.
Searching for a information is easier. Searching for a piece of information is difficult.
Very easy to duplicate Difficult to duplicate
Not tangible (cannot be touched) Tangible.

VIDEO SYSTEMS
The devices or systems that produce the output so that we can see it are video systems. Eg: monitors,
data projectors.
MONITORS
They are the display devices that are housed in a plastic or metal case. A montor along with a keyboard
is called video display terminal.
Classification:
1. Monochrome monitors
2. Grayscale monitors
3. Color monitors
Monochrome Monitors:
Such monitors can display the text in only one color (such as white, green etc) with black background. It
is cheap and is rarely found these days.
Grayscale Monitors:
They are capable of displaying multiple shades ranging from very light gray to black against white or
partially white background.
Color Monitors:
It displays the text or images in varying colors. Present day color monitors can display between 16 colors
and 16 million colors. They can be set to work in monochrome or grayscale mode.
Based on technology monitors are classified as:
1. CRT monitors

Prepared By: Sushma Shetty
18 www.vtulife.com


2. Flat panel monitors
CRT Monitors:
CRT (Cathode Ray Tube) monitor is a TV like display attached to the computer on which the output is
displayed.
COMPONENTS:
1. Electron gun: It generates a beam of
electrons and is situated at the backend of
the monitor as in figure.
2. Deflection plates (Magnetic coil): The
electron beam is directed towards the
screen in front of the tube using the
deflection plates.
3. Phosphor: The back of the screen is coated
with phosphor, a chemical that glows when it is hit by the electron beam.
4. Screen: The light emitted by the phosphor fades very rapidly and hence it is necessary to redraw
the picture rapidly on the screen and thus displaying a continuous image.
WORKING:
The image is displayed on the screen when the
electron gun traverses the screen in a fixed pattern
writing on the pixel or not writing on the pixel as in
figure.
1. The electrons from electron gun will hit
every pixel on the screen starting from top-
left corner horizontally. The beam can be
turned on or off. This horizontal line of
pixels is called as the scan line.
2. When the beam reaches right end of a scan line, the beam is turned off. The electron gun drops
down a small distance and moves to the beginning of the new scan line. This is called horizontal
trace and start scanning from left to right.
3. The above procedure is repeated for each scan line, till the beam gets to the right end of the last
scan line. Now, the beam is turned off and moved to the starting point of the first scan line. This
is vertical trace.
4. The above procedure shows one pass of scanning the screen.
In case of a color monitor, each pixel in the color monitor has three phosphors- red, blue and green. By
varying the intensities of these beams, various colors can be obtained.
ADVANTAGES:

Prepared By: Sushma Shetty
19 www.vtulife.com


1. They provide bright and clear pictures.
2. The cost is really less when compared with other types of monitors.
DISADVANTAGES:
1. The size of CRT monitor is big and hence take more desktop space.
2. Heavy and hence not portable.
3. More power to run.
4. The screen is curved and hence diplay is across the curve.
Flat Panel Monitors:
It has a flat screen, less weight and about one inch thick. These monitors are commonly used these days.
They consume very less power and can be operated with battery built into the computer. These features
are used in laptops also.
They use a special kind of liquid crystals to display the images on the screen. They are transparent but
when charged with electricity they become opaque.
ADVANTAGES:
1. They occupy less desktop space.
2. Portable.
3. Require less power and run on battery.
DISADVANTAGES:
1. Costlier compared to CRT.
2. Images are difficult to see in bright light.
Two categories of LCDS:
1. Passive matrix LCD monitor
2. Active matrix LCD monitor
Passive matrix LCD monitor Active matrix LCD monitor
Each row and column of pixels are controlled by a
set of transistors identified by row and column
transistors.
Each pixel has a transistor and can be turned on
and off individually.
The color of the pixel is determined by the current
coming out of transistor at the end of a row and
top of the column.
The color of the pixel is determined by the current
coming out of that transistor.
Inexpensive Comparatively expensive
Narrow viewing angle Wider viewer angle
Refreshing of pixels is slow Refreshing of pixels is very fast

Prepared By: Sushma Shetty
20 www.vtulife.com


Uses dual scan LCD technology Uses thin film transistor (TFT) technology

OTHER TYPES OF MONITOR:
1. Paper-white displays
2. Electroluminescent displays
3. Plasma displays
MONITOR QUALITY:
1. Size: Monitors available in various sizes such as 14, 15, 17, 19, 21 inches. Larger monitors are
relatively costlier.
2. Resolution: This term is associated with sharpness or clarity of the image displayed on the
screen. It is determined by the number of pixels on the screen.
3. Refresh Rate: When an electron beam strikes the phosphor, the phosphor emits light resulting
in the display of the image only for a fraction of a second. If we want to see the image properly,
the screen has to refreshed with same data for atleast 60-70 times per second. This rate is called
as the refresh rate.
4. Dot pitch: The distance between the two light colored pixels on the display screen is defined as
dot pitch. The smaller the distance, sharper the image.
VIDEO CARD
It is also called as video boards or video display boards or graphics card or graphics adapter.
It is a physical hardware circuit board which is connected to the motherboard. It acts as a intermediate
device between the CPU and monitor. The CPU sends the data or image to be displayed to video card.
This device converts the text or image sent by the CPU into equivalent electrical signals. These signals
are used by the electron gun to produce stream of electrons which displays the appropriate pixels. Thus,
the text or images appear on the screen.
The display capabilities of the computer depends on both the logical circuitry provided in the video
adapter and the display monitor. By placing video card on the motherboard, the cost of the computer
can be reduced.
Eg: VGA (Video Graphics Array), Super VGA.
DATA PROJECTORS
It is a special device used to display the output obtained from the computers on to a large screen on the
wall. The data projectors are first connected to computer. The device projects the video output onto an
external surface. They look and weigh like a camera. Usually used in classes, conferences.
Two types:

Prepared By: Sushma Shetty
21 www.vtulife.com


1. LCD projectors
2. DLP projectors.
LCD Projectors DLP Projectors
Uses liquid crystal display technology Uses digital light processing technology
Uses its own light source to display the
information on the screen or wall
Uses many mirrors to reflect light
Room should be darkened Room need not be darkened

SOUND SYSTEMS
The devices or systems that produce sound are called sound systems. Eg: microphone and speaker,
sound card, CD-ROM or DVD.
Uses:
1. To create multi-media products.
2. To watch video.
3. Listen to music
4. Videoconferencing and distance learning
Working:

1. Speaker speaks into microphone
2. Microphone sends sound waves as input to sound card inside computer.
3. Sound card converts audio signals into equivalent electric current.
4. Current may be in form of voltage which is applied to electromagnet.
5. The changing magnetic field pushes the magnet back and forth.
6. The speaker attached to magnet moves and creates changes in the air pressure. The air pressure
generated by speaker cone is interpreted as sound by brain.
SOUND CARDS
It is a physical hardware circuit board which is connected to the motherboard or inserted into one of the
computers internal expansion slots. This allows computer to produce sounds through speakers.

Prepared By: Sushma Shetty
22 www.vtulife.com


HEADPHONES AND HEADSET:
A headphone consists of a pair of speakers which is attached to a strap that can be fitted to the wearers
head, speakers placed in close proximity to the ears.
A headset is a device which includes two speakers and a microphone mounted to a adjustable head
strap. It can be used to make phone calls using PC, participate in video conferencing.
PRINTERS
It is an output device that is used to print the text and graphical information on a physical medium such
as paper.
TYPES:
1. Impact printers
a) Dot matrix printers
b) Line printers
c) Band printers
2. Non-impact printers
a) Ink jet printers
b) Laser printers
IMPACT PRINTERS
An impact printer works by physically striking an ink ribbon that is placed on the paper.the print head
has pins that take the shape of a letter or character and when the hammer strikes the ribbon, the shape
of the character is transferred through the inked ribbon onto the paper creating a printed character.
ADVANTAGES:
1. Can create carbon copies
2. Used for bulk printing
3. Less expensive
4. Maintenance is cheap
DISADVANTAGES:
1. Relatively slow
2. Print quality is poor
3. They are noisy
NON-IMPACT PRINTERS
It is a printer which forms the characters and images without making the physical contact between the
printing mechanism and the medium on which the printing takes place. Ink is sprayed on the paper in
the form of character.

Prepared By: Sushma Shetty
23 www.vtulife.com


ADVANTAGES:
1. Produces high quality output.
2. They are noiseless
3. They can handle graphics unlike impact printers
4. They handle wide variety of fonts
5. They are relatively faster
DISADVANTAGES:
1. They are more expensive
2. Maintenance is costly
IMPACT/ DOT MATRIX PRINTER NON IMPACT/ INKJET/ LASER PRINTER
Works by striking an ink ribbon
Striking mechanism is not used. Spraying the
ink or by using toner.
Very cheap Costlier
Slow printing because of moving parts Fast printing because of fewer moving parts
Carbon copies can be taken Carbon copies cannot be taken
Noisy because of striking Noiseless
Quality of print is not good Good quality print
Prints only text Prints text and graphics
Only standard text is supported Varying fonts
Ex: line printer, dot matrix printer Ex: ink jet, laser printer

DOT MATRIX PRINTER
It is a character printer that prints all types of characters and images as a pattern of dots by striking
against the ink ribbon. The hammer is a print head consisting of bi-directional pins and works as impact
printers. This is the cheapest printer.
WORKING:
Let the letter T has to be printed which is represented as in figure:





Prepared By: Sushma Shetty
24 www.vtulife.com


As the print head moves across the paper only the pins in the first column will strike the ribbon in turn
will strike the paper. The sequence is as in figure below:

INKJET PRINTER
It is a printer that forms all types of characters and images by spraying small drops of ink on the paper.
They are non impact printers.
WORKING:
The working is similar to that of dot matrix printers. The character is produced by spraying small
droplets of ink through tiny nozzles. Instead of print head, the inkjet printer uses ink nozzles.
The commonly used ink jet printers are HP, Epson and Canon printers.
LASER PRINTER
It is a high quality, high speed non impact printer which operates in a manner similar to Xerox
(photocopying) machine using laser technology. It uses laser beam to form images and it is transferred
to paper electrostatically.
WORKING:
It has its own CPU and built in memory. The
CPU interprets the data received from the
computer and to control the laser.
1. The laser beam moves across the
drum using the mirror and creates an
image on the drum in the form of
electrical charge.
2. The electrical charge on the drum
attracts the toner particles, thus
forming complete image to be printed on the paper.
3. The paper is taken from the tray and passed across the drum and the image is transferred on
the paper.

Prepared By: Sushma Shetty
25 www.vtulife.com


4. The toner particles transferred on the paper are imprinted or fused permanently on the paper
using heat or pressure.
5. The paper comes out of the printer.
6. After the document is printed, the electrical charge is removed from the drum. It is made ready
for the next paper.
Dot matrix printer Laser printer
Impact printer Non impact printer
Slow printing Fast printing
Very cheap Costlier
Carbon copies can be taken Carbon copies cannot be taken
Produces noise Dont produce much noise
Print quality is not good Print quality is very good
Prints only text Prints both text and graphics
PLOTTERS
A pen plotter similar to a printer is used to draw only continuous lines using a pen. Multicolored plotters
use many colored pens to draw different colors. They are used in CAD applications. They are more
expensive than printers.


PROCESSING DATA
DATA/ INFORMATION
Data is a representation of facts or concepts in an organized manner. Information is defined as a
collection of data from which conclusions may be drawn.
DATA INFORMATION
Data is collection of facts and figures Information is the result of processing of data
Data do not convey any meaning It conveys meaning
Computers work with data Computers do not work with information
Data is unstructured Data is correctly organized

Prepared By: Sushma Shetty
26 www.vtulife.com


It is representation of information. So the
representation may change
Even if data representation changes, information
do not change.

NUMBER SYSTEM AND DATA REPRESENTATION
NUMBER SYSTEM
When we type some letters or words, the computer translates them in numbers as computers can
understand only numbers.
DECIMAL NUMBER SYSTEM:
Decimal number system has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the
successive positions to the left of the decimal point represent units, tens, hundreds, thousands and so
on.
Each position represents a specific power of the base (10). For example, the decimal number 1234
consists of the digit 4 in the units position, 3 in the tens position, 2 in the hundreds position, and 1 in the
thousands position, and its value can be written as
(1x1000)+ (2x100)+ (3x10)+ (4xl)
=(1x10
3
)+ (2x10
2
)+ (3x10
1
)+ (4xl0
0
)
=1000 + 200 + 30 + 4
=1234
BINARY NUMBER SYSTEM:
CHARACTERISTICS:
Uses two digits, 0 and 1.
Also called base 2 number system.
Each position in a binary number represents a 0 power of the base (2).
Example 2
0
. Last position in a binary number represents a x power of the base (2). Example
2
x
where x represents the last position - 1.
Eg: Binary Number: 101012 . Calculating Decimal Equivalent:

Prepared By: Sushma Shetty
27 www.vtulife.com



DECIMAL TO BINARY:
STEPS:
Step 1 - Divide the decimal number to be converted by the value of the new base.
Step 2 - Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base
number.
Step 3 - Divide the quotient of the previous divide by the new base.
Step 4 - Record the remainder from Step 3 as the next digit (to the left) of the new base number.
Repeat Steps 3 and 4, getting remainders from right to left, until the quotient becomes zero in Step 3.
The last remainder thus obtained will be the most significant digit (MSD) of the new base number.
Eg: Decimal Number: 29. Calculating Binary Equivalent:


Binary equivalent: 11101
OCTAL NUMBER SYSTEM:
CHARACTERISTICS:
Uses eight digits, 0,1,2,3,4,5,6,7.
Also called base 8 number system
Each position in a octal number represents a 0 power of the base (8). Example 8
0

Last position in a octal number represents a x power of the base (8). Example 8
x
where x represents
the last position - 1.
Eg: Octal Number: 125708 . Calculating Decimal Equivalent:

Prepared By: Sushma Shetty
28 www.vtulife.com




HEXADECIMAL NUMBER SYSTEM:
CHARACTERISTICS:
Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.
Letters represents numbers starting from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15.
Also called base 16 number system
Each position in a hexadecimal number represents a 0 power of the base (16). Example 16
0

Last position in a hexadecimal number represents a x power of the base (16). Example 16
x
where x
represents the last position - 1.
Eg: Hexadecimal Number: 19FDE16 .Calculating Decimal Equivalent:



REPRESENTATION OF DATA
The data are represented in the state of electronic switches. A switch with ON state represents 1 and a
switch with OFF state represents 0. Letters, digits, sound, pictures are all represented using 0s and 1s.
Characters have ASCII values wich are digits and they are represented in binary.
Values which represent state of a switch is called bit.

Prepared By: Sushma Shetty
29 www.vtulife.com


UNITS OF DATA:

HOW CPU PROCESS DATA
The processing of data is performed using following hardware units:
1. Central Processing Unit (CPU)
2. Memory
CPU:
The CPU is the brain of the computer, which executes instructions one after the other. The execution of
each instruction is performed with the help of two basic parts:
1. Control unit
2. Arithmetic Logic Unit
CONTRUL UNIT (CU):
It controls and co-ordinates the activities of all the units by issuing proper commands. The various
responsibilities of the control unit are:
1. Issue propersignals to the memory to fetch the next instruction to be executed.
2. Decode the instruction.
3. Execute the instruction.
4. Issue proper command to ALU, memory, I/O units to get the job done.
INTERCONNECTION OF UNITS
A group of wires connected between various sub-units of a computer to transfer the data/instructions is
called PC bus or bus. Two types of PC bus:
1. System bus

Prepared By: Sushma Shetty
30 www.vtulife.com


a) Data bus
b) Address bus
c) Control bus
2. I/O bus
a) ISA bus
b) PCI bus
c) USB bus
SYSTEM BUS:
It is used to connect the CPU with RAM and cache memory.
1. Data bus: A group of wires used to transfer the data is called data bus.
2. Address bu: A group of wires exclusively used to transfer the address is called address bus.
3. Control bus: A group of wires used to transfer the control signals is called control bus.

THE I/O BUS:.
It is used to connect all I/O devices with CPU and RAM.
1. ISA bus: ISA (Industry Standard Architecture) I/O bus was also 8 bit and ran at 4.77MHz. It
typically runs much slower. One reason is the fact that the ISA bus clock and CPU clock run
asynchronously, resulting in many wasted clock cycles.
2. PCI bus: (Peripheral Component Interface), the performance of PCI is much the same as VLB; it
too is 32 bits wide and runs and 33MHz, resulting in a bandwidth of 127MB/sec. Two major
advantages of PCI over VLB are the support for bus mastering and for Plug and Play.
3. USB: (Universal Serial Bus), helps to convert various devices such as keyboard, mouse, printer
very quickly and easily.
MEMORY
Two types:
1. Primary memory
2. Secondary memory

Prepared By: Sushma Shetty
31 www.vtulife.com


PRIMARY MEMORY/MAIN MEMORY:
Primary memory holds only those data and instructions on which computer is currently working. It has
limited capacity and data get lost when power is switched off.
It is generally made up of semiconductor device. These memories are not as fast as registers. The data
and instruction required to be processed earlier reside in main memory. It is divided into two
subcategories RAM and ROM.
Characteristic of Main Memory:
1. These are semiconductor memories.
2. It known as main memory.
3. Usually volatile memory.
4. Data is lost in case power is switch off.
5. It is working memory of the computer.
6. Faster than secondary memories.
7. A computer cannot run without primary memory.
SECONDARY MEMORY:
This type of memory is also known as external memory or non-volatile. It is slower than main memory.
These are used for storing Data/Information permanently.
CPU directly does not access these memories instead they are accessed via input-output routines.
Contents of secondary memories are first transferred to main memory, and then CPU can access it.For
example: disk, CD-ROM,DVD etc.
Characteristic of Secondary Memory:
1. These are magnetic and optical memories.
2. It is known as backup memory.
3. It is non-volatile memory.
4. Data is permanently stored even if power is switched off.
5. It is used for storage of the data in the computer.
6. Computer may run without secondary memory.
7. Slower than primary memories.

Prepared By: Sushma Shetty
32 www.vtulife.com


CACHE MEMORY:
Cache memory is a very high speed semiconductor memory which can speed up CPU. It acts as a buffer
between the CPU and main memory.
It is used to hold those parts of data and program which are most frequently used by CPU. The parts of
data and programs are transferred from disk to cache memory by operating system, from where CPU
can access them.
ADVANTAGE
1. Cache memory is faster than main memory.
2. It consumes less access time as compared to main memory.
3. It stores the program that can be executed within a short period of time.
4. It stores data for temporary use.
DISADVANTAGE:
1. Cache memory has limited capacity.
2. It is very expensive.
RAM (Random Access Memory):
A RAM constitutes the internal memory of the CPU for storing data, program and program result. It is
read/write memory. It is called random access memory (RAM).
Since access time in RAM is independent of the address to the word that is, each storage location inside
the memory is as easy to reach as other location & takes the same amount of time. We can reach into
the memory at random & extremely fast but can also be quite expensive.
RAM is volatile, i.e. data stored in it is lost when we switch off the computer or if there is a power
failure. Hence a backup uninterruptible power system(UPS) is often used with computers. RAM is small ,
both in terms of its physical size and in the amount of data it can hold.
RAM is of two types: Static RAM (SRAM), Dynamic RAM (DRAM).
ROM (Read Only Memory):
ROM stands for Read Only Memory. The memory from which we can only read but cannot write on it.
This type of memory is non-volatile. The information is stored permanently in such memories during
manufacture.
A ROM, stores such instruction as are required to start computer when electricity is first turned on, this
operation is referred to as bootstrap. ROM chip are not only used in the computer but also in other
electronic items like washing machine and microwave oven.

Prepared By: Sushma Shetty
33 www.vtulife.com


PRIMARY MEMORY VS SECONDARY MEMORY
1. Processor access the primary memory in a random fashion. Unlike primary memory, secondary
memory is not directly accessed through CPU. The accessing of the primary memory through
CPU is done by making use of address and data buses, whereas input/ output channels are used
to access the secondary memory.
2. The primary memory is embedded with two types of memory technologies; they are the RAM
(Random Access Memory) and ROM (Read Only Memory). The secondary memory is accessible
in the form of Mass storage devices such as hard disk, memory chips, Pen drive, floppy disk
storage media, CD and DVD.
3. Primary memory is volatile in nature, while secondary memory is non volatile. The information
that is stored in the primary memory cannot be retained when the power is turned off. In case
of secondary memory, the information can be retrieved even if the power is turned off because
the data will not be destructed until and unless the user erases it.
4. When the data processing speed is compared between the primary and secondary memory, the
primary memory is much faster than the secondary memory.
5. In the cost perspective, the primary memory is costlier than the secondary memory devices.
Because of this reasons most of the computer users install smaller primary memory and larger
secondary memory.
6. As the secondary memory is permanent, all the files and programs are stored in the secondary
memory most and as the primary memory interacts very fast with the micro processor, when
the computer needs to access the files that are stored in the secondary memory, then such files
are first loaded into the primary memory and then accessed by the computer.
MOTHERBOARD
The motherboard serves as a single platform to connect all of the parts of a computer together. A
motherboard connects CPU, memory, hard drives, optical drives, video card, sound card and other ports
and expansion cards directly or via cables. It can be considered as the backbone of a computer.
Features:
1. Motherboard varies greatly in supporting various types of components.
2. Normally a motherboard supports a single type of CPU and few types of memories.
3. Video Cards, Hard disks, Sound Cards have to compatible with motherboard to function properly.
4. Motherboards, cases and power supplies must be compatible to work properly together.
MICROPROCESSOR
It is a chip that contains the CPU. The microprocessors control the logic of almost all digital devices.
CHARACTERISTICS:
1. Instruction set: set of instructions to be executed.

Prepared By: Sushma Shetty
34 www.vtulife.com


2. Bandwidth: the number of bits processed in one instruction.
3. Clock speed: determines the number of instructions to be executed per second.
MICROPROCESSOR ASSOCIATES
The microprocessor is associated with the various components such as clock rate, motherboard, system
bus etc. They determine the capacity of the micropreocessor and work with it in achieving a given task.
The components are:
1. CLOCK RATE:
The rate at which a processor completes its processing is called clock rate. It is measured in cycles per
second (Hz).
2. MOTHERBOARD:
It is the main circuit of the microcomputer that contains various connectors for attaching additional
boards. The motherboard contains CPU, BIOS, memory, mass storage interfaces, serial and parallel
ports, expansion slots.
3. SYSTEM BUS:
It refers to the bus which connects CPU and memory.
4. CACHE MEMORY:
The portion of main memory that a computer processor can access more quickly than a RAM.
5. INSTRUCTION PIPELINING:
CPU can process millions or billions of instructions per second. In pipelining technique, when one
instruction is being executed, another instruction can be fetched from the memory and decoded,
thereby increasing execution speed.
6. HEAT SINK:
It is a device that is attached to the microprocessor chip which is used to bring down the temperature of
electronic device. The heat sink keeps away the processor from overheating by absorbing its heat and
dissipating it in air.
TYPES OF MICROPROCESSOR
1. Complex instruction set computing (CISC)
2. Reduced instruction set computing (RISC)
1. CISC ARCHITECTURE:
It is a special instruction set architectur in which each instruction can execute several low-level
operations such as load from memory, an arithmetic operations and a memory store, all in a single
instruction. Since each instruction is performing two or more primitive operations inside the processor,
it is called complex instruction set.

Prepared By: Sushma Shetty
35 www.vtulife.com


CHARACTERISTICS:
1. Emphasis is on hardware.
2. All instructions are executed in two or more clock cycles.
3. Variable instruction format demanding more decoding locgic and time.
4. Easy to program.
5. Complex data types were handled in hardware.
2. RISC ARCHITECTURE:
It utilizes a small, highly optimized set of instructions. The idea here is simplified instructions can provide
higher performance by faster execution of each instruction.
CHARACTERISTICS:
1. Emphasis is on software.
2. All instructions are executed in one clock cycle.
3. Uniform instruction format demanding less decoding logic and time.
4. Difficult to program.
5. Few data types in hardware.
CISC PROCESSOR RISC PROCESSOR
Instructions are complex Instructions are simple
Program code size is smaller Program code size is lengthier
Increased hardware circuitry and leads to
increased processor size
Reduced hardware circuitry and leads to reduced
processor size
It is less memory intensive More memory intensive
Power consumption is more Power consumption is less
More heat is generated Less heat is generated









Prepared By: Sushma Shetty
36 www.vtulife.com


UNIT 3

FUNDAMENTALS OF PROBLEM SOLVING
INTRODUCTION TO COMPUTER LANGUAGES
PROGRAM: The set of instructions given to the computer to achieve a specific task.
PROGRAMMING: process of providing instructions to solve a specific problem.
PROGRAMMER: person who writes the program.
PROGRAMMING LANGUAGE: the language that is used to write a program.
TYPES OF LANGUAGES:
machine level language
assembly level language
high level language
1. MACHINE LEVEL LANGUAGE
It is a set of instructions given to a computer in the form of 0s and 1s.
It is the language of computers.
ADVANTAGES:
o Faster execution
o Translator is not required. Since machine language is the language of computers, it can
execute.
DISADVANTAGES:
o Difficult to remember machine instructions.
o Difficult to read and write machine language programs.
o Very difficult to debug, correct and modify the program.
o Machine dependent and not portable ie its machine dependent program, program
written for one machine may not be run in other with a different processor.
o It is unstructured language.
2. ASSEMBLY LEVEL LANGUAGE
Also called as symbolic language.
A set of instructions given to a computer in the form of symbolic names or mneumonics.
Eg:
o ADD R1, R2 // adds values in register R1 and R2 and saved in R1
o MUL R1, R2

Prepared By: Sushma Shetty
37 www.vtulife.com


ADVANTAGES:
o Easy to remember symbolic names than machine codes.
o Program understanding, modification is easier compared to machine codes.
o Simple and easy compared to machine language.
o Execution of the same speed as to a equivalent machine language.
DISADVANTAGES:
o A translator is required. It is called as an assembler for assembly level language.
o It is machine dependent.
o It is unstructured language.
o Difficult to understand and debug compared to high level languages.
ASSEMBLER: Its a translator which translates the program written in assembly language into
machine language so that the computer can understand. For each assembly language
instruction, corresponding machine instruction is generated.


3. HIGH LEVEL LANGUAGES
It is written written using symbols and words just like English language.
It enables the programmer to write machine independent code.
Easy to read, write and maintain.
They are portable.
ADVANTAGES:
o Easy to understand.
o Easy to read, write and modify.
o Code is compact and self explanatory.
o They are machine independent programs.
DISADVANTAGES:
o Takes more time to execute compared to machine language or assembly language.
o Translator is required.
COMPILER:
It is a translator which accepts the program written in high level language and produces the
corresponding machine language program (machine code).
The compilation process is shown below

Prepared By: Sushma Shetty
38 www.vtulife.com



The compiler after accepting the program written in high level language, checks for the errors
introduced by the programmer. Appropriate error messages are displayed.
The errors can be corrected and compiled again until there are no errors in the program. Then
the program is converted to machine code.
Eg: Turbo C, Visual C/C++, gcc
CREATING AND RUNNING PROGRAMS:
The steps involved in creating and running programs are:
1. Writing and editing programs
2. Compiling programs
3. Linking programs
4. Program execution
1. WRITING AND EDITING PROGRAMS
The software used to write programs is called as an editor.
Using a text editor the following operations can be performed:
o We can type the program, modify and store the program.
o To correct the program we must be able to move the cursor in desired position. Its done
using the cursor keys.
o We should have familiarity of the complete editor by knowing various commands to
modify such a search and replace etc.
The file which is inputto the compiler is the source file.
In Turbo C, the shortcut key is F2.
2. COMPILING A PROGRAM
Once we type a program, after completion we have to convert it into machine codes using a
compiler (for a C program).
In Tubo C, the shortcut key is ALT+F9.
3. LINKING A PROGRAM
After compilation, the object program consisting of machine language is created, but cannot be
directly executed.
The object code created must be combined to get an executable code.
In our C programs, we use library files, they must be linked before execution.
In Turbo C, the shortcut key is Ctrl+F9.

Prepared By: Sushma Shetty
39 www.vtulife.com


4. PROGRAM EXECUTION
The program can be executed and the result can be displayed on the output screen or a output
device.
SYSTEM DEVELOPMENT LIFE CYCLE:
The model which is commonly used is the waterfall model.

System requirements: In this phase, all the requirements, which are necessary to accomplish
the proposed system are identified. The requirements are usually stated in terms that are
understood by a user.
Analysis: In this phase, the problem stated in the form of requirements is analyzed precisely and
completely and we look at different alternatives from system point of view.
Design: This phase will determine how the system will be built. The individual functions that
make up the system are determined and the solution will be expressed in the form of algorithm
or flowchart, etc.
Code: In this phase, the algorithm will be converted into programs using any of the
programming language. These programs have to be tested by the programmer for his/her
satisfaction.
System Test: In this phase, all the programs and functions are tested together to make sure the
system works as a whole. The results obtained will be compared with the test data that is
prepared manually to make sure that system is working as expected by meeting the
requirements identified in requirement phase.
Maintenance: After the program is implemented, it should be properly maintained, ie taking
care of the changing requirements of its users and systems. The program should be regularly
updated or enhanced by adding additional capabilities.
In any of the above phases, if any errors are identified, it has to be corrected by going back to
the previous phase. Otherwise continue to the next phase.

Prepared By: Sushma Shetty
40 www.vtulife.com



INTRODUCTION TO C LANGUAGE
INTRODUCTION
C language is a high level language.
Reasons for C language to be popular:
o C is a structured programming language.
o It is a high level language and hence easy to understand.
o It has wide variety of operators using which a program can be written easily to solve a
given problem.
o Helps us to develop efficient programs.
o C is machine independent. The program written on one machine will run on other
machine also.
o C program can be executed on many different hardware platforms.
BACKGROUND/ HISTORY:
The C language is derived from various languages as shown below:
ALGOL: It is the first block structured language but never gained wide
acceptance in USA.
BCPL (Basic Combined Programming Language) : the introduction of ALGOL
gave way to the development of structured programming language designed by
Martin Richards.
B: Ken Thomson developed a new language on similar lines of BCPL called B
language. The first version of UNIX operating system is developed using B language.
C : Dennis Ritchie developed C language in 1972. It inherited many concepts
from ALGOL, BCPL, B. but the concept of data types was newly introduced.
ANSI (American National Standards Institute): introduced standards for C
language in 1989. This standard was adopted by ISO in 1990.
C++ : has all the features of C language along with concept of objects,
polymorphism, inheritance etc. C is procedure oriented whereas C++ is object
oriented.
STEPS TO LEARN C LANGUAGE:
Learn alphabets of C language.
Learn how one or more alphabets can be grouped together to form meaningful words. These
meaningful words are tokens.

Prepared By: Sushma Shetty
41 www.vtulife.com


Learn how one or more words are grouped together to form
meaningful sentences. These sentences are called instructions or
statements.
Learn how one or more sentences can be grouped together to form
paragraphs. These constitute a complete program.
1. CHARACTER SET (ALPHABETS OF C)
Any symbol that is used while writing a C program is called a
character or an alphabet. It can be a letter, digit or a special symbol.
All the characters that are used while writing C programs are called
alphabets or character set.
o Eg for alphabets:
Lower case letters: a b c . z
Upper case letters: A B C. Z
Digits: 0 to 9
Symbols such as ~ tilde, ^ caret, - minus, + plus sign
etc..
White spaces: character such as space, tab(\t), new line (\n), carriage return (\r)
etc
2. C TOKENS
A token is a smallest or a basic unit of a C program. One or more characters are grouped in
sequence to form meaningful words. These meaningful words are tokens.
Classification:
o Keywords: if, for, while, etc
o Identifiers: sum, length, i etc
o Constants: 10, 10.5, a, strng etc
o Operators: +, -, *, / etc
o Special symbols: [], {}, () etc
Tokens involving single characters: +, -, *, /
Tokens involving two characters: ++, <=, >=
Tokens involving more than two characters: 100, length, 10.5 etc
Using these tokens, meaningful instructions are framed for a program.
KEYWORDS
The tokens with predefined meaning in C language are called keywords.
They are reserved for specific purpose and hence they are called as reserved words.
The keywords available are:

Prepared By: Sushma Shetty
42 www.vtulife.com




Rules to be followed while using keywords are:
o They should not be used as variable names, function names, array names etc.
o The meaning of keywords cannot be changed by the user.
o All keywords are written in lower case letters.
IDENTIFIERS
Need for identifiers:
o In computer memory, the data and instructions can be stored. Each piece of data or the
instructions is stored at unique address in the memory of the computer. So its difficult
for us to:
Access data or instructions using these addresses.
Manipulate data using these addresses.
Keep track of addresses of data stored in the memory.
o These disadvantages are overcome by using identifiers.
Identifiers are the names given to various program elements such as variables, constants,
function names, array names etc.
It is a word consisting of sequence of one or more letters or digits along with _ (underscore).
Some rules to frame identifiers:
o First character should be a letter or underscore.
o No extra symbols are allowed other than letters, digits, _
o Length can be maximum of 31 charaters.
o Reserved words cannot be used as identifiers.
o They are case sensitive. SUM is not equal to sum.
Difference between keywords and identifiers:
KEYWORDS IDENTIFIERS
It has predefined meaning in a language. They are
used for specific purpose in a language and hence
they are also called as reserved words.
They do not have pre defined meaning.
They are the instructions given to the compiler. They are not instructions given to the compiler.

Prepared By: Sushma Shetty
43 www.vtulife.com


They are names introduced into a program.
Eg: if, for, while Eg: sum, length, I, j, sum_calc

CONSTANTS
It is a data item that does not change during the execution of a program. They cannot be
modified in the program.
Classification:

1. INTEGER CONSTANT
An integer is a whole number without any fraction part. No extra characters allowed other than
+ and sign.
If + and are there, they shoud precede the number, indicating a positive or a negative number.
Types:
o Decimal : combination of digits from 0 to 9. It is a base 10 number.
valid: 1000, 1354, 234, -9877, +65
invalid: 10,000 (no comma), 0.5 (decimal), 10 20 (space), 085 (prefix zero not allowed).
o Octal : is a combination of digits from 0 to 7. It is a base 8 number.
valid: 010, 0777, -065
invalid: 10,000, 0.5, 10 20, 085 (digit 8), 777 (should have prefix 0).
o Hexadecimal : combination of digits from 0 to 9, also alphabets from A to F or a to
f. it is a base 16 number. It must be preceded by 0X or 0x.
valid: 0X12A, 0x13A, 0X a98
invalid: 10,000, 0Xabgh, 0x12c.ab, 0123
2. FLOATING POINT CONSTANT
They are base 10 numbers with fraction part such as 10.5

Prepared By: Sushma Shetty
44 www.vtulife.com


No characters other than + and allowed (only as prefix to indicate positive or negative integer).
Types:
o Fractional form : integer part followed by a dot and a fractional part. Eg: 0.5, 9.5, 34.09,
-122.7623, -9. , +.9
o Scientific notation : represented using scientific notation (exponential notation) has 3
parts:
Mantissa: eg: 9.86
e/E: eg: e, E
exponent: 3
which is equal to 9.86 X 10
3
the mantissa can be integer or a floating point number. Exponent has to be an
integer.
3. CHARATER CONSTANT
a symbol enclosed within a pair of single quotes is called character constant.
Each character is associated with a unique value called an ASCII (American Standard Code for
Information Interchange) value.
CHARACTER CONSTANT VALID/INVALID REASONS FOR INVALIDITY
9 valid -
a Valid -
$ Valid -
\n valid Escape character
9 invalid Double quotes not allowed
99 invalid Two characters not allowed

4. BACKSLASH CONSTANTS (ESCAPE SEQUENCE CHARACTERS)
An escape sequence character begins with a backslash and is followed by one character.
A backslash(\) along with some characters give rise to special print effects by changing the
meaning of some characters.
Since an escape sequence character starts with backslash, they are called backslash constants.
CHARACTER ESCAPE CHARACTER MEANING
Bell \a Beep sound
Backspace \b Cursor moves towards left one position
Horizontal tab \t Cursor moves right by 8 positions
Vertical tab \v This is usually not supported
Newline \n Cursor moves to the beginning of new line
Form feed \f Not supported by some compilers
Carriage return \r Cursor moves towards beginning of current line
Quotation mark \ Double quote
Apostrophe \ Single quote
Question mark \? Question mark

Prepared By: Sushma Shetty
45 www.vtulife.com


Backslash \\ Back slash
NULL \0 Null character

5. STRING CONSTANT
A sequence of characters enclosed within a pair of double quotes is called string constant. The
string always ends with NULL character denoted as \0.
It is enclosed in double quotes.
STRING CONSTANT VALID/INVALID REASONS FOR INVALIDITY
9 Invalid Must be enclosed within
9 Valid -
pace Valid -
\n Valid -
pace Invalid Must be enclosed within
pace cs Valid -
Valid Empty string
CODING CONSTANTS
The data values that cannot be changed during execution of the program are called constants.
The constants can be directly used in the program.
Three different ways to code constants:
o Literal constants
o Defined constants
o Memory constants
1. LITERAL CONSTANTS
The constants which do not have any name are called literal constants ie literal is an unnamed
constant used to specify the data.
A Character literal
9 Numeric literal
3.56 Numeric literal
Sum+10 10 is numeric literal
RAMA String literal

2. DEFINED CONSTANTS
The names that can be used as a substitute for constants such as integer constant or character
constant or floating point constant or a string constant are called symbolic constants. They are
also called symbolic names.
Since these constants are defined using preprocessor command define, they are also called as
defined constants.

Prepared By: Sushma Shetty
46 www.vtulife.com


Eg:
#define MAX_LENGTH 1024
Define the symbolic constants at the beginning of the program even if we can define it
anywhere in between the program. For easy understanding.
To distinguish between symbolic constants and other variables, its written in upper case.
Eg prog:
#include<stdio.h>
#define PI 3.14
int main()
{
printf(pi value is %f,PI);
return 0;
}
3. MEMORY CONSTANTS
The values stored in variables that cannot be changed are called memory constants or named
constants. The memory constants have to be initialized when defining the variables using the
qualifier const.
Eg:
const float pi=3.14
o pi value cannot be changed.
o The compiler generates necessary machine instructions to allocate 4 bytes of memory
space and store the value 3.14 in it.
o The qualifier const indicate that the data stored in that memory space cannot be
modified.
o If compiler encounters a statement trying to modify the value, it results in an error.
Eg:
const float pi;
pi=3.14 //error
OTHER TOKENS
Operators
Special symbols
RANGE OF INTEGER
Integers are classified into:
o Unsigned integer
o Signed integer
1. RANGE OF UNSIGNED INTEGER
Consider the table which shows representation of decimal numbers in binary using only 3 bits.

Prepared By: Sushma Shetty
47 www.vtulife.com



Minimum number




Maximum number
3 bit unsigned number ranges from 0 to 7 (min to max)
=0 to 8-1
=0 to 2
3
-1
So, 3 bit unsigned number range = 0 to 2
3
-1
4 bit unsigned number range= 0 to 2
4
-1
8 bit unsigned number range= 0 to 2
8
-1
In general, n bit unsigned range= 0 to 2
n
-1
For 16 bit machine, range = 0 to 65535
It can be represented in the form of a circle:


(65535+1)%65536=0
(65535+2)%65536=1
.
.
Eg: unsigned int n=300;
2. RANGE OF SIGNED INTEGER
Positive numbers using 3 bit:
BINARY DECIMAL
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7

Prepared By: Sushma Shetty
48 www.vtulife.com



o Sign bit( first bit) : 0 represents positive integer. So positive integer range 0 to 3.
Negative numbers using 3 bit:

o Sign bit( first bit) : 1 represents negative integer. So range = -4 to -1
Using 3 bits range = -4 to +3
= -2
3-1
to 2
3-1
-1
Using 4 bits range = 2
4-1
to 2
4-1
-1
In general, for n bit = 2
n-1
to 2
n-1
-1
BASIC/SIMPLE/PRIMITIVE DATA TYPES
The data type defines the type of data stored in a memory location. The data type determines
how much memory should be allocated for a variable.
Various types of data such as integer constant, floating point constant, character constant etc.
can be stored in memory during execution of a program.
Data types classification:
o Primitive data types or fundamental data types.
o Derived data types: Derived data types are derived from the fundamental data type.
Some of the derived data types are short int, long int, long double etc.
PRIMITIVE DATA TYPES
The data types that can be manipulated by machine instructions are called primitive data types.
Classification:
o Char (character value)
o Int (integer value)
o Float (Floating point value)
o Double (Double floating point value)
o Void (Valueless)

Prepared By: Sushma Shetty
49 www.vtulife.com


INT
In addition, there are a number of qualifiers that can be applied to these basic types. short and
long apply to integers:
o int a;
o short int sh;
o long int counter;
int will normally be the natural size for a particular machine.
short is often 16 bits long, and int either 16 or 32 bits. Each compiler is free to choose
appropriate sizes for its own hardware, subject only to the the restriction that shorts and ints
are at least 16 bits, longs are at least 32 bits, and short is no longer than int, which is no longer
than long.
The standard headers <limits.h> and <float.h> contain symbolic constants for all of these sizes,
along with other properties of the machine and compiler.
ADVANTAGES:
Since integer constants are exact quantities, they are used for
o counting.
o Indexing.
DISADVANTAGES:
o Higher range of numbers cannot be represented.
o The numbers with fractional part cannot be represented and stored.
FLOAT
It is a keyword used to define floating point numbers in C language.

N bit machine Size of float Range of float
16 bit machine 4 bytes 3.4E-38 to 3.4E38
32 bit machine 8 bytes 1.7E-308 to 1.7E308

ADVANTAGES:
o The numbers with fractional part or decimal points can be stored.
o Higher precision and range when compered to integers.
DISADVANTAGES:
o They are not exact quantities and hence not used for counting, indexing.
o Floating point numbers occupying more that 4 bytes cannot be represented.
o Precision of more than 6 digits after the decimal point is not possible.
o Floating point numbers are represented approximately by most computers.
DOUBLE
It is a keyword used to define long floating point numbers in C language. It is treated as long
floating point number.

N bit machine Size of double Range of double
16 bit machine 8 bytes 1.7E-308 to 1.7E308
32 bit machine 16 bytes 3.4E-4932 to 1.1E4932

ADVANTAGES:
o Higher precision and range when compared to floating point numbers.

Prepared By: Sushma Shetty
50 www.vtulife.com


DISADVANTAGES:
o Not used for counting, indexing.
o These numbers are represented approximately by most of the computers.
CHAR
Keyword which is used to define single character or a sequence of characters called string in C
language.
This is a group of 8 data bits.
'C' represents either a letter of roman alphabet.
Small integer in the range of 0 through to +255.
To give a named memory area in which a single letter has to be stored
Declaration:
char letter;
ADVANTAGES:
o Used to represent characters or strings.
VOID
Empty data type. It does not occupy any space in memory.
Declare explicitly that a function is not returning a value
Declare explicitly that a function has no parameter
Create generic pointer
'C' also supports several aggregate types including structure ,union ,enumeration and user
defined types.

Prepared By: Sushma Shetty
51 www.vtulife.com




VARIABLES
A variable is a named data storage location in computers memory. By using a variable name we
are referring to the data stored in the location. A value that changes during the execution of the
program is called variable.
Rules of variables defining in C:
o The variable name is a combination of alphabets, digits, underscore etc.
o The first character in the variable name must be an alphabet.
o A keyword cannot be used as variable name
o No comma or blanks are allowed in variable name.
o No special symbols ($, #) other than underscore can be used in variable name.
o Uppercase & lowercase letters are distinct i.e. case sensitive
o A variable name cant start with digit.

Prepared By: Sushma Shetty
52 www.vtulife.com


o The maximum length of variable name should be 8 characters long in DOS based program &
in ANSI C it supports up to 31 characters long.
A variable should be defined before it is used in the program
Example: data-type var-list;
Data type must be valid data type and var-list may be consist of one or more identifier names
separated by commas operator.
The defining indicates the compiler about the variable names and types of data. It is a method
of informing the compiler to reserve the memory space for the data based on the type of the
variables.
Example : int count;
double balance;
float amount;
int, double,and float are keywords and cannot be used as variable names.
Initialising: Values can be assigned to variable using the assignment operator (=).
var-name=expression;
An expression can be a single constant or combination of variables,operators and constants.
Data-type var-name=constant;
Eg: int value=250;
Int a=58,b=90;
char name= pace
double amount =76.80
Declaring: the variables can be declared without allocating the memory. Its possible by type
declaration.
Type declaration is a method of informing the compiler about the type of data to be stored in a
variable. Using type declaration, the compiler knows that the variables are used in the current
file but are defined in some other file.
o Syntax:
Extern data_type a1,a2,.an;
Where, extern is a keyword.
A1,a2,an are variable names.
Data_type is the type of variables such as int, float etc.
TYPES OF VARIABLES:
Integer variable: if integer value has to be stored in the memory, then define the variable as
type int. it occupies 2 bytes of memory in turbo C compiler.
Floating point variable
Character variable
Double variable
DIFFERENCE BETWEEN KEYWORDS AND VARIABLES

KEYWORDS VARIABLES
They have predefined meaning in a language.used Do not have predefined meaning in a language.

Prepared By: Sushma Shetty
53 www.vtulife.com


for specific purpose, hence called reserved words.
Instructions given to the compiler. Names given to memory locations. During
compilation, compiler determines the size of data
to be stored in the variable depending on the data
type.
Keywords are not used to store the data. Used to store the data.
Eg: if,else, while, for Eg: a, b, length

C PROGRAMS:

The structure of C program is shown below:

preprocessor directives: or pre-compiler directives.
Begins with a # symbol.
eg: #include<stdio.h>
the preprocessor inserts the contents of file stdio.h at that
point.
Global declarations: variables defined immediately
after pre processor directives. It is visible to all parts of the
program.
Main(): every c program must have a main function
from where the execution begins. The main function is divided
into 2 parts:
o Declaration section/ local definitions.
o Executable section.
Local definition: the variables used within the main()
must be declared.
Executable section: these are building blocks of the
program. They represent instructions given to the computer to
perform specific task.

A C PROGRAM:
In C, the program to print ``hello, world'' is

#include <stdio.h>
main()
{
printf("hello, world\n");
}


Just how to run this program depends on the system you are using. As a specific example, on the
UNIX operating system you must create the program in a file whose name ends in ``.c'', such as
hello.c, then compile it with the command

Prepared By: Sushma Shetty
54 www.vtulife.com


gcc hello.c
in the terminal.
If you haven't botched anything, such as omitting a character or misspelling something, the
compilation will proceed silently, and make an executable file called a.out. If you run a.out by
typing the command
a.out
In turbo C,
Save the program, compile by pressing Cntrl+F9
See the output by pressing Alt+F5.
COMMENTS
Used for documenting the program and are ignored by the compiler during compilation.
Comment statements doesnt compile by the computer.
Comments /*..*/
In C, /* is called opening comment mark and */ is closing comment mark.
It helps us to:
o Read and understand the logic of the program.
o Helps to maintain and modify program easily.
SOFTWARE ENGINEERING AND PROGRAMMING STYLE

Software engineering is the establishment and use of sound engineering methods and principles
to obtain software that is reliable and that works on real machines.
This definition, from the first international conference on software engineering in 1969, was
proposed 30 years after the first computer was built. During this period, software was more of
an art then a science.
The following concepts are discussed:
o Program documentation
o Data naming
o Data hiding
Program documentation: it is usually done in two levels:
o General documentation: it must be present in the beginning of every C program with
following information in the order specified:
Each program should start with general description of the program.
Provide the name of the author and the date the program was written.
Change history: it consists of reasons for modifying the earlier program. If no
change occurs, then change history wont be there.
o Module documentation: this should be present in every C program with the following
information:
Include brief description of every block used in the program.
If a block is complex, write a short one/ two line description of the operations
being performed.
o Data names: The use of data names is another good principle of good structured
programming. The guidelines to be followed are:
Use meaningful variable names.

Prepared By: Sushma Shetty
55 www.vtulife.com


The names should match the terminology of the user.
To combine two or more words into a meaningful word, use underscore.
eg: sumofmarks can be written as sum_of_marks as a variable.
Do not use variable names that differ by one or two variables. Eg: a1,a2,a3.
Use appropriate abbreviations.
Avoid usage of generic names.
Use symbolic constants for the characters that are difficult to read and
understand in a program.
eg: #define PI 3.14
o Data hiding: the data should not be visible for all the functions used in the program. The
data must be hidden to protect the data from accidental destruction. So avoid the usage
of global variables in the program.
COMMON ERRORS:
Forgetting to put a break in a switch statement.
Using = instead of ==
Scanf errors:
o Forgetting to put an ampersand(&) on arguments
o Using the wrong format for operand.
Size of arrays.
Integer division
Loop errors.
Not using prototypes.
Not initializing pointers.
String Errors
o Confusing character and string constants.
o Comparing strings with ==.
o Not null terminating strings.
o Not leaving room for the null terminator.
Input /output errors
o Using getc(), getchar(), etc. incorrectly.
o Using feof() incorrectly.
o Leaving characters in the input buffer.
Using keywords as identifiers in the program.



INPUT AND OUTPUT FUNCTIONS
DEFINITION:
The input functions accept the data from input devices like the keyboard, mouse and store in
memory locations. Eg: scanf(), getch(), getchar(), gets().

Prepared By: Sushma Shetty
56 www.vtulife.com


The output functions receive the data from memory locations and display on the monitor or any
other output device. Eg: printf(), putch(), putchar(), puts().

Steps or activities (refer above figure)
o Data is entered from keyboard.
o The data is stored in temporary memory called keyboard buffer. It holds characters until
we press enter.
o Keyboard function converts data into appropriate data type and stored in memory
locations using variables.
o Using output functiuon, it is read from memory and stored in temporary storage area
called screen buffer.
o This data is then visible on the screen.
TYPES OF INPUT OUTPUT FUNCTIONS

A text stream is a sequence of characters divided into lines; each line consists of zero or more
characters followed by a newline character. It is the responsibility of the library to make each
input or output stream confirm this model; the C programmer using the library need not worry
about how lines are represented outside the program.

Prepared By: Sushma Shetty
57 www.vtulife.com


The standard library provides several functions for reading or writing one character at a time, of
which getchar and putchar are the simplest. Each time it is called, getchar reads the next input
character from a text stream and returns that as its value. That is, after
c = getchar();
the variable c contains the next character of input.
The function putchar prints a character each time it is called:
putchar(c);
prints the contents of the integer variable c as a character, usually on the screen. Calls to
putchar and printf may be interleaved; the output will appear in the order in which the calls are
made.
Each source file that refers to an input/output library function must contain the line
#include <stdio.h>
An eg code:
#include <stdio.h>
#include <ctype.h>
main() /* lower: convert input to lower case*/
{
int c
while ((c = getchar()) != EOF)
putchar(tolower(c));
return 0;
}

Getch(), getche(), putch():
o Whenever we want to read a character from the keyboard without echo (typed
character will not be visible on the screen) we use getch() function. The character will be
stored in memory location.
o If we want the character to be displayed, use getche().
o To display the character stored in memory location on the screen, use putch() function.
Gets() and puts():
o Whenever we want to read a sequence of characters from the keyboard with spaces in
between and store them in memory locations, then gets() function is used.
o Whenever we want to display a sequence of characters stored in memory locations on
the screen, then puts() function is used.
o Syntax: gets(str);
reads a string of characters from the keyboard till the user presses enter key.
o Syntax: puts(str);
displays the string str on the screen.

getchar() Reads a character from the keyboard and waits for the user to type ENTER
key.
getch() Reads a character from the keyboard and does not wait for the user to type
ENTER key. Character entered will not be visible.
getche() Reads a character from the keyboard and does not wait for the user to type
ENTER key. Character entered will be visible.
gets() Reads a string from the keyboard and waits for the user to type ENTER key.
putchar() Displays a character on the screen.

Prepared By: Sushma Shetty
58 www.vtulife.com


putch() Displays a character on the screen.
puts() Displays a string on the screen.

ADVANTAGES AND DISADVANTAGES OF UNFORMATTED I/O

ADVANTAGES:
o Very easy to use unformatted I/O functions.
o A single character or a sequence of characters can be easily read into memory or easily
be displayed on the screen using unformatted I/O functions.
DISADVANTAGES:
o It is not possible to read/print any other data except characters ie it is not possible to
read/print integer numbers, floating point numbers etc.
o It can be overcome using formatted I/O functions such as printf() and scanf().
FORMATTED INPUT FUNCTION scanf()

Data entered from keyboard will be treated as sequence of characters.
Even if we enter integer data such as 1234 or floating point numbers 3.14, they are treated as
characters.
Thus, they must be converted into appropriate data type and stored in memeory.
This is done using scanf().
Syntax: scanf(format string,address list);
Eg: scanf(%d%f%c,&x,&y,&z);
%d converts input data to decimal and stores in in address of x.
%f converts input data to floating point and stores in in address of y.
%f converts input data to character and stores in in address of z.
The return value is number of items read from keyboard.

FORMAT SPECIFIERS IN scanf()

The format string usually contains conversion specifications, which are used to control conversion of
input. The format string may contain:
Blanks or tabs, which are not ignored.
Ordinary characters (not %), which are expected to match the next non-white space character of
the input stream.
Conversion specifications, consisting of the character %, an optional assignment suppression
character *, an optional number specifying a maximum field width, an optional h, l or L
indicating the width of the target, and a conversion character.


Prepared By: Sushma Shetty
59 www.vtulife.com




The conversion characters d, i, o, u, and x may be preceded by h to indicate that a pointer to
short rather than int appears in the argument list, or by l (letter ell) to indicate that a pointer to
long appears in the argument list.
example, the rudimentary calculator:
#include <stdio.h>
main() /* rudimentary calculator */
{
double sum, v;
sum = 0;
while (scanf("%lf", &v) == 1)
printf("\t%.2f\n", sum += v);
return 0;
}

Suppose we want to read input lines that contain dates of the form
25 Dec 1988
The scanf statement is
int day, year;
char monthname[20];
scanf("%d %s %d", &day, monthname, &year);
No & is used with monthname, since an array name is a pointer.
Literal characters can appear in the scanf format string; they must match the same characters in
the input. So we could read dates of the form mm/dd/yy with the scanf statement:
int day, month, year;
scanf("%d/%d/%d", &month, &day, &year);
scanf ignores blanks and tabs in its format string. Furthermore, it skips over white space (blanks,
tabs, newlines, etc.) as it looks for input values. To read input whose format is not fixed, it is
often best to read a line at a time, then pick it apart with scanf.
A final warning: the arguments to scanf and sscanf must be pointers. By far the most common
error is writing

Prepared By: Sushma Shetty
60 www.vtulife.com


scanf("%d", n);
instead of
scanf("%d", &n);
This error is not generally detected at compile time.
THE FORMATTED OUTPUT USING printf()

The data stored in memory locations (or variables) will be in machine language.
They must converted into appropriate data type such as integer or floating point number and
then converted into data which has to be displayed on screen for human understanding in
proper format.
It can be done by printf().
Syntax: printf(format string,list of variables);
Eg: printf(%d is a number,x);
The value of x say 8. Then,
8 is a number
will be displayed on the screen while execution.

FORMAT SPECIFIERS USED IN printf()

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, if left adjustment is
called for) 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 be 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 (letter ell) if as a long.
Conversion characters are shown in Table. If the character after the % is not a conversion specification,
the behavior is undefined.


Prepared By: Sushma Shetty
61 www.vtulife.com




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 chapters. One exception is the
precision as it relates to strings. The following table shows the effect of a variety of
specifications in printing ``hello, world'' (12 characters).
We have put colons around each field so you can see it extent.
:%s: :hello, world:
:%10s: :hello, world:
:%.10s: :hello, wor:
:%-10s: :hello, world:
:%.15s: :hello, world:
:%-15s: :hello, world :
:%15.10s: : hello, wor:
:%-15.10s: :hello, wor :
A warning: printf uses its first argument to decide how many arguments follow and what their
type is. It will get confused, and you will get wrong answers, if there are not enough arguments
of if they are the wrong type. You should also be aware of the difference between these two
calls:
printf(s); /* FAILS if s contains % */
printf("%s", s); /* SAFE */
The function sprintf does the same conversions as printf does, but stores the output in a string:
int sprintf(char *string, char *format, arg1, arg2, ...);
sprintf formats the arguments in arg1, arg2, etc., according to format as before, but places the
result in string instead of the standard output; string must be big enough to receive the result.


Prepared By: Sushma Shetty
62 www.vtulife.com


THE ADDRESS OPERATOR (&)

The user can obtain address of a variable in the memory. To obtain the address of a variable the
address operator denoted by symbol & is used.
Eg:
p=&a;
Where p and a are variables. The address of a will be stored
in p when this instruction is executed.

let address of variable a be 1002. Then 1002 will be stored
in p.
when

printf(%d and %d, %d,a,p,&a);

is executed it prints

10 and 1002, 1002

On the output screen.




























Prepared By: Sushma Shetty
63 www.vtulife.com


UNIT 4

STRUCTURE OF A C PROGRAM
EXPRESSIONS
OPERATOR:
It is a symbol or a token that specifies the operation to be performed on various types of data. Ex: +, -, *
OPERAND:
A constant or a variable or a function which returns a value is an operand. An operator may have one or
two o three operands.
EXPRESSION:
A sequence of operands and operators that reduces it to a single value on solving it is an expression.
Eg: a+b-c*a/2
CLASSIFICATION OF OPERATORS
It is classified based on:
1. The number of operand on operator has.
2. The type of operation being performed.
1. BASED ON NUMBER OF OPERANDS
OPERATOR TYPES:
1. Unary operators: ++, -- etc
2. Binary operators: +, -, *, / etc
3. Ternary operators: ? and :
4. Special operators: comma(,), sizeof() etc
a. UNARY OPERATOR:
An operator which acts on only one operand to produce the result. Eg: -10, -a, *b, a++ etc.
b. BINARY OPERATOR:
An operator which acts on two operands to produce the result. Eg: a+b, a*b.
c. TERNARY OPERATOR:
An operator which acts on three operands to produce a result. Eg: a?b:c

Prepared By: Sushma Shetty
64 www.vtulife.com


2. BASED ON TYPE OF OPERATION
TYPES OF OPERATORS:
1. Arithmetic operators. Eg: +, *, - etc
2. Assignment operators. Eg: =, += etc
3. Increment/Decrement operators. Eg: ++, --
4. Relational operators. Eg: <, <= etc
5. Logical operators. Eg: &&, || etc
6. Conditional operators. Eg: ?:
7. Bitwise operators. Eg: &, ^ etc
8. Special operators. Eg: , ,[] etc
1. ARITHMETIC OPERATORS:
The operators that are used to perform arithmetic operations such as addition, subtraction,
multiplication, division and modulus operations are called arithmetic operators. These operators
perform operation on two operands and hence are binary operators.
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus
2. ARITHMETIC EXPRESSIONS:
An expression is a sequence of operands and operators which when evaluated results in a single value.
Two types:
1. Additive expressions. Eg: a+b, a-b
2. Multiplicative expressions. Eg: a*b, a/b, a%b
3. TYPE CONVERSION:
In C language, a programmer can instruct the compiler to convert the data from one data type to
another data type. This process is called type conversion.
1. Implicit conversion. Eg: .0 gets converted to 1.0/2.0
2. Explicit convertion. Eg: 1/(float)2 gets converted to 1.0/2.0
Example program:
#include <stdio.h>
int main()
{
int m1=75, m2=85;
float avg;

Prepared By: Sushma Shetty
65 www.vtulife.com


avg=(float)(m1+m2)/2;
return 0;
}
4. MODES OF ARITHMETIC EXPRESSIONS:
1. Integer expressions
2. Floating point expressions
3. Mixed mode expressions
INTEGER EXPRESSIONS:
If all the operands in an expression are integers, the expression is called integer expression. Eg: 4/2=2,
2+5=7.
FLOATING POINT EXPRESSION:
If all the operands in an expression are floating point numbers or double values, it is floating point
expression. Eg: 4.0/2.0=2.0
MIXED MODE EXPRESSIONS:
An expression that has operands of different data types is called mixed mode expressions. Eg:
4.0/3=1.333
5. ARITHMETIC OPERATORS PRECEEDENCE:
BODMAS rule:
Highest to lowest:

6. ASSOCIATIVITY OF OPERATORS:
In programming languages and mathematical notation, the associativity (or fixity) of an operator is a
property that determines how operators of the same precedence are grouped in the absence
of parentheses.
1. Left associativity (left to right): operators are grouped from the left.

Prepared By: Sushma Shetty
66 www.vtulife.com


2. Right associativity (right to left): operators are grouped from the right.

7. RELATIONAL OPERATORS:
The operators that are used to find the relationship between two operands are called relational
operators.
1. Less than ( < )
2. Less than or equal to ( <= )
3. Greater ( > )
4. Greater than or equal to ( >= )

Prepared By: Sushma Shetty
67 www.vtulife.com


5. Equal ( == )
6. Not equal ( != )
Associativity for all above is left to right.
Relational expressions Results (True/False) output
3>2 TRUE 1
2<3 TRUE 1
2>5 FALSE 0
6==6 TRUE 1
6+2>17 FALSE 0
8!=8 FALSE 0
7. LOGICAL OPERATORS:
If the data value is 0, it is considered false. Else it is true. The operators that are used to combine two or
more relational expressions are called logical operators. Logical operatora are used to combine two or
more relational expressions. The output will be either true or false.
1. Unary operator ( ! )
2. Binary operator ( && , || )
Left to right associativity for both.
1. Logical NOT ( ! ):
OPERAND !OPERAND
True (1) False (0)
False (0) True (1)

2. Logical AND ( && ):
Operand1 AND Operand2 Result
true && true = True
true && False = False
False && True = False
false && false = False

3. Logical OR ( || ):
Operand1 OR Operand2 result
false || False = False
false || True = True
True || False = True
true || true = true

Prepared By: Sushma Shetty
68 www.vtulife.com


8. ASSIGNMENT OPERATORS:
An operator which is used to assign the data or result of an expression into a variable (also called
memory location) is called an assignment operator. It is denoted by = sign. A statement with
assignment operator is called assignment statement or assignment expression.
Three types:
1. Simple assignment statement. eg:a=a+10
2. Shorthand assignment statement. Eg: a+=10
3. Multiple assignment statement. Eg: a=b=10

1. SIMPLE ASSIGNMENT STATEMENT:
Syntax: Variable=expression (eg: a=a+10)
(a) The expression can be a constant or a variable or any expression.
(b) The single symbol = is an assignment operator.
(c) The expression on right side of assignment operator is evaluated and the result is converted into
type of variable on the left side of assignment operator.
(d) The converted data is copied into memory location which is identified by the variable on the LHS
of the assignment operator.
2. SHORTHAND ASSIGNMENT OPERATOR ( COMPOUND ASSIGNMENT ):
Operators such as +=, -=, *=, /= and %=
The expression a+=10 means a=a+10. Similarly others.
3. MULTIPLE ASSIGNMENT STATEMENT:
i=10 ; j=10; k=10
can be written as i=j=k=10;
INCREMENT AND DECREMENT OPERATORS
1. INCREMENT OPERATOR:
Types:
1. Post increment. Eg: a++
2. Pre increment. Eg: ++a
Both increments value of variable a by 1.
1. POST INCREMENT
eg:
#include <stdio.h>
Int main()

Prepared By: Sushma Shetty
69 www.vtulife.com


{
int a=5, b;
b=a++;
return 0;
}

The expression b=a++ is evaluated as
b=a
a++ => a=a+1
i.e value of b is 5. And a is 6.
2. PRE INCREMENT
Eg:
#include <stdio.h>
int main()
{
int a=5, b;
b=++a;
return 0;
}
The expression b=++a is evaluated as
++a => a=a+1
b=a
i.e value of b is 6 and a is also 6.
2. DECREMENT OPERATOR:
Types:
3. Post decrement. Eg: a++
4. Pre decrement. Eg: ++a
Both decrements value of variable a by 1.
2. POST DECREMENT
eg:
#include <stdio.h>
Int main()
{
int a=5, b;
b=a--;
return 0;

Prepared By: Sushma Shetty
70 www.vtulife.com


}

The expression b=a-- is evaluated as
b=a
a-- => a=a-1
i.e value of b is 5. And a is 4.
2. PRE DECREMENT
Eg:
#include <stdio.h>
int main()
{
int a=5, b;
b=--a;
return 0;
}
The expression b=--a is evaluated as
--a => a=a-1
b=a
i.e value of b is 4 and a is also 4.
CONDITIONAL OPERATOR
It is also called ternary operator.
Eg: (expression 1) ? (expression 2): (expression 3)
Expression 1 will be evaluated to either true or false.
If expression 1 is true, expression 2 is executed.
If expression 1 is false, expression 3 is executed.
#include <stdio.h>
int main()
{
int a=7, b=8, big;
big=(a>b)?a:b;
printf(%d, big);
return 0;
}
output: 8

Prepared By: Sushma Shetty
71 www.vtulife.com


BITWISE OPERATOR
The operators that are used to manipulate the bits of given data are called bitwise operators.
Types:
1. Bit-wise negative (~)
2. Left shift (<<)
3. Right shift (>>)
4. Bit-wise AND (&)
5. Bit-wise OR (|)
6. Bit-wise XOR (^)
BIT-WISE NEGATIVE/ ONES COMPLIMENT:
The operator that is used to change every bit from 0 to 1 and from 1 to 0 in the specified operand is
called ones compliment operator.
Eg:
#include <stdio.h>
int main()
{
int a=10;
int b=~a;
return 0;
}
Here, a=10 i.e in binary representation 8 bits: 00001010
Its compliment is 11110101 i.e 245 in decimal which is assigned to b.
LEFT SHIFT OPERATOR:
The operator that is used to shift the data by a specified number of bit positions towards left is called
left shift operator.
Syntax: b=a<<num;
Eg: b=5<<1;
5 in binary is 00000101 which when shifted one bit left
00001010 <= a zero is appended.
Value is 10. Assigned to variable b.
RIGHT SHIFT OPERATOR:
The operator that is used to shift the data by a specified number of bit positions towards left is called
left shift operator.

Prepared By: Sushma Shetty
72 www.vtulife.com


Syntax: b=a>>num;
Eg: b=5>>1;
5 in binary is 00000101 which when shifted one bit left
0000010 <= a zero is appended.
Value is 2. Assigned to variable b.
BIT-WISE AND:
If the corresponding bit positions in both the operands are 1, then AND operation results in 1. Otherwise
AND operation results in 0.
0 & 0=0, 0&1=0, 1&0=0, 1&1=1.
Eg: a=10, b=6;
c=a & b;
then, a: 0 0 0 0 1 0 1 0
b: 0 0 0 0 0 1 1 0
c: 0 0 0 0 0 0 1 0 i.e 2 in decimal.
BIT-WISE OR:
If the corresponding bit positions in both the operands are 0, then OR operation results in 0. Otherwise
OR operation results in 1.
0 & 0=0, 0&1=1, 1&0=1, 1&1=1.
Eg: a=10, b=6;
c=a & b;
then, a: 0 0 0 0 1 0 1 0
b: 0 0 0 0 0 1 1 0
c: 0 0 0 0 1 1 1 0 i.e 14 in decimal.
BIT-WISE XOR:
If the corresponding bit positions in both the operands are 0 or 1, then XOR operation results in 0.
Otherwise XOR operation results in 1.
0 & 0=0, 0&1=1, 1&0=1, 1&1=0.
Eg: a=10, b=6;
c=a & b;

Prepared By: Sushma Shetty
73 www.vtulife.com


then, a: 0 0 0 0 1 0 1 0
b: 0 0 0 0 0 1 1 0
c: 0 0 0 0 1 1 0 0 i.e 12 in decimal.
THE PRECEDENCE OF OPERATORS (HIERARCHY OF OPERATORS)


Prepared By: Sushma Shetty
74 www.vtulife.com


SPECIAL OPERATORS
COMMA OPERATOR:
It has the least precedence among all the operators and is left associative. It is normally used to:
1. Separate items in the list. Eg: a=12,13,14; // 13 and 14 are discarded.
2. Combine two or more statements into a single statement. Eg: a=10, b=20, c=30;
Eg:
printf(%d%d,a,b);
sizeof():
this operator is used to determine the number of bytes occupied by a variable or a constant in the
memory.
Eg: sizeof(char) gives 1 byte.
sizeof(int) gives 4 bytes in a 32 bit machine.
C EXPRESSION FORMATS
Types of C expressions:
1. Primary
2. Unary
3. Binary
4. Ternary
5. Assignment
6. Comma
PRIMARY EXPRESSIONS:
An expression with only one operand but without any operator.
1. Names: variable or a function. Eg: const int MAX=10; int a,b;
2. Constants: a piece of data that cannot be changed during the execution of the program.
3. Parenthesized expressions: any expression or a value enclosed in parentheses must be reducible
to a single value.
UNARY EXPRESSIONS:
An expression with only one operand and one operator is called unary expression.
1. Unary minus expression. Eg: -5
2. Unary plus expression. Eg: +5
3. Prefix expression. Eg: ++i
4. Postfix expression. Eg: i++

Prepared By: Sushma Shetty
75 www.vtulife.com


BINARY EXPRESSIONS:
An expression containing two operands and an operator.
1. Multiplicative expressions. Eg: 2*4, a/b
2. Additive expressions. Eg: a-b, a+b
3. Relational expressions. Eg: a>b, a<b
4. Logical expressions. Eg: a &&b
5. Bitwise expressions. Eg: a&b, a|b
TERNARY EXPRESSIONS:
An expression containing three operands and two operators.
Eg: a?b:c
ASSIGNMENT EXPRESSIONS:
A statement with assignment operator.
E: a=10, a=b*c
COMMA EXPRESSIONS:
A set of statements separated by comma are evaluated from left to right one after the other.
Eg: a=10, b=30;



STATEMENTS, ALGORITHMS AND
FLOWCHARTS
STATEMENTS
In a programming language, it is used to inform the computer to perform an action when a program is
executed. A statement can alter the value of a variable, it can accept the input, it can manipulate the
data and display the data.
1. Expression statement
2. Compound statement
3. Control statement

Prepared By: Sushma Shetty
76 www.vtulife.com


EXPRESSION STATEMENT:
An expression followed by a semicolon. An expression statement include:
1. Statements with assignment operator. Eg: a=b*c; a=50;
2. Statements consisting of only expressions. Eg: i++;
3. Statements that invoke the functions. Eg: printf(hello); sum(n);
COMPOUND STATEMENT:
The sequence of statements enclosed within a pair of braces { and } is called a compound statement.
Eg:
{
sum=a+b;
printf(sum = %d ,sum);
}
CONTROL STATEMENT:
The order in which the statements are executed is called control flow. Three types:
1. Sequential control statements
2. Branching statements
3. Loop statements
ALGORITHMS AND FLOWCHARTS
ALGORITHM:
An algorithm is defined as unambiguous, step by step procedure to solve a given problem in finite
number of steps by accepting a set of inputs and producing desired result for the given problem. After
producing the result, algorithm should terminate.
FLOW CONTROL:
A algorithm or a program contains various actions to be executed in the form of statements. Specifying
the order in which various actions have to be executed is called flow control.
CHARACTERISTICS/PROPERTIES OF ALGORITHMS:
1. Each and every instruction should be precise and unambiguous i.e. each and every instruction
should be clear and should have only one meaning.
2. Each instruction should be performed in finite time.
3. One or more instructions should not be repeated infinitely. It means that the algorithm must
terminate ultimately.
4. After the instructions are executed, the user should get the required results.

Prepared By: Sushma Shetty
77 www.vtulife.com


ADVANTAGES AND DISADVANTAGES OF ALGORITHMS:
ADVANTAGES:
1. it is a step-by-step procedure of a solution to a given problem ,which is very easy to understand.
2. it has got a definite procedure.
3. it easy to first develop an algorithm and then convert it into a flowchart and then into a
computer program.
4. it is independent of programming language.
5. it is easy to debug as every step is got its own logical sequence.
DISADVANTAGES:
It is time consuming & cubersome as an algorithm is developed first which is converted into flowchart
and then into a computer program.
FLOWCHART:
A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting them with arrows. This diagrammatic representation
illustrates a solution to a given problem. Process operations are represented in these boxes, and arrows;
rather, they are implied by the sequencing of operations. Flowcharts are used in analyzing, designing,
documenting or managing a process or program in various fields.

Eg:

Prepared By: Sushma Shetty
78 www.vtulife.com


Factorial of a number.

ADVANTAGES AND DISADVANTAGES OF FLOWCHARTS:
ADVANTAGES:
1. Communication: Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: With the help of flowchart, problem can be analysed in more effective way.
3. Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes.
4. Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
5. Proper Debugging: The flowchart helps in debugging process.
6. Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part
DISADVANTAGES:
1. Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
2. Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely.
3. Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem. The essentials of what is done can easily be lost in the technical details of how it is
done.

Prepared By: Sushma Shetty
79 www.vtulife.com


FLOWCHART ALGORITHM
It is a graphical or pictorical representation along
with instructions
They are expressed in English language along with
maythematical expressions
For complex problems, flowcharts become
complex
They can be used for complex or simple problems
Modification is difficult Can be modified easily
We can easily understand the logic Understanding may be slightly difficult

CONTROL STATEMENT
The order in which the statements are executed is called control flow. The statements that are used to
control the flow of execution of the program are called control statements. Besed on the order in which
the statements are executed, the various control statements are classified into:
1. Sequential control statements
2. Branching statements: if else
3. Loop statements: for, while
SEQUENTIAL STATEMENTS:
The programming statements that are executed sequentially (one after the other) are called sequential
statements.
Eg:
void main()
{
int a,b,sum;
printf(enter 2 numbers: );
scanf(%d%d,&a,&b);
sum=a+b;
printf(\nsum= %d,sum);
}
ADVANTAGES:
1. No separate control statements are required to execute the sequential statements one after the
other.
2. They are executed in the order they appear in the program.
DISADVANTAGES:
1. The sequence of execution of the program cannot be changed.

Prepared By: Sushma Shetty
80 www.vtulife.com


TYPES OF ERRORS
1. Syntax errors
2. Logical errors
3. Runtime errors
SYNTAX ERRORS:
Each language has a set of rules that are to be followed while writing a program. During compilation, the
programming statements that violate these grammatical rules are identified by the compiler and issue
error messages so that programmer can locate and correct them.
Eg:
#include <stdio.h>
void main()
{
int a;
a=10 //error: missing ;
print(a value= %d,a); //error: print is undefined. It must be printf
}
LOGICAL ERRORS:
It is also called as semantic errors. When a program is compiled and executed successfully and if the
desired output not obtained, then logical errors are present.
Eg:
#include <stdio.h>
void main()
{
int a,b,sum;
printf(enter 2 numbers: );
scanf(%d%d,&a,&b);
sum=a-b; //we find the difference and not the sum! No error but answer is not expected.
printf(\nsum= %d,sum);
}
RUNTIME ERRORS:
It occurs when a program attempts to perform a task that is not allowed. The statements which results
in run time errors are syntactically and logically correct.
Eg: attempting to divide by a zero.
#include <stdio.h>
void main()
{

Prepared By: Sushma Shetty
81 www.vtulife.com


float a=5, b=0, quo;
quo=a/b;
}
DIFFERENCE BETWEEN SYNTAX AND LOGICAL ERRORS:
SYNTAX ERRORS LOGICAL ERRORS
When programmer is not following the syntax
rules
These errors are accidentally occurred due to
unintended mistakes
Easy to locate and correct Difficult to locate and correct
Compiler find them out Debuggers are used to locate them
It cannot be executed Can be executed
Programming knowledge of that language is
required
Knowledge of programming logic is required


















Prepared By: Sushma Shetty
82 www.vtulife.com


UNIT 5

FUNCTIONS
FUNCTIONS:
All C programs consist of one or more functions. Functions are the building blocks of a program. All
functions are at the same level there is no nesting. One (and only one) function must be called main.
A large program can be divided into manageable pieces called modules where each module does a
particular task. Thus, functions often called modules are self contained small programs that carry out
some specific, well-defined tasks.
Two types:
1. Library functions/ predefined functions. Eg: printf(), scanf(), sqrt()
2. User defined functions (UDFs)
RETURN VALUE
All functions can return a value, including main.
Functions can return arithmetic values ( int, float etc.), structures, unions, pointers or void. If the return
type is specified as being void, then no value is returned by the function. Functions cannot return a
function or an array.
For functions that will return a value, the return statement is used in conjunction with an expression of
an appropriate type. This causes immediate termination of the function, with the value of the
expression being returned to the caller. return can also be used with functions of type void, but no
return value can be specified.
FUNCTION PARAMETERS
All functions (including main) can accept parameters. Eg:


Prepared By: Sushma Shetty
83 www.vtulife.com


Here, In both cases the parameter list must be specified, and their types must be declared. The
parameters to the function (the expressions given in the function call) are passed by value only.
LIBRARY FUNCTIONS AND USER DEFINED FUNCTIONS:
LIBRARY/PRE-DEFINED FUNCTIONS:
C library that comes with C compiler has a collection of various functions which perform standard
standard and pre-defined tasks. These functions written by manufacturers of C compilers are called
library functions or built-in functions.
LIBRARY NAME EXAMPLE FUNCTIONS HEADER FILE
Math library sqrt(d), pow(d1, d2) etc math.h
Standard library exit(), atoi() etc stdlib.h
Character library Isalpha(a), tolower(a) etc ctype.h
Standard I/O library Printf(), scanf() etc stdio.h
String library Strcpy(), strcmp() etc String.h
time Clock(), time() etc Time.h
MATH LIBRARY:
It allows the programmer to performcertain mathematical operations by using them. Before using these
functions in the program, they have to be declared. They are declared in a file math.h. the arguments
to library functions are denoted by:
i meaning integer type, d the double type, c as character type, u as unsigned integer type.
Function name Return value
exp(d) e
d
pow(d1, d2) d1
d2
sqrt(d) Square root of d
log(d) Natural log of d
log10(d) Logarithm value of base 10
tan(d) Tangent value of d
sin(d) Sine value of d
cos(d) Cosine value of d
STANDARD LIBRARY FUNCTIONS:
1. Math functions. Eg: abs(), srand(), pow()
2. Memory functions. Eg: malloc(), calloc(), free()
3. Program control. Eg: exit()
4. System communication. Eg: system()
5. Conversion functions. Eg: atoi(), itoa()
CHARACTER LIBRARY:
It allows the programmer to perform operations on characters. They are declared in ctype.h.

Prepared By: Sushma Shetty
84 www.vtulife.com


isalnum(a); -returns true if a is an alphabet or a numeric. Else, false.
isalpha(a); -returns true if a is an alphabet. Else, false.
isdigit(a); -returns true if a is a numeric. Else, false.
islower(a); -returns true if a is lower case letter. Else, false.
isupper(a); -returns true if a is upper case letter. Else, false.
tolower(a); -converts upper case letter to lower case. Else, false.
toupper(a); - converts lower case letter to upper case. Else, false.
Example:
#include <stdio.h>
#include <ctype.h>
void main()
{
char a=c;
toupper(a);
printf(converted to upper case : , a);
}
Output: converted to upper case :C
USER-DEFINED FUNCTIONS:
The functions whichare written by a programmer to do some specific task is called user-defined
function.
VARIABLE FUNCTION PARAMETERS:
All function parameters are passed by value. To make a function alter a variable, the address of the
variable must be passed, i.e. pass the variable by reference.


Prepared By: Sushma Shetty
85 www.vtulife.com


FUNCTION DEFINITION AND DECLARATION:
A function definition is where the function name, parameters, code and return type are specified. A
function declaration is where the name and return type of a function are given. The definition of a
function includes a declaration of that same function implicitly.
A function can be declared many times (as long as the declarations declare the function to be of the
same type) but can only be defined once. Declarations of functions are sometimes necessary to appease
the compiler, which always assumes, if the information is not available, that all functions return int.


The use of prototypes or the new style function definition allows the compiler to check that the
parameters to a function are sensible (not necessarily the same), as well as checking the return type of
the function; but only if the definition or prototype appears before the function call.
ELEMENTS OF USER-DEFINED FUNCTIONS:
1. Function definition
2. Function call
3. Function declaration
FUNCTION DEFINITION:
The program module that is written to achieve a specific task is called function definition.


Prepared By: Sushma Shetty
86 www.vtulife.com


FUNCTION CALL:
Execution always start from function main(). If we want to execute the function minimum() in the above
example, it must be invoked.

FUNCTION DECLARATION/ FUNCTION PROTOTYPE:
The use of prototypes or the new style function definition allows the compiler to check that the
parameters to a function are sensible (not necessarily the same), as well as checking the return type of
the function; but only if the definition or prototype appears before the function call.

FORMAL PARAMETERS AND ACTUAL PARAMETERS
The variables defined in the function header of function definition are called formal parameters.

The variables that are used when a function is invoked are called actual parameters. Using the actual
parameters, the data can be transferred to the function.
minimum(1.23, 4.56);
ACTUAL PARAMETERS FORMAL PARAMETERS
Used in calling function when a function is
invoked. Ex: c=add(a,b);
Used in the function header of a called function.
Eg: int add(int m, int n) { }
It can be constants, variables or expressions. Eg:
c=add(a+5, b);
It should be only variables. Expressions and
constants are not allowed.
Sends values to the formal parameters.
Eg: c=add( 2,3);
Receive values from the actual parameters.
Addresses of actual parameters can be sent to
formal parameters.
If formal parameters contains addresses, they
should be declared as pointers.
CAREGORIES OF FUNCTIONS
1. Functions with no parameters and no return values
2. Functions with no parameters and return values
3. Functions with parameters and no return values

Prepared By: Sushma Shetty
87 www.vtulife.com


4. Functions with parameters and return values
PASSING PARAMETERS TO FUNCTIONS
1. Pass by value (call by value)
2. Pass by reference (call by reference)
3. Pass by address
PASS BY VALUE (CALL BY VALUE):
The values of actual parameters are copied into formal parameters i.e formal parameters contain only
the copy of actual parameters. So, even if the values of formal parameters changes in the called
function, the values of the actual parameters are not changed.
ADVANTAGE:
1. Makes the function more self contained
2. Protect them against accidental changes
DISADVANTAGE:
1. It does not allow information to be transferred back to calling function via arguments.
Eg:
#include <stdio.h>
void exchange(int m, int n)
{
int temp;
temp=m;
m=n;
n=temp;
}
void main()
{
int a=5, b=1;
exchange(a,b);
printf(after the function usage: a= %d, b=%d,a,b);
}
output:
after the function usage: a=5, b=1

Prepared By: Sushma Shetty
88 www.vtulife.com


PASS BY REFERENCE (CALL BY REFERENCE):
The formal parameters are treated as aliases (alternamte names) for actual parameters. So, any change
in formal parameter imply there is a change in actual parameter. Here, if we change the formal
parameters, the actual parameters also change.
Eg:
#include <stdio.h>
void exchange(int &m, int &n)
{
int temp;
temp=m;
m=n;
n=temp;
}
void main()
{
int a=5, b=1;
exchange(a,b);
printf(after the function usage: a= %d, b=%d,a,b);
}
output:
after the function usage: a=1, b=5
PASS BY ADDRESS:
When a function is called, the address of actual parameters are sent. In the called function, the formal
parameters should be declared as pointers with the same type as the actual parameters. The addresses
of actual parameters are copied into formal parameters. Using these addresses, the values of the actual
parameters are changed.
Eg:
#include <stdio.h>
void exchange(int *m, int *n)
{
int temp;
temp=*m;
*m=*n;
*n=temp;
}

Prepared By: Sushma Shetty
89 www.vtulife.com


void main()
{
int a=5, b=1;
exchange(&a,&b);
printf(after the function usage: a= %d, b=%d,a,b);
}
output:
after the function usage: a=5, b=1
BLOCKS AND SCOPE
C is a block structured language. Blocks are delimited by { and }. Every block can have its own local
variables. Blocks can be defined wherever a C statement could be used. No semi-colon is required after
the closing brace of a block.

Reference to a variable will be to the variable of that name in the nearest enclosing block.
Scope of an object is defined as the region or a boundary of the program in which an object is visible.
Objects can be variables or function prototypes. Two types are:
1. Local scope
2. Global scope
LOCAL SCOPE:
The objects/ variables that are declared inside a block have local scope. They exist only from the point of
declaration until the end of the block.
GLOBAL SCOPE:
The objects/ variables that are defined outside a block have global scope. They are visible to till the end
of the program and to all the functions in that file.
Eg:
#include <stdio.h>
int c=10; //global variable

Prepared By: Sushma Shetty
90 www.vtulife.com


void exchange(int &m, int &n)
{
int temp;
temp=m;
m=n;
n=temp;
}
void main()
{
int a=5, b=1; //local variables
exchange(a,b);
printf(after the function usage: a= %d, b=%d,a,b);
printf(\nc=%d, c);
}
output:
the function usage: a= 1, b=5
c=10
STORAGE CLASSES
STORAGE CLASS DEFINITION
Global variables
These objects/ variables are defined outside a block. They are visible to till
the end of the program and to all the functions in that file.
Local variables
These objects/ variables are declared inside a block. They exist only from the
point of declaration until the end of the block.
Auto variables
The default class. Automatic variables are local to their block. Their storage
space is reclaimed on exit from the block.
Register variables
If possible, the variable will be stored in a processor register. May give faster
access to the variable. If register storage is not possible, then the variable
will be of automatic class. Use of the register class is not recommended, as
the compiler should be able to make better judgement about which variables
to hold in registers, in fact injudicious use of register variables may slow
down the program.
Static variables
On exit from block, static variables are not reclaimed. They keep their value.
On re-entry to the block the variable will have its old value.
Extern variables
Allows access to external variables. An external variable is either a global
variable or a variable defined in another source file. External variables are
defined outside of any function. (Note: Variables passed to a function and
modified by way of a pointer are not external variables)


Prepared By: Sushma Shetty
91 www.vtulife.com


DECLARATION VERSUS DEFINITION
Definition is the place where variable is created (allocated storage). Declaration is a place where nature
(type) of variable is stated, but no storage is allocated.
Variables can be declared many times, but defined only once.

Declaring a variable without defining it is more useful when a variable needs to be accessed in more
than one source file when a program is split between multiple source files. For example:

In fact, as variables can be declared more than once in the same source file, and to ensure that the
variable is declared identically in each source file, it is common to place declarations of global variables
in a header file which is then included in each source file.




Prepared By: Sushma Shetty
92 www.vtulife.com


UNIT 7

ARRAYS
ARRAY
It is a powerful data structure in C language. It is used to store, process and print large amount of data. It
is a collection of similar type of items stored sequentially one after the other in memory.
The following declaration states that x is an array of three integer values.
int x[3];
Each individual part (or element) of x is accessed by adding an index value in square brackets after the
array name, e.g.
x[0] = 74;
printf("%d\n", x[0]);
Note that the index values range from 0 to one less than the number of elements. Arrays can have any
number of dimensions; to declare a 2-D array of double :
Double matrix[10][10];
CLASSIFICATION OF ARRAYS
1. Single dimensional array
2. Multi dimensional array
SINGLE DIMENSIONAL ARRAY:
The name of an array is a constant, it is not possible to change its value, otherwise it would be possible
to lose access to the contents of the array. Also, an array name is not an lvalue, it cannot appear on the
left hand side of an assignment operator. The following array declaration gives the following structure in
memory:
int x[3]= {23, 41, 17};
In memory:

Prepared By: Sushma Shetty
93 www.vtulife.com



The operation of accessing what a pointer is pointing at via the * operator is called dereferencing the
pointer or pointer indirection.

Array index always starts from 0.
STORING VALUES IN ARRAYS
1. Initialization
2. Assigning values
3. Input values from keyboard
INITIALIZATION OF SINGLE DIMENSIONAL ARRAYS:
Assigning or providing the required values to a variable before processing it is called initialization.
Syntax: type array_name[size]={value1, value2, value3,., value n};
int ndigit[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char greeting1[] = "hello";
char greeting2[] = { 'h', 'e', 'l', 'l', 'o', '\0' };

Prepared By: Sushma Shetty
94 www.vtulife.com


Various ways of initializing an array:
1. Initializing all specified memory locations
2. Partial array initialization
3. Initialization without size
4. String initialization
The last two declarations show the two alternative ways of initialising an array of characters. They are
exactly equivalent, but one is somewhat easier to type! If the number of elements of the array is not
specified, then the compiler will determine this from the initialiser. The declarations of greeting1 and
greeting2 above both declare an array of 6 characters.
The values given in a brace delimited initialiser (first and last examples above) must be constant
expressions (one whose value can be determined at the time of compilation). If the initialiser is a single
expression, the restriction does not apply.
If the number of expressions in the initialiser is less than the number of elements in the array then the
remaining elements will be initialised as though they were static objects; that is arrays of numeric values
will be initialised with zeros whatever the storage class of the array (external, static or automatic).
When initialising multi-dimensional arrays, extra braces can be used to show the reader how the values
are to be used:
int x[3][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
INITIALIZING ALL SPECIFIED MEMORY LOCATION:
int x[3]={23, 41, 17};

int x[3]={1,2,3,4,5}; //error
PARTIAL ARRAY INITIALIZATION:
int a[5]={10, 15};


Prepared By: Sushma Shetty
95 www.vtulife.com


Rest of the values will be initialized to 0.
INITIALIZATION WITHOUT SIZE:
int x[]={23, 41, 17};

Here size is not specified.
ARRAY INITIALIZATION AS A STRING:
char s[]=COMPUTER;

\0 that is NULL is attached to the end, to mark the end of the string.
In case of:
char s[]={C,O,M,P,U,T,E,R};

ASSIGNING VALUES TO ARRAY:
int a[5];
a[2]=10;
a[4]=7;
assigning values in this format is also possible. But other locations will be having garbage values.
int b[5];
b=a; //error
but, b[2]=a[4]; is possible.

Prepared By: Sushma Shetty
96 www.vtulife.com


Also
for (i=0; i<5;i++)
b[i]=a[i]; is valid.
EXAMPLE:
#include <stdio.h>
void main()
{
int a[5], i;
printf(enter 5 numbers:);
for(i=0;i<5;i++)
scanf(%d,&a[i]);
printf(\nthe values in array a are:\n);
for(i=0;i<5;i++)
printf(%d ,a[i]);
}
ARRAYS AND FUNCTIONS
Arrays can be passed to functions in two methods:
1. Passing individual elements of the array
2. Passing the whole array
PASSING INDIVIDUAL ELEMENTS OF THE ARRAY:
1. The type of array element passed to the function and the type of parameter in the
corresponding function definition should be same.
2. The array element is passed as a value parameter so that any change to the formal parameter
(inside the function) wont affect the actual parameter.
Eg:

PASSING THE WHOLE ARRAY:
PASSING ENTIRE ONE-DIMENSIONAL ARRAY TO A FUNCTION:

Prepared By: Sushma Shetty
97 www.vtulife.com


While passing arrays to the argument, the name of the array is passed as an argument(,i.e, starting
address of memory area is passed as argument). Write a C program to pass an array containing age of
person to a function. This function should find average age and display the average age in main function.

Output:
Average age=27.08
PASSING MULTI-DIMENSIONAL ARRAYS TO FUNCTION:
To pass two-dimensional array to a function as an argument, starting address of memory area reserved
is passed as in one dimensional array Example to pass two-dimensional arrays to function.


Prepared By: Sushma Shetty
98 www.vtulife.com



SEARCHING
Searching for a element in a array.
1. Linear search
2. Binary search
BINARY SEARCH:
C program for binary search: This code implements binary search in c language. It can only be used for
sorted arrays, but it's fast as compared to linear search. If you wish to use binary search on an array
which is not sorted then you must sort it using some sorting technique say merge sort and then use
binary search algorithm to find the desired element in the list. If the element to be searched is found
then its position is printed.
Binary search is faster than linear search but list should be sorted, hashing is faster than binary search
and perform searches in constant time.
Code:

Prepared By: Sushma Shetty
99 www.vtulife.com




Output:

Prepared By: Sushma Shetty
100 www.vtulife.com



LINEAR SEARCH:


Output:

Prepared By: Sushma Shetty
101 www.vtulife.com



COMPARING THE TWO:
Binary search requires the input data to be sorted; linear search doesn't.
Binary search requires an ordering comparison; linear search only requires equality
comparisons.
Binary search has complexity O(log n); linear search has complexity O(n).
Binary search requires random access to the data; linear search only requires sequential access.
BUBBLE SORT
C program for bubble sort: c programming code for bubble sort to sort numbers or arrange them in
ascending order. You can easily modify it to print numbers in descending order.
You can also sort strings using Bubble sort, it is less efficient as its average and worst case complexity is
high, there are many other fast sorting algorithms.
A bubble sort is a sort where adjacent items in the array or list are scanned repeatedly, swapping as
necessary, until one full scan performs no swaps. Advantage is simplicity.
Disadvantage is that it can take N scans, where N is the size of the array or list, because an out of
position item is only moved one position per scan.

Prepared By: Sushma Shetty
102 www.vtulife.com




Output:

Prepared By: Sushma Shetty
103 www.vtulife.com



EVALUATE POLYNOMIAL
A polynomial can be evaluated using following two methods:
1. By adding all the terms in polynomial
2. Horners method
BY ADDING ALL TERMS OF POLYNOMIAL:
Polynomial given by: a0x
0
+a1x
1
+a2x
2
+.+anx
n
.
1. Identify parameters to function.
Eg program: Parameters are: double a[], int n, double x
2. Return type: eg: return double.
3. Designing body of the function: for aix
i
for i=0,1,2,3.,n.
C equivalent code:
sum=0;
for(i=0; i<=n; i++)
sum=sum+a[i]*pow(x,i);
HORNER'S METHOD:
(or synthetic division) is a technique for evaluating polynomials. It can be thought of as nested
multiplication. For example, the fifth-degree polynomial



can be written in the "nested multiplication" form

.

Prepared By: Sushma Shetty
104 www.vtulife.com



MULTI-DIMENSIONAL ARRAYS:
TWO DIMENSIONAL ARRAYS
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array
is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y you
would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional
array can be think as a table which will have x number of rows and y number of columns. A 2-
dimensional array a, which contains three rows and four columns can be shown as below:

Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the
name of the array, and i and j are the subscripts that uniquely identify each element in a.

Prepared By: Sushma Shetty
105 www.vtulife.com


INITIALIZATION OF TWO-DIMENSIONAL ARRAYS:
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
ACCESSING TWO DIMENSIONAL ARRAY ELEMENTS:
An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index
of the array. For example:
int val = a[2][3];
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram. Let us check below program where we have used nested loop to handle a two dimensional
array:

Output:

Prepared By: Sushma Shetty
106 www.vtulife.com



SOME C PROGRAMS
1. HELLO WORLD

2. PROGRAM TO TAKE INPUT FROM USER


Prepared By: Sushma Shetty
107 www.vtulife.com


3. USING IF ELSE CONTROL INSTRUCTIONS

4. LOOP EXAMPLE


Prepared By: Sushma Shetty
108 www.vtulife.com


5. PRIME NUMBER

6. COMMAND LINE ARGUMENTS


Prepared By: Sushma Shetty
109 www.vtulife.com


7. ARRAY PROGRAM

8. FUNCTION PROGRAM


Prepared By: Sushma Shetty
110 www.vtulife.com


9. USING COMMENTS IN A PROGRAM

10. USING STRUCTURES


Prepared By: Sushma Shetty
111 www.vtulife.com


11. FIBONACCI SERIES

12. CALCULATE AVERAGE USING ARRAYS:


Prepared By: Sushma Shetty
112 www.vtulife.com


13. ODD OR EVEN

14. FACTORIAL PROGRAM


Prepared By: Sushma Shetty
113 www.vtulife.com


15. FIND HCF AND LCM

16. SWAP TWO NUMBERS


Prepared By: Sushma Shetty
114 www.vtulife.com


17. REVERSE A NUMBER

18. PALINDROME

19. FLOYDS TRIANGLE


Prepared By: Sushma Shetty
115 www.vtulife.com


1
2 3
4 5 6
7 8 9 10


Prepared By: Sushma Shetty
116 www.vtulife.com


20. FIND MAXIMUM ELEMENT IN ARRAY


Prepared By: Sushma Shetty
117 www.vtulife.com


21. REVERSE AN ARRAY


Prepared By: Sushma Shetty
118 www.vtulife.com


22. INSERT AN ELEMENT IN AN ARRAY


Prepared By: Sushma Shetty
119 www.vtulife.com


23. DELETE AN ELEMENT FROM ARRAY


Prepared By: Sushma Shetty
120 www.vtulife.com


24. MERGE ARRAYS


Prepared By: Sushma Shetty
121 www.vtulife.com




Prepared By: Sushma Shetty
122 www.vtulife.com


25. INSERTION SORT


Prepared By: Sushma Shetty
123 www.vtulife.com


26. SELECTION SORT


Prepared By: Sushma Shetty
124 www.vtulife.com


27. ADD TWO MATRIX


Prepared By: Sushma Shetty
125 www.vtulife.com


28. TRANSPOSE OF A MATRIX


Prepared By: Sushma Shetty
126 www.vtulife.com


29. MATRIX MULTIPLICATION



Prepared By: Sushma Shetty
127 www.vtulife.com


30. COMPARE TWO STRINGS

31. PALINDROME


Prepared By: Sushma Shetty
128 www.vtulife.com


32. ACCESS ARRAY ELEMENTS USING POINTER





















Prepared By: Sushma Shetty
129 www.vtulife.com

Potrebbero piacerti anche