0% found this document useful (0 votes)
4 views65 pages

Types of Computers Explained

The document provides an introduction to computers, detailing their definition, features, and historical evolution through five generations, from vacuum tubes to artificial intelligence. It also categorizes different types of computers, including supercomputers, mainframes, minicomputers, and microcomputers, along with their uses and examples. Additionally, it describes various input and output devices, highlighting their functions and significance in computer operations.

Uploaded by

manishkreddy123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views65 pages

Types of Computers Explained

The document provides an introduction to computers, detailing their definition, features, and historical evolution through five generations, from vacuum tubes to artificial intelligence. It also categorizes different types of computers, including supercomputers, mainframes, minicomputers, and microcomputers, along with their uses and examples. Additionally, it describes various input and output devices, highlighting their functions and significance in computer operations.

Uploaded by

manishkreddy123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Module – 1
Introduction to C

1.1 Introduction to Computers


Definition: Computer is an electronic device which accepts the input data from the input devices, process the
data, stores the processed data and generates the output in the output devices.

Modern computers can perform generic sets of operations known as programs. These programs enable
computers to perform a wide range of tasks. A computer system is a nominally complete computer that
includes the hardware, operating system (main software), asnd peripheral equipment needed and used for full
operation. This term may also refer to a group of computers that are linked and function together, such as
a computer network or computer cluster.

Features of Computer :
[Link]
[Link] and Reliability
[Link]
[Link]
[Link]

Early days of Computer


The Generations of Computers

1940 – 1956: First Generation – Vacuum Tubes: These early computers used vacuum tubes as circuitry
and magnetic drums for memory. As a result, they were enormous, literally taking up entire rooms and
costing a fortune to run. These were inefficient materials which generated a lot of heat, sucked huge
electricity and subsequently generated a lot of heat which caused ongoing breakdowns.

These first generation computers relied on ‘machine language’ (which is the most basic programming

Dept of CSE/ISE
language that can be understood by computers). These computers were limited to solving one problem
at a time. Input was based on punched cards and paper tape. Output came out on print-outs. The two
notable machines of this era were the UNIVAC and ENIAC machines.

1956 – 1963: Second Generation – Transistors: The replacement of vacuum tubes by transistors saw

RVITM
the advent of the second generation of computing. Although first invented in 1947, transistors weren’t
used significantly in computers until the end of the 1950s. They were a big improvement over the
vacuum tube, despite still subjecting computers to damaging levels of heat. However they were hugely
superior to the vacuum tubes, making computers smaller, faster, cheaper and less heavy on electricity

Department of ISE 1
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

use. They still relied on punched card for input/printouts.

The language evolved from cryptic binary language to symbolic (‘assembly’) languages. This meant
programmer could create instructions in words. About the same time high level programming languages
were being developed (early versions of COBOL and FORTRAN). Transistor-driven machines were the
first computers to store instructions into their memories – moving from magnetic drum to magnetic core
‘technology’.

1964 – 1971: Third Generation – Integrated Circuits: In this phase, transistors were now being
miniaturized and put on silicon chips (called semiconductors). This led to a massive increase in speed
and efficiency of these machines. These were the first computers where users interacted using
keyboards and monitors, which interfaced with an operating system, a significant leap up from the punch
cards and printouts.
This enabled these machines to run several applications at once using a central program which
functioned to monitor memory. As a result of these advances which again made machines cheaper and
smaller.

1972 – 2010: Fourth Generation – Microprocessors: This revolution can be summed in one word:
Intel. The chip-maker developed the Intel 4004 chip in 1971, which positioned all computer components
(CPU, memory, input/output controls) onto a single chip. What filled a room in the 1940s now fit in the
palm of the hand. The Intel chip housed thousands of integrated circuits. The year 1981 saw the first
ever computer (IBM) specifically designed for home use and 1984 saw the MacIntosh introduced by
Apple. Microprocessors even moved beyond the realm of computers and into an increasing number of

Dept of CSE/ISE
everyday products. The increased power of these small computers meant they could be linked, creating
networks, which ultimately led to the development, birth and rapid evolution of the Internet. Other major
advances during this period have been the Graphical user interface (GUI), the mouse and more recently
the astounding advances in lap-top capability and hand-held devices.

2010-Fifth Generation – Artificial Intelligence: Computer devices with artificial intelligence are still

RVITM
in development, but some of these technologies are beginning to emerge and be used such as voice
recognition. AI is a reality made possible by using parallel processing and superconductors. Leaning to
the future, computers will be radically transformed again by quantum computation, molecular and nano
technology.

Computer types, bits, bytes and words, CPU, Primary memory, Secondary

Department of ISE 2
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

memory

Types of Computers

Since the advent of the first computer different types and sizes of computers are offering different
services. Computers can be as big as occupying a large building and as small as a laptop or a
microcontroller in mobile & embedded systems.

The four basic types of computers are as under:

1. Supercomputer
2. Mainframe Computer
3. Minicomputer
4. Microcomputer

1. Supercomputer
The most powerful computers in terms of performance and data processing are the Supercomputers.
These are specialized and task specific computers used by large organizations. These computers are used
for research and exploration purposes, like NASA uses supercomputers for launching space shuttles,
controlling them and for space exploration purpose.

The supercomputers are very expensive and very large in size. It can be accommodated in large air-
conditioned rooms; some super computers can span an entire building.

Uses of Supercomputers

⮚ Space Exploration
Supercomputers are used to study the origin of the universe, the dark-matters. For these studies scientist
use IBM’s powerful supercomputer “Roadrunner” at National Laboratory Los Alamos.

Department of ISE 3
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

⮚ Earthquake studies
Supercomputers are used to study the Earthquakes phenomenon. Besides that supercomputers are used
for natural resources exploration, like natural gas, petroleum, coal, etc.

Department of ISE 4
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Weather Forecasting
Supercomputers are used for weather forecasting, and to study the nature and extent of Hurricanes,
Rainfalls, windstorms, etc.

⮚ Nuclear weapons testing


Supercomputers are used to run weapon simulation that can test the Range, accuracy & impact of
Nuclear weapons.

Popular Supercomputers
● IBM’s Sequoia, in United States
● Fujitsu’s K Computer in Japan
● IBM’s Mira in United States

D
2.


IBM’s SuperMUC in Germany
NUDT Tianhe-1A in China

Mainframe computer

RVITM
Although Mainframes are not as powerful as supercomputers, but certainly they are quite expensive
nonetheless, and many large firms & government organizations uses Mainframes to run their business
operations. The Mainframe computers can be accommodated in large air-conditioned rooms because of
its size. Super-computers are the fastest computers with large data storage capacity, Mainframes can
also process & store large amount of data. Banks educational institutions & insurance companies use
mainframe computers to store data about their customers, students & insurance policy holders.

