Module 1
Module 1
Introduction to Computers
1.1 Computer
A computer can be defined as an electronic device that is designed to accept data, perform the
required mathematical and logical operations at high speed, and output the result.
2. Accuracy
A computer is a very fast, reliable, and robust electronic device.
It always gives accurate results, provided the correct data and set of instructions are input to it.
This clearly means that the output generated by a computer depends on the given instructions
and input data.
If the input data is wrong, then the output will also be erroneous. In computer terminology, this
is known as garbage-in, garbage-out (GIGO).
3. Automation
Besides being very fast and accurate, computers are automatable devices that can perform a task
without any user intervention.
The user just needs to assign the task to the computer, after which it automatically controls
different devices attached to it and executes the program instructions.
4. Diligence
Computers never get tired of a repetitive task. It can continually work for hours without creating
errors.
Even if a large number of executions need to be executed, each and every execution requires the
same duration, and is executed with the same accuracy.
5. Versatile
Versatility is the quality of being flexible. Today, computers are used in our daily life in
different fields.
For example, they are used as personal computers (PCs) for home use, for business-oriented
tasks, weather forecasting, space exploration, teaching, railways, banking, medicine, and so on,
indicating that computers can perform different tasks simultaneously.
1
6. Memory
Computers have internal or primary memory (storage space) as well as external or secondary
memory.
The computer stores a large amount of data and programs in the secondary storage space.
The stored data and programs can be retrieved and used whenever required.
Secondary memory is the key for data storage. Some examples of secondary devices include
floppy disks, optical disks (CDs and DVDs), hard disk drives (HDDs), and pen drives.
7. No IQ
Although the trend today is to make computers intelligent by inducing artificial intelligence
(AI) in them, they still do not have any decision-making abilities of their own. They need
guidance to perform various tasks.
8. Economical
Today, computers are considered as short-term investments for achieving long-term gains.
Using computers also reduces manpower requirements and leads to an elegant and efficient way
of performing various tasks.
Hence, computers save time, energy, and money. When compared to other systems, computers
can do more work in lesser time.
For example, using the conventional postal system to send an important document takes at least
two to three days, whereas the same information when sent using the Internet (e-mail) will be
delivered instantaneously.
2
Figure 1.2. Von Neumann architecture (a) Shared memory for instructions and data (b)
Separate memories for instructions and data
3
1977: Apple II was launched that offered colour graphics and incorporated an audio cassette
drive for storage.
1978: a word processor application, was released by MicroPro International.
1979: the first computerized spreadsheet program for personal computers, was unveiled.
1981: The first IBM personal computer was introduced that used Microsoft’s MS-DOS
operating system. The term PC was popularized.
1983: The first laptop was introduced.
1985: Microsoft announced Windows as a new operating system.
1986: Compaq introduced Deskpro 386 in the market, which was a 32-bit architecture machine
that provides speed comparable to mainframes.
1990: Invented the World Wide Web with HTML as its publishing language.
1993: The Pentium microprocessor introduced the use of graphics and music on PCs.
1994: PC games became popular.
1996: developed the Google search engine at Stanford University.
1999: The term Wi-Fi was introduced when users started connecting to the Internet without
wires.
2001: Apple introduced Mac OS X operating system, which had protected memory architecture
and pre-emptive multi-tasking, among other benefits. To stay competitive, Microsoft launched
Windows XP.
2003: The first 64-bit processor, AMD’s Athlon 64, was brought into the consumer market.
2004: Mozilla released Firefox 1.0 and in the same year Facebook, a social networking site, was
launched.
2005: YouTube, a video sharing service, was launched. In the same year, Google acquired
Android, a Linux-based mobile phone operating system.
2006: Apple introduced MacBook Pro, its first Intelbased, dual-core mobile computer.
2007: Apple released iPhone, which brought many computer functions in the smartphone.
2009: Microsoft launched Windows 7 in which users could pin applications to the taskbar.
2010: Apple launched iPad, which revived the tablet computer segment.
2011: Google introduced Chromebook, a laptop that runs on the Google Chrome operating
system.
2015: Apple released the Apple Watch. In the same year, Microsoft launched Windows 10.
Memory
Electromagnetic relay was used as primary memory and
Punched cards were used to store data and instructions.
Software Technology
Programming was done in machine or assembly language.
Highlights
They were the fastest calculating device.
Computers were too bulky and required a complete room for storage
Highly unreliable as vacuum tubes emitted a large amount of heat and burnt frequently
4
Required air-conditioned rooms for installation
Costly
Difficult to use
Required constant maintenance because vacuum tubes used filaments that had limited
life time. Therefore, these computers were prone to frequent hardware failures.
Memory
Magnetic core memory was used as primary memory;
Magnetic tapes and magnetic disks were used to store data and instructions.
These computers had faster and larger memory than the first generation computers.
Software Technology
Programming was done in high level programming languages. Batch operating system
was used.
Highlights
Faster, smaller, cheaper, reliable, and easier to use
They consumed 1/10th the power consumed by first generation computers
Bulky in size
Dissipated less heat than first generation computers
Costly
Difficult to use.
Memory
Larger magnetic core memory was used as primary memory; larger capacity magnetic
tapes and magnetic disks were used to store data and instructions.
Highlights
Faster, smaller, cheaper, reliable, and easier to use than the second generation computers
They consumed less power than second generation computers.
Bulky in size and required a complete room for installation
Dissipated less heat than second generation computers
Costly
5
Easier to use and upgrade
Software Technology
Programming was done in high level programming languages such as FORTRAN,
COBOL, Pascal, and BASIC.
Time sharing operating system was used.
Software was separated from the hardware.
Memory
Semiconductor memory was used as primary memory; large capacity magnetic disks
were used as built in secondary memory.
Magnetic tapes and floppy disks were used as portable storage devices.
Software Technology
Programming was done in high level programming language such as C and C++.
Graphical User Interface (GUI) based operating system (e.g. Windows) was
introduced. It had icons and menus among other features to allow computers to be used
as a general purpose machine by all users.
UNIX was also introduced as an open source operating system. Apple Mac OS and MS
DOS were also released during this period.
All these operating systems had multi-processing and multiprogramming capabilities.
Examples IBM PC, Apple II, TRS-80, VAX 9000, CRAY1, CRAY-2, CRAY-X
Highlights
Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers.
Memory
Semiconductor memory is used as primary memory;
large capacity magnetic disks are used as built-in secondary memory.
portable storage devices like optical disks and USB flash drives are used.
6
Software Technology
Programming is done in high-level programming languages such as Java, Python, and
C#.
Graphical User Interface (GUI)-based operating systems such as Windows, Unix, Linux,
Ubuntu, and Apple Mac are being used.
These operating systems are more powerful and user friendly than the ones available in
the previous generations.
Used for Scientific, commercial, interactive online, multimedia (graphics, audio, video), and
network applications.
Examples IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2, Param supercomputer
Highlights
Faster, smaller, cheaper, powerful, reliable, and easier to use than the previous
generation computers.
Speed of microprocessors and the size of memory are growing rapidly.
High-end features available on the microprocessors
They consume less power than computers of prior generations.
3. Minicomputers
Minicomputers are smaller, cheaper, and slower than mainframes.
They are called minicomputers because they were the smallest computer of their times. Also
known as midrange computers.
Minicomputers are widely used in business, education, hospitals, government organizations, etc.
While some minicomputers can be used only by a single user, others are specifically designed to
handle multiple users simultaneously.
Minicomputers can also be used as servers in a networked environment.
4. Microcomputers
Microcomputers, commonly known as PCs, are very small and cheap.
Many computer hardware companies copied this design and termed their microcomputers as
PC-compatible.
PCs can be classified into the following categories:
Desktop PCs, Laptops, Workstations, Network Computers and Handheld Computers.
(i) Desktop PCs A desktop PC is the most popular model of PCs.
(ii) Laptops: Laptops operate on a battery. The memory and storage capacity of a laptop is
almost equivalent to that of a desktop computer. laptops have the same features and processing
speed as the most powerful PCs.
(iii) Workstations: Workstation computers have advanced processors, more RAM and storage
capacity than PCs.
(iv) Network Computers: Network computers have less processing power, memory, and
storage than a desktop computer. Some network computers do not have any storage space and
merely rely on the network’s server for data storage and processing tasks
(v) Handheld Computers: Handheld computers are very small in size, and hence they have
small-sized screens and keyboards. Some examples of handheld computers are as follows:
Smartphones, Tablet PCs.
a. Smartphones: These days, cellular phones are web-enabled telephones. Such phones are also
known as smartphones because, in addition to basic phone capabilities, they also facilitate the
users to access the Internet and send e-mails, edit Word documents, generate an Excel sheet,
create a presentation, and lots more.
b. Tablet PCs: A tablet PC is a computing device that is smaller than a laptop, but bigger than a
smartphone. Features such as user-friendly interface, portability, and touch screen have made
them very popular in the last few years.
Uses The following are the uses of Tablet PCs:
• View presentations
• Videoconferencing
• Reading e-books, e-newspaper
• Watching movies
• Playing games
• Sharing pictures, video, songs, documents, etc.
• Browsing the Internet
• Keeping in touch with friends and family on popular social networks, sending emails
• Business people use them to perform tasks such as editing a document, exchanging
documents, taking notes, and giving presentations
• Tablets are best used in crowded places such as airports and coffee shops.
2. Internet
The Internet is a network of networks that connects computers all over the world.
It gives the user access to an enormous amount of information, much more than available in any
library.
Using e-mail, the user can communicate in seconds with a person who is located thousands of
miles away.
Chat software enables users to chat with another person in real-time.
Video conferencing tools are becoming popular.
4. Desktop publishing
Desktop publishing software enables us to create page layouts for entire books.
5. e-Business
e-Business or electronic business is the process of conducting business via the Internet.
This may include buying and selling of goods and services using computers and the Internet.
Companies today use e-commerce applications for marketing, transaction, processing, and
product and customer services processing.
Business-to-consumer or B2C: In this form of electronic commerce, business companies
deploy their websites on the Internet to sell their products and services to the customers. On
their websites, they provide features such as catalogues, interactive order processing system,
secure electronic payment system, and online customer support.
Business-to-business or B2B: This type of electronic commerce involves business transactions
performed between business partners (customers are not involved). For example, companies use
computers and networks (in the form of extranets) to order raw materials from their suppliers.
Companies can also use extranets to supply their products to their dealers.
Consumer-to-consumer or C2C: This type of electronic commerce enables customers to carry
business transactions among themselves. For example, on auction websites, a customer sells
his/her product which is purchased by another customer.
Electronic banking Electronic banking, also known as cyber banking or online banking,
supports various banking activities conducted from home, a business, or on the road instead of a
physical bank location.
6. Bioinformatics
Bioinformatics is the application of computer technology to manage large amount of biological
information.
Computers are used to collect, store, analyse, and integrate biological and genetic information to
facilitate gene-based drug discovery and development.
Bioinformatics is an interdisciplinary field of molecular biology, computer science, statistics,
and mathematics.
7. Health care
Computers have also become a necessary device in the health care industry. The following are
areas in which computers are extensively used in the health care industry:
Storing records: computers are first and foremost used to store the medical records of patients.
Surgical procedures Computers are used for certain surgical procedures. They enable the
surgeon to use computer to control and move surgical instruments in the patient’s body for a
variety of surgical procedures.
Better diagnosis and treatment Computers help physicians make better diagnoses and
recommend treatments.
9. Meteorology
Meteorology is the study of the atmosphere. Meteorology has applications in many diverse
fields. Some of the applications include the following:
Weather forecasting It includes application of science and technology to predict the state of the
atmosphere (temperature, precipitation, etc.) for a future time and a given location.
Aviation meteorology Aviation meteorology studies the impact of weather on air traffi c
management.
Agricultural meteorology Agricultural meteorology deals with the study of effects of weather
and climate on plant distribution, crop yield, water-use efficiency, plant and animal
development.
Nuclear meteorology Nuclear meteorology studies the distribution of radioactive aerosols and
gases in the atmosphere. Maritime meteorology Maritime meteorology is the study of air and
wave forecasts for ships operating at sea.
Multimedia and Animation Multimedia and animation that combines still images, moving
images, text, and sound in meaningful ways is one of most powerful aspects of computer
technology. We all have seen cartoon movies, which are nothing but an example of computer
animation.
12. Sports
In sports, computers are used to compile statistics, identify weak players and strong players by
analysing statistics, sell tickets, create training programs and diets for athletes, and suggest
game plan strategies based on the competitor’s past performance.
14. Simulation
Simulation of automobile crashes or airplane emergency landings is done to identify potential
weaknesses in designs without risking human lives.
15. Education
A computer is a powerful teaching aid and can act as another teacher in the classroom. Teachers
use computers to develop instructional material.
17. Robotics
Robots are computer-controlled machines mainly used in the manufacturing process in extreme
conditions where humans cannot work.
Input: This is the process of entering data and instructions (also known as programs) into the
computer system. The data and instructions can be entered by using different input devices such as
keyboard, mouse, scanner, and trackball.
Figure 1.4. Block diagram of a computer
Storage: Storage is the process of saving data and instructions permanently in the computer so that
they can be used for processing.
A computer has two types of storage areas:
Primary storage: Primary storage, also known as the main memory, is the storage area that is
directly accessible by the CPU at very high speeds. Primary storage space is very expensive and
therefore limited in capacity.Another drawback of main memory is that it is volatile in nature; that
is, as soon as the computer is switched off, the information stored gets erased. Hence, it cannot be
used as a permanent storage of useful data and programs for future use. Example of primary storage
is random access memory (RAM).
Secondary storage Also known as auxiliary memory. It is cheaper, non-volatile, and used to
permanently store data and programs of those jobs that are not being currently executed by the CPU.
Output: Output is the process of giving the result of data processing to the outside world. The
results are given through output devices such as monitor, and printer. Since the computer accepts
data only in binary form and the result of processing is also in binary form, the result cannot be
directly given to the user. The output devices, therefore, convert the results available in binary codes
into a human-readable language before displaying it to the user.
Control: The control unit (CU) manages and controls all the components of the computer system. It
is the CU that decides the manner in which instructions will be executed and operations performed.
It takes care of the step-by-step processing of all operations that are performed in the computer.
The CPU is a combination of the arithmetic logic unit (ALU) and the CU. The CPU is better
known as the brain of the computer system because the entire processing of data is done in the
ALU, and the CU activates and monitors the operations of other units (such as input, output, and
storage) of the computer system.
Processing: The process of performing operations on the data as per the instructions specified by
the user (program) is called processing. Data and instructions are taken from the primary memory
and transferred to the ALU, which performs all sorts of calculations.
1.8 Motherboard
The motherboard, also known as the main board or the parent board is the primary component
of a computer. It is used to connect all the components of the computer.
Characteristics of a Motherboard
A motherboard can be classified depending on the following characteristics:
Form factor
Chipset
Type of processor socket used
Input–Output connectors
Form factor: Form factor refers to the motherboard’s geometry, dimensions, arrangement, and
electrical requirements.
Integrated components: Some of the motherboard’s components are integrated into its printed
circuitry. These include the following:
The chipset is a circuit that controls the majority of the computer’s resources such as the bus
interface with the processor, cache memory, RAM, and expansion cards.
CMOS clock and battery
BIOS
System bus and expansion bus
Chipset: The chipset is an electronic circuit that basically coordinates data transfers between the
different components of the computer.
Some chipsets may include a graphics or audio chip, which makes it unnecessary to install a
separate graphics card or sound card.
CMOS clock and battery: The real-time clock (or RTC) is a circuit that is used to synchronize the
computer’s signals. When the computer is switched off, the power supply stops providing electricity
to the motherboard. The CMOS chip is powered by a battery located on the motherboard.
Processor socket: The processor (also called the microprocessor) is the brain of the computer. The
processor is characterized by its speed or frequency, which is the rate at which it executes
instructions.
RAM connectors RAM is the primary storage area that stores data while the computer is running.
However, its contents are erased when the computer is turned off or restarted.
Expansion slots: Expansion slots are compartments into which expansion cards can be inserted.
Such cards render new features or enhance the computer’s performance.
I/O connectors: The motherboard has a number of input– output sockets on its rear panel, some of
which include:
A serial port to connect some old peripherals
A parallel port to connect old printers
USB ports to connect more recent peripherals such as mouse and pen drive.
RJ45 connector (also known as LAN or Ethernet port) to connect the computer to a network.
It corresponds to a network card integrated into the motherboard.
Video graphics array (VGA) connector to connect a monitor. This connector interfaces with
the built-in graphics card.
Audio plugs that include the line in, line out, and microphone to connect sound speakers, hi-
fi system, or microphone. This connector interfaces with the built-in sound card.
13
Figure 1.5. Computer’s motherboard
soprotection.com
Module 1
Input and Output Devices
2.1 Input Devices
An input device is used to feed data and instructions into the computer. In the absence of an
input device, a computer would have only been a display device.
2.1.1 Keyboard
With a keyboard, the user can type a document, use keystroke shortcuts, access menus, play
games and perform numerous other tasks. Most keyboards have between 80 and 110 keys which
include:
Typing keys: These include the letters of the
alphabet. The layout of the keyboard is known
as QWERTY for its first 6 letters.
Control keys: These keys provide cursor and screen control. It includes four directional arrow
key. Control keys also include Home, End, Insert, Delete, Page Up, Page Down, Control (Ctrl),
Alternate (Alt), Escape(Esc).
Special purpose keys: Keyboard also contains some special purpose keys such as Enter, Shift, Caps
Lock, Num Lock, Space bar, Tab, and Print screen.
2. TRACKBALL
A trackball is a pointing device which is used to control the position of the
cursor on the screen. These are usually used in notebook and laptop
computers where it is placed on the keyboard. The trackball is nothing but
an upside-down mouse that rotates in place within a socket. The user rolls
the ball to position the cursor at an appropriate position on the screen and
then clicks one of the buttons to select objects or position the cursor for text entry.
Advantages:
Trackball provides better resolution; Occupies less space
Easier to use as compared to mouse as its use involves less hands-and-arms movements.
Disadvantage:
The trackball chamber is often covered with dust, so it must be cleaned regularly.
3. TOUCHPAD
A touchpad (or track pad) is a small, flat, rectangular stationary
pointing device with sensitive surface of 1.5 or 2 inches square. The
user has to slide his finger tips across the surface of the pad to point
to a specific object on the screen.
The surface translates the motion and position of user’s fingers to a
relative position on the screen. There are also buttons around the
edge of the pad that work like mouse buttons. Touchpad is widely used in laptops and is built-in
on the keyboard.
Advantages:
Occupies less space.
Easier to use as compared to mouse as its use involves less hands-and-arms movements.
It is built-in the keyboard, so no need to carry an extra device separately.
2. STYLUS:
A stylus is a pen-shaped input device used to enter information or
write on the touch screen of a phone. Stylus is a small stick that
can also be used to draw lines on a surface as input to a computer,
choose an option from a menu, move the cursor to another location
on the screen, take notes and create short messages. The stylus
usually slides into a slot built into the smart phone for that purpose.
3. TOUCH SCREEN:
A touch screen is a display screen which can identify the occurrence
and position of a touch inside the display region. The user can touch
the screen either by his finger or by using a stylus. These displays
can be connected to computers, laptops, PDAs, cell phones etc.
2. IMAGE SCANNER:
• It is a device that captures images, printed text, handwriting from
different sources and converts it into a digital image for computer editing
and display.
• Scanners come in hand-held, feed-in, and flatbed types.
• In the flat bed scanner, the object to be scanned is placed on a
glass pane and a sensor and light moves along the pane, reflecting off the
image placed on the glass.
• A hand image scanner has to be manually moved across an object or image to be
scanned. The scanner produces light from green LEDs which highlight and scan the
image onto a computer for further processing.
• Film scanners are usually used in photography and slides. The slide or negative film is
first inserted in strips of six or less frames into the film scanner, and then moved across a
lens and censor to capture the image.
Disadvantages:
OCR cannot recognize all types of fonts.
Documents that are poorly types or have strikeover cannot be recognized.
Very old documents when passed through OCR may not have an exact copy of the text
file.
Web cameras also capture videos which can be transferred via internet in real time.
Advantages:
• Video input devices are very useful for applications like video
conferencing.
• Video input devices can be used to record memorable moments in one’s life.
• Video input devices can be used to check security.
Disadvantages:
• Videos and images captured using video input devices have a very big file size and there
must be compressed before being stored on the computer.
• Plasma monitors are thin and flat monitors widely used in TVs and computers. The
plasma display contains two glass plates that have tiny cells filled with xenon and neon
gas.
• The display electrode is covered by a magnesium oxide protective layer and is arranged
in horizontal rows along the screen while the address electrodes are arranged in vertical
columns thereby forming grid like structure.
• To ionize the gas in a particular cell, the electrodes that intersect at that cell are charged
at least thousands of times in a small fraction of a second.
• An electric current begins to flow through the gas in the cell. The current creates a rapid
flow of charged particles thereby stimulating the gas atoms to release ultraviolet
photons.
• When these UV photons hit a phosphor atom in the cell, one of the phosphor's electrons
jumps to a higher energy level and the atom heats up. When the electron falls back to its
normal level, it releases energy in the form of a visible light photon.
3. SPEAKERS :
Today all business and home users demand sound capabilities and thus different types of
speakers to enable users to enjoy music, movie, or a game and the voice will be spread through
the entire room. With good quality speakers, the voice will also be audible even to people sitting
in another or room or even to neighbors.
However, in case the user wants to enjoy loud music without disturbing the people around him,
he can use a headphone.
Another device called headset was developed to allow the users to talk and listen at the same
time, using the same device.
PRINTERS
Printer is a device that outputs text and graphics information obtained from the computer and
prints it on to a paper. Printers are available in the market in a variety of size, speed,
sophistication, and cost. The qualities of printer which are of interest to users include:
Color: Colored printouts are needed for presentations or maps and other pages where color is
part of the information. They are more expensive.
Memory: Most printers have a small amount of memory that can be expanded by the user.
Having more memory makes enhances the speed of printing
Resolution: The resolution of a printer means the sharpness of text and images on paper. It is
usually expressed in dots per inch (dpi). Even the least inexpensive printer provides sufficient
resolution for most purposes at 600 dpi.
Speed: Speed means number of pages that are printed in one minute. While high speed printers
are a little expensive, the inexpensive printers on the other hand can print only about 3 to 6
sheets per minute. Color printing is even slower.
A. Impact Printer: They create characters by striking an inked ribbon against the paper.
Example: dot-matrix printers, daisywheel printers, and most types of line printer.
B. Non Impact Printer: Non-impact printers are much quieter than impact printers as their
printing heads do not strike the paper. They offer better print quality, faster printing and
the ability to create prints that contain sophisticated graphics.
Non-impact printers use either solid or liquid cartridge-based ink which is either
sprayed, dripped or electro statically drawn onto the page. The main types of non-impact
printer are: inkjet, printer, laser printer and thermal printer.
A dot matrix printer prints characters and images of all types as a pattern of dots. It has a print
head (or hammer) that consists of pins representing the character or image. The print head runs
back and forth, or in an up and down motion, on the page and prints by striking an ink-soaked
cloth ribbon against the paper, much like the print mechanism on a typewriter.
Advantages:
• It can produce carbon copies; offers lowest printing cost per page.
• widely used for bulk printing where quality of the print is not of much importance; is
cheap; When the ink is about to finish,
• The printout gradually fades rather than suddenly stopping partway through a job.
• It can use continuous paper rather than individual sheets, making them useful for data
logging.
Disadvantages :
• It creates a lot of noise when the pins strike the ribbon to the paper.
• It can only print lower-resolution graphics, with limited quality.
• It is very slow.
• Poor print quality.
• Daisy wheel printers use an impact printing technology to generate high-quality output
comparable to typewriters but three times faster.
• The print head of a daisy wheel printer is a circular wheel, about 3 inches in diameter
with arms or spokes. The characters are embossed at the outer end of the arms.
• To print a character, the wheel is rotated in such a way that the character to be printed is
positioned just in front of the printer ribbon.
• The spoke containing the required character is then hit by a hammer thereby striking the
ribbon to leave an impression on the paper placed behind the ribbon. Movement of all
these parts is controlled by microprocessor in the printer.
• The key benefit of using a daisy wheel printer is that the print quality is high as the exact
shape of the character hits the ribbon to leave and impression on paper.
LINE PRINTER:
Line printer is a high speed impact printer in which one typed line is printed at a time. The
speed of a line printer usually varies from 600 to 1200 lines-per-minute or approximately 10 to
20 pages per minute. They are widely used in datacenters and in industrial environments. Band
printer is a commonly used variant of line printers.
Band Printer: A band printer (loop printer) is an impact printer. The set of characters are
permanently embossed on the band and this set cannot be changed unless the band is replaced.
The band itself revolves around hammers that push the paper against the ribbon, allowing the
desired character to be produced on the paper. However, band printers cannot be used for any
graphics printing as the characters are predetermined and cannot be changed unless the band is
changed.
INKJET PRINTERS
• In inkjet printers, the print head has several
tiny nozzles, also called jets.
• As the paper moves past the print head, the
nozzles spray ink onto it, forming the characters and
images.
• The dots are extremely small (usually
between 50 and 60 microns in diameter) and are
positioned very precisely, with resolutions of up to 1440x720 dots per inch (dpi).
• There is usually one black ink cartridge and one so-called color cartridge containing ink
in primary pigments (cyan, magenta, and yellow).
• While inkjet printers are cheaper than laser printers, they are more expensive to
maintain. The cartridges of inkjet printers have to be changed more frequently and the
special coated paper required to produce high-quality output is very expensive. So the
cost per page of inkjet printers becomes ten times more expensive than laser printers.
Therefore, inkjet printers are not well-suited for high-volume print jobs.
LASER PRINTER
PLOTTERS
A plotter is used to print vector graphics with a high print quality. They
are widely used to draw maps, in scientific applications and in
applications like CAD, CAM and CAE.
• A drum plotter is used to draw graphics on a paper that is
wrapped around a drum. It works by rotating the drum back and forth to
produce vertical motion. The pen which is mounted on a carriage is
moved across the width of the paper. Hence, the vertical movement of
the paper and the horizontal movement of the pen create the required
design under the control of the computer.
• In a flatbed plotter, the paper is spread on the flat rectangular surface of the plotter and
the pen is moved over it. Flatbed plotters are less expensive and used in many smaller
computing systems. In this type of plotter, the paper is not moved rather plotting is done
by moving an arm that moves a pen over paper.
online-pdf-no-copy.com
Module-1
Designing Efficient Programs
3.1 Programming Paradigms
A programming paradigm is a fundamental style of programming that defines how the
structure and basic elements of a computer program will be built.
The style of writing programs and the set of capabilities and limitations that a particular
programming language has depends on the programming paradigm it supports.
These paradigms, in sequence of their application, can be classified as follows:
Monolithic programming — emphasizes on finding a solution.
Procedural programming—lays stress on algorithms.
Structured programming—focuses on modules.
Object-oriented programming—emphasizes on classes and objects.
Logic-oriented programming—focuses on goals usually expressed in predicate
calculus.
Rule-oriented programming—makes use of ‘if-then-else’ rules for computation.
Constraint-oriented programming—utilizes invariant relationships to solve a
problem.
1. Monolithic Programming
Monolithic programs have just one program module.
Such programming languages do not support the concept of subroutines.
Therefore, all the actions required to complete a particular task are embedded within the same
application itself. This not only makes the size of the program large but also makes it difficult
to debug and maintain.
Programs written using monolithic programming languages consist of global data and
sequential code.
Sequential code is one in which all instructions are executed in the specified sequence.
In order to change the sequence of instructions, jump statements or ‘goto’ statements are
used.
The global data can be accessed and modified from any part of the program, thereby posing
a serious threat to its integrity (no security for data).
Examples are Assembly Language and BASIC.
Advantages:
The only goal is to write correct programs.
Programs are easier to write as compared to monolithic programming.
Disadvantages:
No concept of reusability.
Requires more time and effort to write programs.
Programs are difficult to maintain.
Global data is shared and therefore may get altered (mistakenly).
3. Structured Programming
Structured programming employs a top-down approach in which the overall program
structure is broken down into separate modules.
This allows the code to be loaded into memory more efficiently and also be reused in other
programs.
Modules are coded separately and once a module is written and tested individually, it is then
integrated with other modules to form the overall program.
Structured programming is based on modularization which groups related statements together
into modules.
Advantages:
The goal of structured programming is to write correct programs that are easy to understand
and change.
Modules enhance programmers productivity by allowing them to look at the big picture first
and focus on details later.
With modules, many programmers can work on a single, large program, with each working on a
different module.
A structured program takes less time to be written than other programs.
Each module has its own local data.
A structured program is easy to debug because each procedure is specialized to perform just
one task and every procedure can be checked individually for the presence of any error.
Individual procedures are easy to change as well as understand.
More emphasis is given on the code and the least importance is given to the data.
Modules or procedures written for one program can be reused in other programs as well.
Disadvantages:
Not data-centred.
Global data is shared and therefore may get inadvertently modified.
Main focus is on functions.
1. Requirements Analysis
In this phase, user’s expectations are gathered to know why the program/software has to be
built.
All the gathered requirements are analysed gathered the scope to arrive at or the objective of
the overall software product.
All the gathered requirements are documented to avoid any doubts or uncertainty regarding the
functionality of the programs.
2. Design
A plan of actions is made before the actual development process could start.
The core structure of the software/program is broken down into modules.
The solution of the program is then specified for each module in the form of algorithms,
flowcharts, or pseudocodes.
3. Implementation
Designed algorithms are converted into program code using any of the high level
languages.
The choice of language depends on the type of program like whether it is a system or an
application program.
Program codes are tested by the programmer to ensure their correctness.
While constructing the code, the development team checks whether the software is
compatible with the available hardware and other software components that were
mentioned in the Requirements Specification Document created in the first phase.
4. Testing
All the modules are tested together to ensure that the overall system works well as a whole
product.
Although individual pieces of codes are already tested by the programmers in the
implementation phase, there is always a chance for bugs to creep in the program when the
individual modules are integrated to form the overall program structure.
Software is tested using a large number of varied inputs also known as test data to ensure
that the software is working as expected by the users’ requirements that were identified in the
requirements analysis phase.
6. Maintenance
Maintenance and enhancements are ongoing activities which are done to cope with newly
discovered problems or new requirements.
Such activities may take a long time to complete as the requirement may call for addition of
new code that does not fit the original design or an extra piece of code required to fix an
unforeseen problem.
3. Repetition: Repetition, which involves executing one or more steps for a number of times, can
be implemented using constructs such as while, do-while, and for loops. These loops execute one
or more steps until some condition is true.
Example: Algorithm to print first 10 Natural numbers
Examples:
1. Write an algorithm to find the larger of two numbers.
4. Write an algorithm to print the grade obtained by a student using the following rules:
8. Write an algorithm to compute the perimeter and area of a triangle when three sides are
given.
Solution:
Step 1: Start
Step 2: Read a, b, c
Step 3: s= (a + b + c)/2
a= sqrt(s*(s-a)*(s-b)*(s-c))
p= a + b + c
Step 4: Print a, p
Step 5: Stop
3.3.2 Flowcharts
Flowchart is a graphical or symbolic representation of a process.
or
A flowchart is a “graphical or symbolic” representation of an algorithm.
It is basically used to design and document virtually complex processes to help the viewers
to visualize the logic of the process, so that they can gain a better understanding of the
process and find flaws, bottlenecks, and other less obvious features within it.
When designing a flowchart, each step in the process is depicted by a different symbol and is
associated with a short description. The symbols in the flowchart are linked together with
arrows to show the flow of logic in the process.
or
Figure 3.6. Symbols of flowchart
Advantages of Flowcharts:
They act as a guide or blueprint for the programmer to code the solution in any
programming language.
It helps programmers to understand the logic of complicated and lengthy problems.
They are very good communication tools to explain the logic of a system to all concerned.
They help to analyze the problem in a more effective manner.
Flowchart can be used to debug programs that have error(s).
Limitations of Flowcharts:
Drawing flowcharts is a laborious and time consuming activity.
Flowchart of a complex program becomes complex and clumsy.
A little bit of alteration in the solution may require complete redrawing of the flowchart.
There are no well-defined standards that limit the details that must be incorporated in a flow
chart.
Examples:
1. Draw a flowchart to add two numbers.
Solution:
2. Draw a Flowchart to display sum of first 10 natural numbers.
Solution:
Read P, T, R
SI= (P*T*R)/100
Print SI
Stop
Read r
A = 3.142*r*r
P = 2*3.142*r
Print A, P
Stop
Read l, b
A = l*b
P = 2*(l + b)
Print A, P
Stop
8. Draw the flowchart to compute the area and perimeter of a triangle when three sides are
given.
Solution:
Start
Read a, b, c
s = (a + b + c)/2
A = sqrt(s*(s-a)*(s-b)*(s-c))
P=a +b + c
Print A, P
Stop
Read n1, n1
sum=n1+n2
sub=n1-n2
mul=n1*n2
div=n1/n2
mod=n1%n2
Stop
Dr. DBIT-CSE 13
10. Draw the flowchart to compute Compound Interest.
Solution:
Start
Read P, T, R
CI= P*(1+R/100)T-P
Print CI
Stop
11. Draw the flowchart to compute the area and volume of sphere.
Solution:
Start
Read r
A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
Print A, V
Stop
12. Draw the flowchart to compute the area and volume of cube.
Solution:
Start
Read s
A= 6*s*s
V= s*s*s
Print A, V
Stop
DBIT-CSE 14
13. Draw the flowchart to convert from degrees in Fahrenheit to degrees in Celsius.
Solution:
Start
Read f
c=(5/9)*(f-32)
Print c
Stop
3.3.3 Pseudocode
Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language.
or
“Pseudo code is nothing but a series of steps to solve a given problem written using a mixture
of English language and C like language.”
Pseudo code consists of statements which are a combination of English and C.
It is not quite ‘C’ code but can be translated.
Pseudo code is an outline of a program that can easily be converted into programming language.
Flowcharts can be considered as graphical alternatives to pseudo codes but requires more space
on paper.
Examples:
1. Write a pseudocode for calculating the price of a product after adding the sales tax to its
original price.
Solution:
2. Write a pseudocode to calculate the weekly wages of an employee. The pay depends on
wages per hour and the number of hours worked. Moreover, if the employee has worked for
more than 30 hours, then he or she gets twice the wages per hour, for every extra hour he or
she has worked.
Solution:
15
3. Write a Pseudo code for printing the number and its square starting from 4 to 9.
Solution:
Begin
Input 4
square=4*4
Print 4,16
do the same for each of the other numbers from 5 to 9
End
DBIT-CSE 16
7. Write a Pseudo code to calculate the area and perimeter of rectangle.
Solution:
Begin
Input l, b
A=l*b
P=2*(l+b)
Print A, P
End
8. Write a Pseudo code to calculate the area and perimeter of triangle when three sides are
given.
Solution:
Begin
Input a,b,c
s= (a + b + c)/2
A=sqrt(s*(s-a)*(s-b)*(s-c))
P= a + b +c
Print A, P
End
10. Write a Pseudo code to calculate the area and perimeter of cube.
Solution:
Begin
Input s
A= 6*s*s
V= s*s*s
Print A, V
End
11. Write a Pseudo code to convert from degrees in Fahrenheit to degrees in Celsius.
Solution:
Begin
Input f
c=0.56*(f-32)
Print c
End
DBIT-CSE 17
Figure 3.7. Types of Errors
1. Run-time Errors
Run-time Errors occur when the program is being run executed.
Such errors occur when the program performs some illegal operation like:
• Dividing a number by zero.
• Opening a file that already exists.
• Lack of free memory space.
• Finding square or logarithm of negative numbers.
Run-time errors may terminate program execution, so the code must be written in such a way
that it handles all sorts of unexpected errors rather terminating it unexpectedly.
This ability to continue operation of a program despite of run-time errors is called
robustness.
2. Compile-time Errors
Compile-time Errors occur at the time of compilation of the program.
Such errors can be further classified as follows:
(i) Syntax Errors: Syntax error is generated when rules of C programming language are violated.
For example, if we write int a: then a syntax error will occur since the correct statement should be
int a;
(ii) Semantic Errors: Semantic errors are those errors which may comply with rules of the
programming language but are not meaningful to the compiler.
For example, if we write, a * b = c; it does not seem correct. Rather, if written like c = a * b would
have been more meaningful.
3. Logical Errors
Logical Errors are errors in the program code that result in unexpected and undesirable
output which is obviously not correct.
Such errors are not detected by the compiler, and programmers must check their code line by
line or use a debugger to locate and rectify the errors.
Logical errors occur due to incorrect statements.
For example, if you meant to perform c = a + b; and by mistake you typed c = a * b; then though
this statement is syntactically correct it is logically wrong.
4. Linker Errors
Linker Errors occur when the linker is not able to find the function definition for a given
prototype.
For example, if you write clrscr(); but do not include conio.h then a linker error will be shown.
3.5 Testing and Debugging Approaches
Testing is an activity that is performed to verify correct behavior of a program.
It is specifically carried out with an intent to find errors.
• Unit testing is applied only on a single unit or module to ensure whether it exhibits the
expected behavior.
• Integration Tests are a logical extension of unit tests. In this test, two units that have
already been tested are combined into a component and the interface between them is tested.
This process is repeated until all the modules are tested together. The main focus of
integration testing is to identify errors that occur when the units are combined.
• System testing checks the entire system. For example, if our program code consists of
three modules then each of the module is tested individually using unit tests and then system
test is applied to test this entire system as one system.
Debugging Approaches
Debugging is an activity that includes execution testing and code correction.
It is done to locate errors in the program code.
Once located, errors are then isolated and fixed to produce an error-free code.
Different approaches applied for debugging a code includes:
• Brute-Force Method: In this technique, a printout of CPU registers and relevant
memory locations is taken, studied, and documented. It is the least efficient way of
debugging a program and is generally done when all the other methods fail.
• Backtracking Method: works by locating the first symptom of error and then trace
backward across the entire source code until the real cause of error is detected. However,
the main drawback of this approach is that with increase in number of source code lines,
the possible backward paths become too large to manage.
• Cause Elimination: lists all possible causes of an error is developed. Then relevant tests
are carried out to eliminate each of them. If some tests indicate that a particular cause may
be responsible for an error then the data are refined to isolate the error.
Module-1
Introduction to C
4.1 Introduction
C is a high-level programming language.
The programming language C was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories to be used by the UNIX operating system.
It was named C because many of its features were derived from an earlier language called B.
Although C was designed for implementing system software, it was later on widely used for
developing portable application software.
C is one of the most popular programming languages.
It is being used on several different software platforms.
In a nutshell, there are a few computer architectures for which a C compiler does not exist.
It is a good idea to learn C because few other programming languages such as C++ and Java are
also based on C which means you will be able to learn them more easily in the future.
4.2 Characteristics of C
C is a robust language whose rich set of built-in functions and operators can be used to write
complex programs. The C compiler combines the features of assembly languages and high-level
DBIT-CSE 1
languages, which makes it best suited for writing system software as well as business packages.
Some basic characteristics of C language that define the language and have led to its popularity as
a programming language are listed below:
C is a high-level programming language, which enables the programmer to concentrate on the
problem at hand and not worry about the machine code on which the program would be run.
Small size: C has only 32 keywords. This makes it relatively easy to learn as compared to other
languages.
C makes extensive use of function calls.
C is well suited for structured programming. In this programming approach, C enables users
to think of a problem in terms of functions/modules where the collection of all the modules
makes up a complete program. This feature facilitates ease in program debugging, testing, and
maintenance.
Unlike PASCAL it supports loose typing (as a character can be treated as an integer and vice
versa).
Structured language as the code can be organized as a collection of one or more functions
Stable language: ANSI C was created in 1983 and since then it has not been revised.
Quick language as a well written C program is likely to be as quick as or quicker than a
program written in any other language.
Facilitates low-level programming.
Core language: C is a core language as many other programming languages (like C++, Java,
Perl, etc) are based on C.
C is a portable language, i.e., a C program written one computer can be run on another
compute with little or no modification.
C is an extensible language as it enables the user his own functions to the C library.
C is often treated as the second best language for any given programming task.
4.3 Uses of C
C is a very simple language that is widely used by software professionals around the globe. The
uses of C language can be summarized as follows:
C is a very simple language that is widely used by software professionals around the globe.
C is primarily used for system programming. The portability, efficiency, the ability to access
specific hardware addresses and low runtime.
The compiler, libraries and interpreters of other programming languages are often
implemented in C.
DBIT-CSE 2
For portability and convenience reasons, C is sometimes used as an intermediate language for
implementation of other languages. Major parts of popular operating systems like windows,
UNIX, Linux are still written in C.
C is widely used to implement end-user applications.
Mobile devices like cellular phones and palmtops consisting of microprocessor, operating
system and some applications are written in C.
Common consumer devices like microwave ovens, washing machines and digital cameras are
consisting of many programs which are written in C language.
Several professional 3D computer games and many popular gaming frameworks have been
built using C language.
[Comments]
[Preprocessor Directives]
[Global Declarations]
[Function Declarations]
[Function Definitions]
main()
{
[Declaration Section]
[Executable Section]
}
1. Comments
At the beginning of each program is a comment with a short description of the problem to
be solved.
We can use the comments anywhere in the program.
The comments section is optional.
Ex: 1. /* Program1: To find the sum of two numbers*/
2. // Program2: To calculate the area and perimeter of circle
The symbol /* and ends with */ represents the multiline comment.
The symbol // can also be used for representing single line comment.
2. Preprocessor directives
The preprocessor statements start with # symbol.
These statements instruct the compiler to include some of the files in the beginning of the
program.
Ex: #include<stdio.h>
#include<math.h>
are the files that the compiler includes in the beginning of the program.
The line containing #include<stdio.h> tells the compiler to allow our program to perform
standard input and output ‘stdio’ operations.
DBIT-CSE 3
The ‘#include’ directive tells the compiler that we will be using parts of the standard
function library.
Information about these functions is contained in a series of ‘header files’ (stdio.h).
.h says this file is a header file.
The pointed brackets < and > tell the compiler the exact location of this header file.
Using the preprocessor directives the user can define the constants also.
Ex: #define PI 3.142
3. Global Declarations
The variables that are declared above (before) the main program are called global variables.
The global variables can be accessed anywhere in the main program and in all the other
functions.
7. Declaration section
The variables that are used inside the function should be declared in the declaration
section.
For example, consider the declaration shown below:
int sum=0;
int a;
float b;
Here, the variable sum is declared as an integer variable and it is initialized to zero. The variable
a is declared as an integer variable whereas the variable b is declared as a floating point
variable.
8. Executable section
They represent the instructions given to the computer to perform a specific task.
DBIT-CSE 4
The instructions can be input/output statements, expressions to be evaluated, simple
assignment statements, control statements such as if statement, for statement etc.
Each executable statement ends with “;”.
2. Header Files
They have an extension '.h'.
They contain the C function declarations and macro definitions that are shared between
various source files.
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.
DBIT-CSE 5
Standard header files
C provides us with some standard header files which are available easily.
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.
3. 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.
4. 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.
DBIT-CSE 7
The compiler ignores the comments when forming the object file means that the comments
are non-executable statements.
C supports two types of comments.
// is used to comment a single statement. This is known as a line comment. A line comment
can be placed anywhere on the line and it does not require to be specifically ended as the end of
the line automatically ends the line.
/* is used to comment multiple statements. A /* is ended with */ and all statements that lie
within these characters are commented. This type of comment is known as block comment.
4.8 C Tokens
Tokens are the basic building blocks in C language.
A token is the smallest individual unit in a C program.
This means that a program is constructed using a combination of these tokens.
There are six main types of tokens in C as shown below:
1. Keywords:
Keywords are the tokens which have predefined meaning in C language, whose meaning
cannot be changed by the user.
All keywords are basically a sequence of characters that have a fixed meaning.
They are also called reserved words.
C Keywords are case sensitive. Therefore all C keywords must be written in small letters.
int, float, if, while, void etc are valid keywords.
Int, Float, IF, VOID etc are invalid keywords. (They are written using capital letters).
List of keywords:
There are total 32 keywords in C language as shown below.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
DBIT-CSE 8
2. Variables: A variable is a data item whose value changes during the execution of program.
Ex: int a,b,sum;
3. Constants: A constant is a data item which will not change during the execution of a
program.
Ex: #define PI 3.142
4. Strings: String is an array of characters and terminated by NULL character which is denoted by
‘\0’.
Ex: char name[21];
5. Operators: Operator is a symbol (or token) that specifies the operation to be performed on
various types of data.
Ex: Arithmetic operators (+,-,*,/), Relational operators (&&,||,!), Logical operators ( >,>=,<,<=)
and Assignment operator (=) etc.
6. Special characters: [ ], { }, ( ) etc. used in the program to execute the code correctly and helps
to write a complex codes by special symbols.
DBIT-CSE 9
Table 4.1: Escape sequences
4.10 Identifiers
Identifiers help us to identify data and other objects in the program.
Identifiers are basically the names given to program elements such as variables, arrays, and
functions.
Identifiers may consist of sequence of letters, numerals, or underscores.
DBIT-CSE 10
4.11 Basic Data types in C and Sizes
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.
The data types that can be manipulated by machine instructions are called ‘basic or primitive
data types’.
i. int:
An int is a keyword which is used for defining integers in C language.
Using int the programmer can inform the compiler that the data associated with this
should be treated as integer.
Using ‘int’ compiler determines the size of the data (2 bytes) and reserve space in memory
to store the data.
Integer data types namely:
1. short int 2. int 3.long int
Type Size
short int 2 bytes
int 2 bytes
long int 4 bytes
Ex: int a,b,c;
ii. float:
A float is a keyword which is used to define floating point numbers in C language.
The programmer can inform the compiler that the data associated with this keyword
should be treated as floating point number.
The default precision of floating point number is 6 digits after dot(.).
Size of float
16-bit Machine 4 bytes
32-bit Machine 8 bytes
iii. double:
It is a keyword which is used to define long floating point numbers in C language.
The default precision of floating point number is 14 digits after dot(.).
Size of double
16-bit Machine 8 bytes
32-bit Machine 16 bytes
Ex: double p,q,r;
DBIT-CSE 11
iv. char:
It is a keyword which is used to define single character or a sequence of characters called
String in C language.
Using this keyword, the compiler determines the size of the data and reserve space in
memory to store the data.
Each character stored in the memory is associated with a unique value called an ASCII
(American Standards Code for Information Interchange).
Size of char Range of Unsigned char Range of Signed char
16/32-bit Machine 1 byte 0 to 255 -128 to +127
Ex: char ch; // ch variable stores a single character Ex: ch= ‘a’;
char s[20]; // s variable stores a string(group of characters) Ex: s= “jitdvg”;
v. void:
It is an empty data type, since no value is associated with this data type.
It does not occupy any space in the memory.
Size of void Range
16/32-bit Machine 0 No value
}
It is primarily used in three cases:
To specify the return type of a function (when the function returns no value)
To specify the parameters of the function (when the function accepts no arguments from the
caller)
To create generic pointers.
4.12 Constants
A constant is a data item which will not change during the execution of a program.
or
Constants are identifiers whose values do not change.
While values of variables can be changed at any time, values of constants can never be changed.
Constants are used to define fixed values like mathematical constant pi or the charge on an
electron so that their value does not get changed in the program even by mistake.
C allows the programmer to specify constants of integer type, floating point type, character
type, and string type.
The constants cannot be modified in the program.
DBIT-CSE 12
4.12.1 Types of Constants
1. Integer Constants
A constant of integer type consists of a sequence of digits.
For example, 1, 34, 567, 8907 are valid integer constants.
Integer literals can be expressed in decimal, octal or hexadecimal notation.
By default an integer is expressed in decimal notation. Decimal integers consists of a set of
digits 0 through 9, preceded with an optional + or – sign. Example: 123, -123, +123, and 0.
An integer constant preceded by a zero (0) is an octal number. Octal integers consist of a set
of digits, 0 through 7. Example: 012, 0, 01234.
An integer constant is expressed in hexadecimal notation if it is preceded with 0x or 0X.
Hexadecimal numbers contain digits from 0-9 and letters A through F, which represent
numbers 10 through 15. Example: Ox12, Ox7F, OxABCD, Ox1A3B.
3. Character Constants
A character constant consists of a single character enclosed in single quotes.
For example, ‘a’ and ‘@’ are character constants.
In computers, characters are stored using machines character set using ASCII codes. All escape
sequences mentioned in Table 4.1 are also character constants.
DBIT-CSE 13
4. String Constants
A string constant is in double quotes.
So “a” is not the same as ‘a’.
The characters comprising the string constant are stored in successive memory locations.
When a string constant is encountered in a C program, the compiler records the address of the
first character and appends a null character (‘\0’) to the string to mark the end of the string.
Thus, length of a string constant is equal to number of characters in the string plus 1 (for the
null character). Therefore, the length of string literal “hello” is 6.
4.13 Variable
A variable is a name given to a memory location within the computer that can hold one
value at a time.
OR
A variable is a data item whose value changes during the execution of program.
Every variable should be associated with type, size and value.
Whenever a new value is placed into a variable, it replaces the previous value.
DBIT-CSE 14
The case of alphabetic characters that form the variable name is significant. For example,
‘FIRST’ is different from ‘first’ and ‘First’.
Variables must begin with a letter or an underscore.
Variables can be of any reasonable length. They should not contain more than 31 characters.
They can actually be longer than 31, but the compiler looks at only the first 31 characters of the
name.
Ex: Classify the following into valid and invalid variable names in C. If invalid give reasons:
1. Numeric Variables
Numeric variables can be used to store either integer values or floating point values.
While an integer value is a whole number without a fraction part or decimal point, a
floating point value can have a decimal point.
Numeric variables may also be associated with modifiers, such as short, long, signed, and
unsigned. The difference between signed and unsigned numeric variables is that signed
variables can be either negative or positive but unsigned variables can only be positive.
When we do not specify the signed/ unsigned modifier, C language automatically takes it as a
signed variable. To declare an unsigned variable, the unsigned modifier must be explicitly
added during the declaration of the variable.
2. Character Variables
Character variables are just single characters enclosed within single quotes. These characters
could be any character from the ASCII character set-letters (‘a’, ‘A’), numerals ( ‘2’), or special
characters (‘&’).
A number that is given in single quotes is not the same as a number without them. This is
because 2 is treated as an integer value, but ‘2’ is considered character not an integer.
DBIT-CSE 15
4.13.3 Declaring/Defining a Variable
Each variable to be used in the program must be declared.
‘Declaration’ tells the computer which storage locations or variables to use in the program.
It is a method of informing the compiler to reserve the memory space for the program
data based on the type of variables.
To declare a variable, specify the data type of the variable followed by its name.
The data type indicates the kind of values that the variable will store.
Syntax: datatype v ,v ,…….,v ;
1 2 n
Where, datatype: is the type of the data to be stored in memory location. (int,float,char,double)
var_name: name of a variable
= is assignment operator
data: is the value to be stored in memory associated with variable var_name.
Ex: int a=10;
Formatting Input/Output
C language supports two formatting functions printf and scanf.
printf is used to convert data stored in the program into a text stream for output to the
monitor and scanf is used to convert the text stream coming from the keyboard to data
values and stores them in program variables.
DBIT-CSE 16
1. printf()
The printf() function (stands for print formatting), is used to display information required by
the user and also prints the values of variables.
For this, the printf() function takes data values, converts them to a text stream using
formatting specifications in the control string and passes the resulting text stream to
standard output.
Each data value to be formatted in the text stream is described using a separate conversion
specification in the control string.
The specification in the control string describes data value’s type, size, specific format.
Flags
Flag is an optional argument which specifies output justifications such as numerical sign,
trailing zeros or octal, decimal or hexadecimal prefixes.
Types of flags:
- : Left justify
+ : Display data with numeric sign
# : Provide additional specifier o,O,X,0,0x
0 : Left-padding with zeros
Width
It is an optional argument which specifies minimum number of positions in the output.
Precision
Precision is an optional argument which specifies the maximum number of characters to print.
DBIT-CSE 17
Therefore, a conversion specification %7.3f means print a floating point value of maximum 7
digits where 3 digits are allotted for the digits after the decimal point.
Length modifiers
Table 4.2 Length modifiers for printf()
Type specifiers
Type specifiers are used to define the type and interpretation of the value of the corresponding
argument.
DBIT-CSE 18
If there are variables or expressions to be printed, commas are used to separate them from the
control string and each other, once comma is used as separator, it is not necessary to add blank
spaces (not allowed).
2. scanf()
The scanf() function stands for scan formatting and is used to read formatted data from the
keyboard.
The scanf() function takes a text stream from the keyboard, extracts and formats the data
from the stream according to a format control string and then stores the data in a
specified program variables.
Syntax of the scanf() function:
scanf ( “control string”, arg1, arg2, arg3,….. argn);
Control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by arg1, arg2, …, argn,i.e., arguments are
actually the variable addresses where each piece of data is to be stored.
Prototype of the control string can be given as:
%[*][width][modifier] type
Here the * is an optional argument which indicates that data should be read from the stream, but
ignored (not stored in memory location).
Width
This is an optional argument that specifies the maximum number of characters to be read.
Fewer characters are read if scanf() encounters a white space and will stop processing further.
Modifier
It is an optional argument that can be h, l, or L for the data pointed by corresponding additional
arguments.
Modifier h is used for short int or unsigned short int, l is used for long int, unsigned long int, or
double values. Finally, L is used for long double data values.
Type
It specifies the type of data that has to be read.
The type specifiers for scanf( ) function are same as that of printf ( ) function.
The scanf function ignores any blank spaces, tabs and newlines entered by the user.
The address of the variable is denoted by an ‘&’ sign followed by the name of the variable.
DBIT-CSE 19
Rule 2: Every variable that has to be processed must have a conversion specification associated
with it. Therefore, following scanf statement will generate an error as num3 has no conversion
specification associated with it.
scanf(“ %d %d”, &num1, &num2, &num3);
Rule 3: There must be a variable address for each conversion specification. Therefore following
scanf will generate an error as no variable address is given for the third conversion specification.
scanf(%d %d %d”, &num1, &num2);
Rule 4: An error will be generated if the format string is ended with the white space character.
Rule 5: The data entered by the user must match the character specified in the control string,
otherwise, an error will be generated and scanf will stop its processing.
For example, consider the following scanf of statement
scanf(“%d / %d”, &num1, &num2);
Here the slash in the constant string is neither a white space character nor a part of the
conversion specification, so the users must enter data of the form 21/46.
Rule 7: Any unread data value will be considered as a part of data input in the next call to the
scanf.
Rule 8: When the field width specifier is used, it should be large enough to contain the input data
size.
Examples of printf/scanf:
1. Code to input values in variables of different data types:
int num;
scanf(“%d”,&num);
float salary;
scanf(“%f”, &salary);
char ch;
scanf(“%c”,&ch);
char str[10];
scanf(“%s”, str);
Dr. DBIT-CSE 20
soprotection.com