Popular Mainframe computers


● Fujitsu’s ICL VME
● Hitachi’s Z800

3. Minicomputer

Minicomputers are used by small businesses & firms. Minicomputers are also called as “Midrange
Computers”. These are small machines and can be accommodated on a disk with not as processing and
data storage capabilities as super-computers & Mainframes. These computers are not designed for a

Department of ISE 5
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

single user. Individual departments of a large company or organizations use Mini-computers for specific
purposes. For example, a production department can use Mini-computers for monitoring certain
production process.

Popular Minicomputers

● K-202
● Texas Instrument TI-990
● SDS-92
● IBM Midrange computers

4. Microcomputer

Desktop computers, laptops, personal digital assistant (PDA), tablets & smart-phones are all types of

Dept of CSE/ISE
microcomputers. The micro-computers are widely used & the fastest growing computers. These
computers are the cheapest among the other three types of computers. The Micro-computers are
specially designed for general usage like entertainment, education and work purposes. Well known
manufacturers of Micro-computer are Dell, Apple, Samsung, Sony & Toshiba. Desktop computers,
Gaming consoles, Sound & Navigation system of a car, Netbooks, Notebooks, PDA’s, Tablet PC’s,

RVITM
Smart-phones, Calculators are all type of Microcomputers.

Bit, Byte and Word


● Bit: A bit (short for binary digit) is the smallest unit of data in a computer. A bit has a
single binary value, either 0 or 1.
● Byte: Eight bits makes one byte
● Nibble: Half a byte (four bits) is called a nibble.
● Word: Normally, four eight-bit bytes (4 bytes) form a 32-bit word.

Department of ISE 6
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1.2 Input and Output Devices


Input devices :
An input device is a piece of equipment used to provide data and control signals to an information processing
system, such as a computer or information appliance. Examples of input devices include keyboards, mouse,
scanners, cameras, joysticks, and microphones.
Following are some of the important input devices which are used in a computer −

• Keyboard
• Mouse
• Joy Stick
•Light pen
• Track Ball
• Scanner
• Graphic Tablet
• Microphone
• Magnetic Ink Card Reader(MICR)
• Optical Character Reader(OCR)
• Bar Code Reader
• Optical Mark Reader(OMR)
Keyboard
Keyboard is the most common and very popular input device which helps to input data to the computer. The layout
of the keyboard is like that of traditional typewriter, although there are some additional keys provided for
performing additional functions.

Department of ISE 7
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Keyboards are of two sizes 84 keys or 101/102 keys, but now keyboards with 104 keys or 108 keys are also available
for Windows and Internet.
The keys on the keyboard are as follows −

[Link] Keys & Description

Typing Keys
1 These keys include the letter keys (A-Z) and digit keys (09) which generally give the
same layout as that of typewriters.

Numeric Keypad

2 It is used to enter the numeric data or cursor movement. Generally, it consists of a


set of 17 keys that are laid out in the same configuration used by most adding
machines and calculators.

Function Keys

3 The twelve function keys are present on the keyboard which are arranged in a row
at the top of the keyboard. Each function key has a unique meaning and is used for
some specific purpose.

Control keys

4 These keys provide cursor and screen control. It includes four directional arrow keys.
Control keys also include Home, End, Insert, Delete, Page Up, Page Down,
Control(Ctrl), Alternate(Alt), Escape(Esc).

Special Purpose Keys


5 Keyboard also contains some special purpose keys such as Enter, Shift, Caps Lock,
Num Lock, Space bar, Tab, and Print Screen.

Mouse
Mouse is the most popular pointing device. It is a very famous cursor-control device having a small palm size box
with a round ball at its base, which senses the movement of the mouse and sends corresponding signals to the CPU
when the mouse buttons are pressed.

Department of ISE 8
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Generally, it has two buttons called the left and the right button and a wheel is present between the buttons. A
mouse can be used to control the position of the cursor on the screen, but it cannot be used to enter text into the
computer.

Advantages
• Easy to use
• Not very expensive
• Moves the cursor faster than the arrow keys of the keyboard.
Joystick
Joystick is also a pointing device, which is used to move the cursor position on a monitor screen. It is a stick having
a spherical ball at its both lower and upper ends. The lower spherical ball moves in a socket. The joystick can be
moved in all four directions.

The function of the joystick is similar to that of a mouse. It is mainly used in Computer Aided Designing (CAD)
and playing computer games.
Light Pen

Department of ISE 9
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Light pen is a pointing device similar to a pen. It is used to select a displayed menu item or draw pictures on the
monitor screen. It consists of a photocell and an optical system placed in a small tube.

When the tip of a light pen is moved over the monitor screen and the pen button is pressed, its photocell sensing
element detects the screen location and sends the corresponding signal to the CPU.

Track Ball

Track ball is an input device that is mostly used in notebook or laptop computer, instead of a mouse. This is a ball
which is half inserted and by moving fingers on the ball, the pointer can be moved.

Since the whole device is not moved, a track ball requires less space than a mouse. A track ball comes in various
shapes like a ball, a button, or a square.

Scanner

Scanner is an input device, which works more like a photocopy machine. It is used when some information is
available on paper and it is to be transferred to the hard disk of the computer for further manipulation.

Department of ISE 10
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Scanner captures images from the source which are then converted into a digital form that can be stored on the disk.
These images can be edited before they are printed.

Digitizer

Digitizer is an input device which converts analog information into digital form. Digitizer can convert a signal
from the television or camera into a series of numbers that could be stored in a computer. They can be used by the
computer to create a picture of whatever the camera had been pointed at.

Department of ISE 11
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Digitizer is also known as Tablet or Graphics Tablet as it converts graphics and pictorial data into binary inputs.
A graphic tablet as digitizer is used for fine works of drawing and image manipulation applications.

Microphone

Microphone is an input device to input sound that is then stored in a digital form.

The microphone is used for various applications such as adding sound to a multimedia presentation or for mixing
music.

Magnetic Ink Card Reader (MICR)

MICR input device is generally used in banks as there are large number of cheques to be processed every day.
The bank's code number and cheque number are printed on the cheques with a special type of ink that contains
particles of magnetic material that are machine readable.

Department of ISE 12
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

This reading process is called Magnetic Ink Character Recognition (MICR). The main advantages of MICR is that
it is fast and less error prone.

Optical Character Reader (OCR)

OCR is an input device used to read a printed text.

OCR scans the text optically, character by character, converts them into a machine readable code, and stores the
text on the system memory.

Bar Code Readers

Department of ISE 13
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Bar Code Reader is a device used for reading bar coded data (data in the form of light and dark lines). Bar coded
data is generally used in labelling goods, numbering the books, etc. It may be a handheld scanner or may be
embedded in a stationary scanner.

Optical Mark Reader (OMR)

OMR is a special type of optical scanner used to recognize the type of mark made by pen or pencil. It is used
where one out of a few alternatives is to be selected and marked.

It is specially used for checking the answer sheets of examinations having multiple choice questions.

Output devices

Monitors

Department of ISE 14
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Monitors, commonly called as Visual Display Unit (VDU), are the main output device of a computer. It forms
images from tiny dots, called pixels that are arranged in a rectangular form. The sharpness of the image depends
upon the number of pixels.

There are two kinds of viewing screen used for monitors.

• Cathode-Ray Tube (CRT)


• Flat-Panel Display

Cathode-Ray Tube (CRT) Monitor

The CRT display is made up of small picture elements called pixels. The smaller the pixels, the better the image
clarity or resolution. It takes more than one illuminated pixel to form a whole character, such as the letter ‘e’ in
the word help.

A finite number of characters can be displayed on a screen at once. The screen can be divided into a series of
character boxes - fixed location on the screen where a standard character can be placed. Most screens are capable
of displaying 80 characters of data horizontally and 25 lines vertically.

There are some disadvantages of CRT −

• Large in Size
• High power consumption

Flat-Panel Display Monitor

Department of ISE 15
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

The flat-panel display refers to a class of video devices that have reduced volume, weight and power requirement
in comparison to the CRT. You can hang them on walls or wear them on your wrists. Current uses of flat-panel
displays include calculators, video games, monitors, laptop computer, and graphics display.

The flat-panel display is divided into two categories −

• Emissive Displays − Emissive displays are devices that convert electrical energy into light. For example,
plasma panel and LED (Light-Emitting Diodes).
• Non-Emissive Displays − Non-emissive displays use optical effects to convert sunlight or light from
some other source into graphics patterns. For example, LCD (Liquid-Crystal Device).

Printers

Printer is an output device, which is used to print information on paper.

There are two types of printers −

• Impact Printers
• Non-Impact Printers

Impact Printers

Impact printers print the characters by striking them on the ribbon, which is then pressed on the paper.

Characteristics of Impact Printers are the following −

• Very low consumable costs

Department of ISE 16
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

• Very noisy
• Useful for bulk printing due to low cost
• There is physical contact with the paper to produce an image

These printers are of two types −

• Character printers
• Line printers

Character Printers

Character printers are the printers which print one character at a time.

These are further divided into two types:

• Dot Matrix Printer(DMP)


• Daisy Wheel

Dot Matrix Printer


• In the market, one of the most popular printers is Dot Matrix Printer. These printers are popular because of
their ease of printing and economical price. Each character printed is in the form of pattern of dots and head
consists of a Matrix of Pins of size (5*7, 7*9, 9*7 or 9*9) which come out to form a character which is why
it is called Dot Matrix Printer.

Advantages

Department of ISE 17
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

• Inexpensive
• Widely Used
• Other language characters can be printed

Disadvantages

• Slow Speed
• Poor Quality

Daisy Wheel

Head is lying on a wheel and pins corresponding to characters are like petals of Daisy (flower) which is why it
is called Daisy Wheel Printer. These printers are generally used for word-processing in offices that require a
few letters to be sent here and there with very nice quality.

Advantages

• More reliable than DMP


• Better quality
• Fonts of character can be easily changed

Disadvantages

• Slower than DMP


• Noisy
• More expensive than DMP

Line Printers

Department of ISE 18
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Line printers are the printers which print one line at a time.

These are of two types −

• Drum Printer
• Chain Printer

Drum Printer

This printer is like a drum in shape hence it is called drum printer. The surface of the drum is divided into a
number of tracks. Total tracks are equal to the size of the paper, i.e. for a paper width of 132 characters, drum
will have 132 tracks. A character set is embossed on the track. Different character sets available in the market
are 48 character set, 64 and 96 characters set. One rotation of drum prints one line. Drum printers are fast in
speed and can print 300 to 2000 lines per minute.

Advantages

• Very high speed

Disadvantages

• Very expensive
• Characters fonts cannot be changed

Chain Printer

In this printer, a chain of character sets is used, hence it is called Chain Printer. A standard character set may
have 48, 64, or 96 characters.

Department of ISE 19
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Advantages

• Character fonts can easily be changed.


• Different languages can be used with the same printer.

Disadvantages

• Noisy

Non-impact Printers

Non-impact printers print the characters without using the ribbon. These printers print a complete page at a
time, thus they are also called as Page Printers.

These printers are of two types –

• Laser Printers
• Inkjet Printers

Characteristics of Non-impact Printers

• Faster than impact printers


• They are not noisy
• High quality
• Supports many fonts and different character size

Laser Printers

These are non-impact page printers. They use laser lights to produce the dots needed to form the characters to
be printed on a page.

Department of ISE 20
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Advantages

• Very high speed


• Very high quality output
• Good graphics quality
• Supports many fonts and different character size

Disadvantages

• Expensive
• Cannot be used to produce multiple copies of a document in a single printing

Inkjet Printers

Inkjet printers are non-impact character printers based on a relatively new technology. They print characters
by spraying small drops of ink onto paper. Inkjet printers produce high quality output with presentable
features.

Department of ISE 21
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

They make less noise because no hammering is done and these have many styles of printing modes available.
Color printing is also possible. Some models of Inkjet printers can produce multiple copies of printing also.

Advantages

• High quality printing


• More reliable

Disadvantages

• Expensive as the cost per page is high


• Slow as compared to laser printer

Central Processing Unit (CPU)


A central processing unit (CPU), also called a central processor or main processor, is the electronic
circuitry within a computer that carries out the instructions of a computer program by performing the
basic arithmetic, logic, controlling, and input/output (I/O) operations specified by the instructions. Fig
1.2 shows CPU and the processors.

Department of ISE 22
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

An Intel 80486DX2 CPU, Bottom side of an Intel

Dept of CSE/ISE, as seen from above 80486DX2, bottom pins

Fig 1.2: Central Processing Unit

RVITM
Control Unit

Input Devices Output


Arithmetic and Logical Unit Devices

Memory
Unit

Fig 1.3: Block Diagram of Central Processing Unit

Department of ISE 23
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Computer Memory
Computer memory is any physical device capable of storing information temporarily like RAM (random
access memory), or permanently, like ROM (read-only memory). Memory devices utilize integrated
circuits and are used by operating systems and software.

⮚ Types of computer memory (RAM and ROM) is shown in Fig 1.4.

Memory is the most essential element of a computing system because without it computer can’t perform
simple tasks. Computer memory is of two basic type – Primary memory / Volatile memory and
Secondary memory / non-volatile memory. Random Access Memory (RAM) is volatile memory and
Read Only Memory (ROM) is non-volatile memory.

Dept of CSE/ISE,
RVITM
Fig 1.4: Types of Computer Memory

Department of ISE 24
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1. Random Access Memory (RAM) –

● It is also called as read write memory or the main memory or the primary memory.
● The programs and data that the CPU requires during execution of a program are stored
in this memory.
● It is a volatile memory as the data loses when the power is turned off.
● RAM is further classified into two types- SRAM (Static Random Access
memory) and DRAM

The differences between SRAM and DRAM is listed in Table 1.1.


Table 1.1: Difference between SRAM and DRAM
DRAM SRAM
1. Constructed of tiny capacitors that 1. Constructed of circuits similar to D
leak electricity. flip-flops.

Dept of CSE/ISE,2. Requires a recharge every few milli


seconds to maintain its data.

3. Inexpensive

4. Slower than SRAM


2. Holds its contents as long as power is
available.

3. Expensive

4. Faster than DRAM

RVITM 5. Can store many bits per chip

6. Uses less power

7. Generates less heat


5. Can not store many bits per chip

6. Uses more power

7. Generates more heat

8. Used for main memory 8. Used for cache

2. Read Only Memory (ROM) –


● Stores crucial information essential to operate the system, like the program essential to
boot the computer.
● It is not volatile.
● Always retains its data.
● Used in embedded systems or where the programming needs no change.
● Used in calculators and peripheral devices.

Department of ISE 25
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

ROM is further classified into 4 types- ROM, PROM, EPROM, and EEPROM.

Types of Read Only Memory (ROM) –


● PROM (Programmable read-only memory) – It can be programmed by user. Once
programmed, the data and instructions in it cannot be changed.
● EPROM (Erasable Programmable read only memory) – It can be reprogrammed. To
erase data from it, expose it to ultra violet light. To reprogram it, erase all the previous
data.
● EEPROM (Electrically erasable programmable read only memory) – The data can be
erased by applying electric field, no need of ultra violet light. We can erase only
portions of the chip.
Table 1.2: Difference Between RAM and ROM
BASIS FOR

Dept of CSE/ISE,
COMPARISON

Basic
RAM

It is a read-write memory.

Used to store the data that has to be


ROM

It is read only memory.

It stores the instructions


Use required during bootstrap of the

RVITM
currently processed by CPU temporarily.
computer.

Volatility It is a volatile memory. It is a nonvolatile memory.

Stands for Random Access Memory. Read Only Memory.

Data in ROM can not be


Modification Data in ROM can be modified.
modified.

ROM is comparatively
Capacity RAM sizes from 64 MB to 4GB.
smaller than RAM.

ROM is comparatively
Cost RAM is a costlier memory.
cheaper than RAM.

Types of RAM are static RAM and Types of ROM are PROM,
Type
dynamic RAM. EPROM, EEPROM.

Department of ISE 26
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Fig 1.5: Types of Memory

Dept of CSE/ISE,
Cache Memory: is a special very high-speed memory. It is used to speedup and synchronising with
high-speed CPU. Cache memory is costlier than main memory or disk memory but economical than
CPU registers. Cache memory is an extremely fast memory type that acts as a buffer between RAM and
the CPU. It holds frequently requested data and instructions so that they are immediately available to
the CPU when needed.

RVITM
Cache memory is used to reduce the average time to access data from the Main memory. The cache is a
smaller and faster memory which stores copies of the data from frequently used main memory locations.
There are various different independent caches in a CPU, which stored instruction and data.

Firure 1.6: Interaction between CPU- and Memories

Department of ISE 27
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1.3 Designing Efficient Programs

Software : Software is a set of computer programs and associated documentation and data. This is in
contrast to hardware, from which the system is built and which actually performs the work. In computing, a
program is a specific set of ordered operations for a computer to perform.

Different types of Softwares:


System Software enables the application software to interact with the computer hardware.
Applications Software - It provides the real functionality of a computer.
It help you use your computer to do specific types of work

Fundamentals of algorithms and flowcharts

Algorithm:

An algorithm is defined as unambiguous, step by step procedure (instructions) to solve a given


problem in finite number of steps by accepting a set of inputs and producing the desired output. After
producing the result, the algorithm should terminate. An algorithm is ‘an effective procedure for
solving a problem in a finite number of steps. Usually, Algorithms are written in simple English like
statements along with simple mathematical expressions.
C=A A=B
Algorithm to add 2 numbers:
B=C
Step 1: Start
Step 4: [Output the result]
Step 2: [Read 2 values a and b to be added] Print A AND B. Step 5:
Read a,b. [End of Algorithm]
Step 3: [Find the sum of 2 numbers] Stop
sum=a+b.
Step 4: [Output the result]
Print sum.
Step 5: [End of Algorithm]
Stop

Algorithm to find swap 2 numbers:


Step 1: Start
Step 2: [Read the values A and B]
Read A,B
Step 3: [Find A AND B]

Department of ISE 28
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Algorithm to find Area of Rectangle:


Step 1: Start
Step 2: [Read the values of

Dept of CSE/ISE,
length andbreadth]
Read length, breadth.
Step 3: [Find the area of
rectangle]
Area=length*brea
dth.
Step 4: [Output
the result]
Print
area.
RVITM
Step 5: [End of Algorithm]
Stop

Department of ISE 29
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Flowchart:
⮚ A flowchart is a pictorial representation of an algorithm. That is flowchart consists of sequence
of instructions that are carried out in an algorithm. All the steps are drawn in the form of different
shapes of boxes, circle and connecting arrows. Flowcharts are mainly used to help programmer to
understand the logic/the flow of the program.
⮚ The various types of geometric shapes, arrows and symbols used while drawing the flow chart
are called flowchart symbols. The symbols used and the meaning associated with each symbol are
shown below in Fig 1.10

Dept of CSE/ISE,
RVITM
Fig 1.10 : Flow chart symbols

Department of ISE 30
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

✔ Flow chart to find the area of rectangle:

Dept of CSE/ISE,
✔ Flowchart for Swapping contents of 2 variables:

RVITM

Department of ISE 31
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Algorithm & Flowchart to find the Largest of given three numbers:


Step 1: Start
Step 2: Read three numbers A, B, C
Step 3: Compare A with B
Step 4: If A is larger compare it with C
Step 5: If A is larger than C then A is the largest otherwise C is the largest.
Step 6: If A is smaller than or equal to B in the first step then B is compared with C.
Step 7: If B is larger than C then B is the largest number otherwise C is the largest
number.
Step 8: Stop

Flowchart:

Dept of CSE/ISE,
RVITM

Department of ISE 32
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Algorithm & Flowchart for solving a given quadratic equation:


Step 1: Start
Step 2: Read the values of non-zero coefficients a,b and c.
Step 3: Compute the value of discriminant (disc) which is equal to (b*b-4*a*c).
Step 4: Check if disc is equal to 0. If true, then go to Step 5. Otherwise, go to Step 6.
Step 5: Compute the roots.
root1 = (-b)/ (2*a)
root2=root1
Output the values of roots, root1 and root2.
Go to Step 9.
Step 6: Check if disc is greater than zero or not. If true, then go to Step [Link], go to Step 8.
Step 7: Compute the real and distinct roots, root1 = (-b+sqrt(disc))/(2*a)
root2 = (-b-sqrt(disc))/(2*a)
Output the values of roots, root1 and root2.

Dept of CSE/ISE,
Go to Step 9.
Step 8: Compute the complex and distinct roots.
Compute the real part, r_part = (-b)/(2*a)
Compute the imaginary part, i_part = sqrt(-disc)/(2*a)
Output roots as root1 = r_part + i_part
root2 = r_part – i_part

RVITM
Step 9: Stop

Flow Chart:

1.5 Introduction to C programming

Programming is the process of taking an algorithm and encoding it into a notation, a programming
language, so that it can be executed by a computer. Although many programming languages and
many different types of computers exist, the important first step is the need to have the solution.
Without an algorithm there can be no program.

Computer science is not the study of programming. Programming, however, is an important part
of what a computer scientist does. Programming is often the way that we create a representation
for our solutions. Therefore, this language representation and the process of creating it becomes a
fundamental part of the discipline.

Dept of CSE/ISE,
Algorithms describe the solution to a problem in terms of the data needed to represent the problem

RVITM
Department of ISE 33
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

instance and the set of steps necessary to produce the intended result. Programming languages
must provide a notational way to represent both the process and the data. To this end, languages
provide control constructs and data types.

Control constructs allow algorithmic steps to be represented in a convenient yet unambiguous way.
At a minimum, algorithms require constructs that perform sequential processing, selection for
decision-making, and iteration for repetitive control. As long as the language provides these basic
statements, it can be used for algorithm representation.

All data items in the computer are represented as strings of binary digits. In order to give these
strings meaning, we need to have data types. Data types provide an interpretation for this binary
data so that we can think about the data in terms that make sense with respect to the problem being
solved. These low-level, built-in data types (sometimes called the primitive data types) provide the
building blocks for algorithm development.

Department of ISE 34
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Programming paradigms:

A Programming paradigm is a style or “way” of programming.


1. Imperative: The language provides statements, such as assignment statements, which
explicitly change the state of the memory of the computer. In this the emphasize is on the
idea of computation as being about evaluating mathematical functions combined in
expressions. While all languages try to provide a representation of basic functions like
addition, functional languages support a functional way of expressing computations on
large and complex structures, although some such as Scheme also have imperative features.
In a pure functional language a mathematical identity like: fred(x) + fred(x)
= 2*fred(x) should hold .

2. Functional: In this paradigm we express computations as the evaluation of mathematical


functions. Languages which reflect this paradigm recognize the fact computers have re-

Dept of CSE/ISE,
usable memory that can change state. So they are characterized by statements, which affect
the state of the machine, for example : x := x+1 :This can only be understood
mathematically by associating a sequence of values with x let us say x 1, x2,..., where xt
denotes the value the variable x has at some time t. Thus the above statement can be
translated into mathematics as xt+1 = xt + 1.

RVITM
3. Logic: In this paradigm we express computation in exclusively in terms of mathematical
logic. It focusses on predicate logic, in which the basic concept is a relation. Logic
languages are useful for expressing problems where it is not obvious what the functions
should be. Thus, for example where people are concerned, it is natural to use relations. For
example consider the uncle relationship: a given person can have many uncles, and another
person can be uncle to many nieces and nephews.

4. Object-Oriented: In this paradigm we associate behavior with data-structures called


objects which belong to classes which are usually structured into a hierarchy. It focusses
on the objects that a program is representing, and on allowing them to exhibit "behavior".
This is contrasted with the typical approach in the imperative paradigm, in which one
typically thinks of operating on data with procedures. In the imperative paradigm typically
the data are passive, the procedures are active. In the O-O paradigm, data is combined with
procedures to give objects, which are thereby rendered active. For example, in the

Department of ISE 35
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

imperative paradigm, one would write a procedure which prints the various kinds of object
in the program. In the O-O paradigm, each object has a print- method, and you "tell" an
object to print itself

1.6 Structure of C programs

Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section;
}

Dept of CSE/ISE,
User-defined functions; The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer would like to use later.
The link section provides instructions to the complier to link functions from the system library.
The definition section defines all symbolic constants.

RVITM
There are some variables that are used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is outside of all the functions. This
section also declares also declares all the user-defined functions.

Every C program must have one main() function section. This section contains two parts,
declaration part and execution part. There is at least one statement in the executable part. These
two parts must appear between the opening and closing braces. The program execution begins at
the opening brace and ends at the closing brace. The closing brace of the main function section is
the logical end of the program. All statements in the declaration and executable parts end with a
semicolon (;).

Department of ISE 36
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1.7 Files used in C Program

Source Code File


• This file includes the source code of the program.
• The extension for these kind of files are '.c'. It defines the main and many more functions written in C.
• main() is the starting point of the program. It may also contain other source code files.

Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions that are shared
between various source files.

Advantages of header files:


1. At times the programmer may want to use the same subroutines for different programs. To do this, he would
just compile the code of the subroutine once and link to the resulting object file in any file in which the
functionalities of this subroutine are required.

2. At times the programmer may want to change or add the subroutines and reflect those changes in all the
programs. For doing this, he will have to only change the source file for the subroutines, recompile the source
code and then recompile and re-link the program.
This tells us that including a header file will make it easier at all levels of the program. If we need to modify
anything then changes are made only in the subroutines after which all the changes will be reflected.
Standard header files

C provides us with some standard header files which are available easily.

Department of ISE 37
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Common standard header files are:


i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

The header files are added at the start of the source code so that they can be used by more than one
function of the same file.
Object files
• They are the files that are generated by the compiler as the source code file is processed.
• These files generally contain the binary code of the function definitions.
• The object file is used by the linker for producing an executable file for combining the object files
together. It has a '.o' extension.
Executable file
• This file is generated by the linker.
• Various object files are linked by the linker for producing a binary file which will be executed
directly.
• They have an '.exe' extension.

1.8 Compilers
Compiler is an Application Software that translates from high level language to low level language.
Code Blocks is the compiler used in our laboratory.
Code::Blocks is a free C/C++ and Fortran IDE built to meet the most demanding needs of its users. It is
designed to be very extensible and fully configurable.
Built around a plugin framework, Code::Blocks can be extended with plugins. Any kind of functionality
can be added by installing/coding a plugin. For instance, event compiling and debugging functionality is
provided by plugins!

1.9 Compiling and Executing C Programs


To compile and run a C language program, you need a C compiler. A compiler is a software that is used
to compile and execute programs. To set up a C language compiler in your Computer/laptop, there are
two ways:
1. Download a full-fledged IDE like Turbo C++ or Microsoft Visual C++ or DevC++, which comes
along with a C language compiler.
2. Or, you can use any text editor to edit the program files and download the C compiler separately
and then run the C program using the command line.

Department of ISE 38
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

If you haven't already installed an IDE for the C language - Follow this step-by-step guide to Install
Turbo C++ for C Language
Using an IDE - Turbo C
We will recommend you to use Turbo C or Turbo C++ IDE, which is the oldest IDE for C
programming. It is freely available over the internet and is good for a beginner.
Step 1: Open turbo C IDE(Integrated Development Environment), click on File and then click on New

Step 2: Write a Hello World program that we created in the previous article - C Hello World program.

Step 3: Click on Compile menu and then on Compile option, or press the keys press Alt + F9 to
compile the code.

Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled to generate
the object code and then that object code is Run.
Step 5: Output

1.9Variables in ‘C’ Language

C variable is a named location in a memory where a program can manipulate the data. This location
is used to hold the value of the variable. The value of the C variable may get change in the
program. C variable might be belonging to any of the data type like int, float, char etc. The different
datatypes supported in C language are shown in Table 1.3.

Department of ISE 39
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Rules for naming variables:

⮚ All variable names must begin with a letter of the alphabet or an. underscore (_)
⮚ After the first initial letter, variable names can also contain letters and numbers.
⮚ Uppercase characters are distinct from lowercase characters.
You cannot use a C++ keyword (reserved word) as a variable name

1.10 Constants in C Language

As the name suggests the name constants is given to such variables or values in C programming
language which cannot be modified once they are defined. They are fixed values in a program. There
can be any types of constants like integer, float, octal, hexadecimal, character constants etc. Every
constant has some range. C - Constants and Literals. Constants refer to fixed values that the
program may not alter during its execution. These fixed values are also called literals. the syntaxof
declaring constants.

const int var = 5;


Syntax of declaring constants

The constants in ‘C’ Language are divided into two types 1) Primary Constants and 2) Secondary
Constants.

Dept of CSE/ISE,
The primary constants are further divided into two types 1) Numeric and 2) Character

RVITM
Fig 1.8 : Different types of constants

Department of ISE 40
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

⮚ .

Table 1.3: Datatypes supported in C Language

FORMA
MEMORY
DATA TYPE RANGE T
(BYTES) SPECIFIER
short int 2 -32,768 to 32,767 %hd
unsigned short int 2 0 to 65,535 %hu

Dept of CSE/ISE,
unsigned int
int

long int
4
4

4
0 to 4,294,967,295
-2,147,483,648 to
2,147,483,647
-2,147,483,648 to
2,147,483,647
%u
%d

%ld
unsigned long int 4 0 to 4,294,967,295 %lu

RVITM long long int


unsigned long
long int
signed char
unsigned char
8
8
1
1
-(2^63) to (2^63)-1
0 to
18,446,744,073,709,551,615
-128 to 127
0 to 255
%lld
%llu
%c
%c
float 4 %f
double 8 %lf
long double 12 %Lf

Department of ISE 41
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

C tokens
It is the basic building block of a C-Program. A C program consists of various tokens and a token
is either a keyword, an identifier, a constant, a variable.

Keywords and Identifiers

Keywords – it a word which has pre-defined meaning. The following list shows the reserved words
in C. These reserved words may not be used as constant or variable or any other identifier names.
auto else long switch
break enum register typedef
case extern return union

Dept of CSE/ISE, char


const
continue
default
float
for
goto
if
short
signed
sizeof
static
unsigned
void
volatile
while

RVITM do
double
int struct _Packed

Identifiers - A C identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero
or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in
A. Here are some examples of acceptable identifiers:

mohd zara abc move_name a_123


myname50 _temp j a23b9 retVal

Department of ISE 42
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

1.11 Managing Input and Output Operations

Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a file. C programming
language provides many built-in functions to read any given input and to display data on screen
when there is a need to output the result. Here we will learn about such functions, which can be
used in our program to take input from user and to output the result on screen. All these built-in
functions are present in C header files,
scanf() and printf() functions: The standard input-output header file, named stdio.h contains the
definition of the functions printf() and scanf(), which are used to display output on screen and to
take input from user respectively.

#include<stdio.
h>void main()
{
// defining a
variableint i;
/* displaying message on the screen asking the user to input a value
*/printf("Please enter a value...");
/* Reading the value entered by the user
*/scanf("%d", &i);
/* displaying the number as output
*/printf( "\nYou entered: %d",
i);
}

When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is
known as format string and this informs the scanf() function, what type of input to expect
andin printf() it is used to give a heads up to the compiler, what type of output to expect.
Table 2.1 : Formatted Input and Output

Department of ISE 43
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Format String Meaning

%d Scan or print an integer as signed decimal number

%f Scan or print a floating point number

%c To scan or print a character

%s To scan or print a character string. The scanning ends at whitespace.

We can also limit the number of digits or characters that can be input or output, by adding a number
with the format string specifier, like "%1d" or "%3s", the first one means a single numeric digit
and the second one means 3 characters, hence if you try to input 42, while scanf() has "%1d",
it willtake only 4 as input. Same is the case for output.
In C Language, computer monitor, printer etc output devices are treated as files and the same
process is followed to write output to these devices as would have been followed to write the output
to a file.
NOTE : printf() function returns the number of characters printed by it, and scanf() returns
thenumber of characters read by it.
int i = printf("Hello World");

In this program printf("Hello World"); will return 11 as result, which will be stored in the variable
i,because “Hello World” has 11 characters.

➢ getchar() & putchar() functions

Department of ISE 44
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

The getchar() function reads a character from the terminal and returns it as an integer. This function
reads only single character at a time. You can use this method in a loop in case you want to read more
than one character. The putchar() function displays the character passed to it on the screen andreturns
the same character. This function too displays only a single character at a time. In case you want to
display more than one characters, use putchar() method in a loop.

Department of ISE 45
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

#include <stdio.h>
void main( ){
int c;
printf("Enter a character");
/* Take a character as input and store it in variable c
*/c = getchar();
/*display the character stored in variable
c*/putchar(c);
}
When you will compile the above code, it will ask you to enter a value. When you will enter
thevalue, it will display the value you have entered.
▪ gets() & puts() functions
The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer,
until either a terminating newline or EOF (end of file) occurs. The puts() function writes the
string str and a trailing newline to stdout.

str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not
ableto understand this now.)

#include<stdio.
h>void main()
{
/* character array of length 100
*/char str[100];
printf("Enter a
string");gets( str );
puts(
str );
getch();
}
When you will compile the above code, it will ask you to enter a string. When you will enter
thestring, it will display the value you have entered.
➢ Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops reading characters when it
encounters a space, but gets() reads space as character too. If you enter name as Study Tonight
using scanf() it will only read and store Study and will leave the part after space. But gets()
function will read it completely.

Department of ISE 46
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

2.1 Programming Examples:

Example 1
The program 1 shows the use of getchar function in an interactive environment.

The program displays a question of YES/NO type to the user and reads the user's response in a
single character (Y or N). If the response is Y, it outputs the message My name is Alice
otherwise, outputs. You are good for nothing

Note there is one line space between the input text and output message.

Program: Reading a character from keyboard


#include <stdio.h>
main()
{
char answer;

printf("Would you like to know my name?\n");


printf("Type Y for YES and N for NO: ");
answer = getchar(); /* .... Reading character...*/
if(answer == 'Y' || answer == 'y')
printf("\n\nMy name is Alice\n");
else
printf("\n\nYou are good for nothing\n");
}
Output

Would you like to know my name?


Type Y for YES and N for NO: Y

My name is Alice

Would you like to know my name?


Type Y for YES and N for NO: n

You are good for nothing

Department of ISE 47
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Example 2
The program of Example 2 requests the user to enter a character and displays a message on
the screen telling the user whether the character is an alphabet or digit, or any other special
character.
This program receives a character from the keyboard and tests whether it is a letter or digit
andprints out a message accordingly. These tests are done with the help of the following
functions:
isalpha(character) isdigit(character)
For example, isalpha assumes a value non-zero (TRUE) if the argument character contains
analphabet; otherwise it assumes 0 (FALSE). Similar is the case with the function isdigit.
Program:
#include
<stdio.h>
#include
<ctype.h>
main()
{
char character;
printf("Press any
key\n");
character = getchar();
if (isalpha(character) > 0)
printf("The character is a
letter.");
else
if (isdigit (character) > 0)
printf("The character is a
digit.");
else
printf("The character is not alphanumeric.");
}
Output

Press any
keyh
The character is a letter.

Department of ISE 48
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Press any
key5
The character is a digit.

Press any key


*
The character is not alphanumeric.

Example 3
A program that reads a character from keyboard and then prints it in reverse case is given
inExample 3. That is, if the input is upper case, the output will be lower case and vice
versa.
The program uses three new functions: islower, toupper, and tolower. The function islower is
a conditional function and takes the value TRUE if the argument is a lower case alphabet;
otherwise takes the value FALSE. The function toupper converts the lower case argument into
an upper case alphabet while the function tolower does the reverse.

Program
#include
<stdio.h>
#include
<ctype.h>

main()
{
char alphabet;
printf("Enter an alphabet");
putchar('\n'); /* move to next line
*/alphabet = getchar();
if (islower(alphabet))
putchar(toupper(alphabet)
);
else
putchar(tolower(alphabet));
}
Output
Enter an alphabet
a
A

Department of ISE 49
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Enter an alphabet
Q
q
Enter an alphabet
z
Z

Example 4
Various input formatting options for reading integers are experimented in the program
shownin Example 4.

The first scanf requests input data for three integer values a, b, and c, and accordingly three
values 1, 2, and 3 are keyed in. Because of the specification %*d the value 2 has been skipped
and 3 is assigned to the variable b. Notice that since no data is available for c, it contains
garbage.

The second scanf specifies the format %2d and %4d for the variables x and y respectively.
Whenever we specify field width for reading integer numbers, the input numbers should not
contain more digits that the specified size. Otherwise, the extra digits on the right-hand side will
be truncated and assigned to the next variable in the list. Thus, the second scanf has truncated
the four digit number 6789 and assigned 67 to x and 89 to y. The value 4321 has been assigned
to the first variable in the immediately following scanf statement.
Program:
main()
{
int
a,b,c,x,y,z;
int p,q,r;
printf("Enter three integer
numbers\n");scanf("%d %*d
%d",&a,&b,&c); printf("%d %d %d
\n\n",a,b,c);
printf("Enter two 4-digit
numbers\n");scanf("%2d
%4d",&x,&y);
printf("%d %d\n\n", x,y);

Department of ISE 50
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

printf("Enter two integers\n")


;scanf("%d %d", &a,&x);
printf("%d %d \n\n",a,x);
printf("Enter a nine digit number\n");
scanf("%3d %4d %3d",&p,&q,&r);
printf("%d %d %d \n\n",p,q,r);
printf("Enter two three digit numbers\n");
scanf("%d %d",&x,&y);
printf("%d %d",x,y);
}

Output
Enter three integer
numbers1 2 3
1 3 -3577
Enter two 4-digit
numbers6789 4321
67 89
Enter two
integers44 66
4321 44
Enter a nine-digit
number123456789
66 1234 567
Enter two three-digit
numbers123 456
89 123

Department of ISE 51
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Department of ISE 52
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Reading of real numbers (in both decimal point and exponential notation) is illustrated
inExample 5.
Program:
main()
{
float
x,y;
double
p,q;
printf("Values of x and
y:");scanf("%f %e", &x,
&y);
printf("\n");
printf("x = %f\ny = %f\n\n", x, y);
printf("Values of p and q:");
scanf("%lf %lf", &p, &q);
printf("\np = %lf\nq =
%e",p,q);
printf("\n\np = %.12lf\np = %.12e", p,q);
}

Output:

Values of x and y:12.3456


17.5e-2x = 12.345600
y = 0.175000
Values of p and q:4.142857142857
18.5678901234567890p = 4.142857142857
q = 1.856789012346e+001
Example 6
Reading of strings using %wc and %ws is illustrated in Example 6.

The program in Example 6 illustrates the use of various field specifications for reading
[Link] we use %wc for reading a string, the system will wait until the wth character is
keyed in.
Note that the specification %s terminates reading at the encounter of a blank space. Therefore,
name2 has read only the first part of "New York" and the second part is automatically assigned

Department of ISE 53
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

to name3. However, during the second run, the string "New-York" is correctly assigned to
name

2.

main()
{
int no;
char name1[15], name2[15], name3[15];
printf("Enter serial number and name
one\n");scanf("%d %15c", &no, name1);
printf("%d %15s\n\n", no, name1);
printf("Enter serial number and name
two\n");scanf("%d %s", &no, name2);
printf("%d %15s\n\n", no, name2);
printf("Enter serial number and name
three\n");scanf("%d %15s", &no, name3);
printf("%d %15s\n\n", no, name3);
}

Output
Enter serial number and name
one1 123456789012345
1 123456789012345r
Enter serial number and name
two2 New York
2 New
Enter serial number and name three
2 York
Enter serial number and name
one1 123456789012
1 123456789012 r
Enter serial number and name
two2 New-York
2 New-York
Enter serial number and name
three3 London
3 London

Department of ISE 54
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Example 7
The program in Example 7 illustrates the function of %[ ] specification.
Program A:
main()
{
char address[80];
printf("Enter address\n");
scanf("%[a-z]", address);
printf("%-80s\n\n",
address);
}
Output
Enter address
new delhi
110002new
delhi
Program-B
main()
{
char address[80];
printf("Enter
address\n");
scanf("%[^\n]",
address);printf("%-
80s", address);
}
Output
Enter address
New Delhi 110 002
New Delhi 110 002

Example 8
The program presented in Example 8 illustrates the testing for correctness of reading of
data by scanf function.

Department of ISE 55
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

The function scanf is expected to read three items of data and therefore, when the values for all the three
variables are read correctly, the program prints out their values. During the third run, the second item
does not match with the type of variable and therefore the reading is terminated and the error message
is printed. Same is the case with the fourth run.
In the last run, although data items do not match the variables, no error message has
beenprinted. When we attempt to read a real number for an int variable, the integer part is
assignedto the variable, and the truncated decimal part is assigned to the next variable.
Note that the character `2' is assigned to the character variable c.

Program

main()
{
int
a;
float
b;
char
c;
printf("Enter values of a, b and c\n");
if (scanf("%d %f %c", &a, &b, &c) == 3)
printf("a = %d b = %f c = %c\n" , a, b, c);
else
printf("Error in input.\n");
}

Output
Enter values of a, b and c 12
3.45 A
a = 12 b = 3.450000 c = A
Enter values of a, b and c23 78 9
a = 23 b = 78.000000 c = 9
Enter values of a, b and c8 A 5.25
Error in input.
Enter values of a, b and cY 12 67
Error in input.

Department of ISE 56
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Enter values of a, b and c


15.75 23 X
a = 15 b = 0.750000 c = 2
Example 9
The program in Example 9 illustrates the output of integer numbers under various formats.
Program:
main()
{
int m = 12345;
long n =
987654;

printf("%d\n",m);
printf("%10d\n",m
);
printf("%010d\n",
m);printf("%-
10d\n",m);
printf("%10ld\n",n
);
printf("%10ld\n",-
n);
}
Output
12345
12345
0000012345
12345
987654
-987654

Example 10
All the options of printing a real number are illustrated in Example 10.
Program
main()
{
float y = 98.7654;

Department of ISE 57
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

printf("%7.4f\n", y);
printf("%f\n", y);
printf("%7.2f\n", y);
printf("%-7.2f\n", y);
printf("%07.2f\n", y);
printf("%*.*f", 7, 2,
y);printf("\n");
printf("%10.2e\n", y);
printf("%12.4e\n", -y);
printf("%-10.2e\n", y);
printf("%e\n", y);
}
Output
98.7654
98.765404
98.77
98.77
0098.77
98.77
9.88e+001
-
9.8765e+0
01
9.88e+001
9.876540e+001

Example 11
Printing of characters and strings is illustrated in Example11.
Program
main()
{
char x = 'A';
static char name[20] = "ANIL KUMAR GUPTA";

printf("OUTPUT OF
CHARACTERS\n\n");
printf("%c\n%3c\n%5c\n", x,x,x);
printf("%3c\n%c\n", x,x);

Department of ISE 58
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

printf("\n");

printf("OUTPUT OF STRINGS\n\n");
printf("%s\n", name);
printf("%20s\n", name);
printf("%20.10s\n", name);
printf("%.5s\n", name);
printf("%-20.10s\n", name);
printf("%5s\n", name);
}

Output

OUTPUT OF CHARACTERS

A
A

OUTPUT OF STRINGS

ANIL KUMAR GUPTA


ANIL KUMAR GUPTA
ANIL KUMAR
ANIL
ANIL KUMAR
ANIL KUMAR GUPTA

Sample C programs:
1. Program to demonstrate printf statement

#include<stdio.
h>main()
{

Department of ISE 59
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

printf(“hello,
world\y”);
printf(“hello,
world\7”);
printf(“hello,
world\?”);
}

1) Program to convert farenheit to Celsius

#include<stdio.
h>main()
{
float fahr, Celsius;
printf(“ enter the value for
farenheit\n”);scanf(“ %f”, &fahr);
Celsius=(5.0/9.0)*fahr-32.0;
printf(“%f %f \n”, fahr,Celsius);
}

2) Program to depict interactive computing using scanf

function.#include<stdio.h>

main()
{ int number;
printf(“enter an integer number\n”);

scanf(“%d”,
&number);if
(number<100)
{
printf(“Your number is smaller than 100\n\n”);
}
else
printf(“Your number contains more than two digits\n”);
}

Department of ISE 60
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Output:
Enter an integer
number54
Your number is smaller than 100

Enter an integer
number108
Your number contains more than digits
3) Program to depict interactive investment program

#include<stdio.

h>main()
{
int year,period;
float amount,inrate,value;

printf(“Input amount , interest rate and period


\n\n”);scanf(“%f %f %d”, &amount,
&inrate,&period); printf(“\n”);
year=1;
while(year<=peri
od)
{
value amount + inrate*amount;
printf(“%2d Rs. %8.2f\n”, year,
value);

amount=val
ue;
year=year+
1;
}
}

Department of ISE 61
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

4) Program to calculate the average of a set of N numbers

#define N

10main()
{
int count;
float sum,
average,number;sum=0;
count=0;
while(count<N)
{
scanf(“%f”,
&number);
sum=sum+number;
count=count+1;
}
average= sum/N;
printf(“N=%d Sum= %f”, N, sum); printf(“Average=%f”, average);
}
5) Program to convert days to months and days

#include<stdio.
h>main()
{
int months,days; printf(“enter days
\n”);scanf(“%d”, &days);
months=days/
30;
days=days%3
0;
printf(“Months = %d Days= %d”, months,days);
}

Department of ISE 62
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Department of ISE 63
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Dept of CSE/ISE,
RVITM
Algorithm & flowchart to find the Factorial of a given integer:
Algorithm:
Step 1. Start
Step 2. Read the number n
Step 3. [Initialize] i=1, fact=1

Department of ISE 64
RV INSTITUTE OF TECHNOLOGY AND MANAGEMENT

Step 4. Repeat step 4 through 6 until i=n


Step 5. fact=fact*i
Step 6. i=i+1
Step 7. Print fact
Step 8. Stop [process finish of calculate the factorial value of a number]

Flowchart:

Dept of CSE/ISE,
RVITM

Department of ISE 65

You might also like