Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Module 1

Uploaded by

COC BADSHA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module 1

Uploaded by

COC BADSHA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

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

1.2 Characteristics of Computers

Figure 1.1. Characteristics of computers


1. Speed
 Computers can perform millions of operations per second.
 The speed of computers is usually given in nanoseconds and picoseconds, where 1 nanosecond
= 1 × 10 −9 seconds and 1 picosecond = 1 × 10 −12 seconds.

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

1.3 Stored Program Concept


 All digital computers are based on the principle of stored program concept.
 The following are the key characteristic features of this concept:
 Before any data is processed, instructions are read into memory.
 Instructions are stored in the computer’s memory for execution.
 Instructions are stored in binary form (using binary numbers—only 0s and 1s).
 Processing starts with the first instruction in the program, which is copied into a control
unit circuit. The control unit executes the instructions.
 Instructions written by the users are performed sequentially until there is a break in
the current flow.
 Input/Output and processing operations are performed simultaneously. While data is being
read/written, the central processing unit (CPU) executes another program in the memory that
is ready for execution.

1.3.1 Types of Stored Program Computers


1. Shared Memory Architecture
 A computer with a Von Neumann architecture stores data and instructions in the same memory.
 There is a serial machine in which data and instructions are selected one at a time.
 Data and instructions are transferred to and from memory through a shared data bus. Since there
is a single bus to carry data and instructions, process execution becomes slower.

2. Distributed Memory Architecture


 Later Harvard University proposed a stored program concept in which there was a separate
memory to store data and instructions.
 Instructions are selected serially from the instruction memory and executed in the processor.
When an instruction needs data, it is selected from the data memory. Since there are separate
memories, execution becomes faster.

2
Figure 1.2. Von Neumann architecture (a) Shared memory for instructions and data (b)
Separate memories for instructions and data

1.4 History of Computers


 Timeline of Developments
300 BC: The abacus was an early aid for mathematical computations and was designed to aid
human’s memory while performing calculations.
1822: Charles Babbage designed a steam-driven calculating machine that could compute tables
of numbers.
1890: a punched card system was designed for the calculations.
1936: Turing machine were designed, which were capable of computing anything that is
computable.
1941: It was the first time a computer could store information in its main memory.
1943–1944:
 Electronic Numerical Integrator and Calculator (ENIAC) were built.
 It is considered as the grandfather of digital computers.
 It filled a 20 × 40 feet room and had 18,000 vacuum tubes.
1946: UNIVAC was designed, which was the first commercial computer for business and
government applications.
1947: vacuum tubes in computers were replaced by transistors.
1953: Developed the first computer language COBOL.
1954: The FORTRAN programming language was developed.
1958: invented integrated circuit, which is commonly known as the computer chip.
1964: developed a prototype of the modern computer, with a mouse and a graphical user
interface (GUI). This was a remarkable achievement as it shifted computers from a specialized
machine for scientists and mathematicians to general public.
1969: Unix operating system was developed at Bell Labs. It was written in the C programming
language and was designed to be portable across multiple platforms.
1970: DRAM chip was introduced by Intel.
1971: invented the floppy disk which allowed data to be shared among computers.
1973: developed Ethernet for connecting multiple computers and other hardware.
1974–1977: Personal computers started becoming popular.
1975: Paul Allen and Bill Gates started writing software using the new BASIC language. They
both formed their own software company, Microsoft.
1976: Apple Computers and developed Apple I, the first computer with a single-circuit board.

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.

1.4.1 Generations of Computers


1. First Generation (1942–1955)
Hardware Technology
First generation computers were manufactured using thousands of vacuum tubes.

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

Used for Scientific applications

Examples ENIAC, EDVAC, EDSAC, UNIVAC I, IBM 701

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

2. Second Generation (1955–1964)


Hardware Technology
 Second generation computers were manufactured using transistors.
 Transistors were reliable, powerful, cheaper, smaller, and cooler than vacuum tubes.

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

Used for Scientific and commercial applications

Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC

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

3. Third Generation (1964–1975)


Hardware Technology
 Third generation computers were manufactured using integrated chips (ICs).
 ICs consist of several components such as transistors, capacitors, and resistors on a
single chip to avoid wired interconnections between components.
 These computers used SSI and MSI technology. Minicomputers came into existence.

Memory
 Larger magnetic core memory was used as primary memory; larger capacity magnetic
tapes and magnetic disks were used to store data and instructions.

Used for Scientific, commercial, and interactive online applications.

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

4. Fourth Generation (1975–1989)


Hardware Technology
 Fourth generation computers were manufactured using ICs with LSI (Large Scale
Integrated) and later with VLSI technology (Very Large Scale Integration).
 Microcomputers came into existence.
 Use of personal computers became widespread.
 High speed computer networks in the form of LANs, WANs, and MANs started
growing.

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

Used for Scientific, commercial, interactive online, and network applications.

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

5. Fifth Generation (1989–Present)


Hardware Technology
 Fifth generation computers are manufactured using ICs with ULSI (Ultra Large Scale
Integrated) technology.
 The use of Internet became widespread and very powerful mainframes, desktops,
portable laptops, and smartphones are being used commonly.
 Supercomputers use parallel processing techniques.

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

1.5 Classification of Computers


 Computers can be broadly classified into four categories based on their speed, amount of data
that they can process, and price:
 Supercomputers
 Mainframe computers
 Minicomputers
 Microcomputers

Figure 1.3. Classification of computers


1. Supercomputers
 The supercomputer is the fastest, most powerful, and most expensive computer.
 Process large amounts of data and to solve complex scientific problems.
 Supercomputers use parallel processing technology and can perform more than one trillion
calculations in a second.
 A single supercomputer can support thousands of users at the same time.
 Such computers are mainly used for weather forecasting, nuclear energy research, aircraft
design, automotive design, online banking, controlling industrial units, etc.
2. Mainframe Computers
 Mainframe computers are large-scale computers (but smaller than supercomputers).
 These are very expensive and need a very large clean room with air conditioning, thereby
making them very costly to deploy.
 Support multiple processors.
 The two types of terminals that can be used with mainframe systems are as follows:
1. Dumb Terminals
 Dumb terminals consist of only a monitor and a keyboard (or mouse). They do not have their
own CPU and memory and use the mainframe system’s CPU and storage devices.
2. Intelligent Terminals:
 Intelligent terminals have their own processor and thus can perform some processing
operations.
 Usually, PCs are used as intelligent terminals to facilitate data access and other services from
the mainframe system.
 Mainframe computers are typically used as servers on the World Wide Web.
 They are also used in organizations such as banks, airline companies, and universities, where a
large number of users frequently access the data stored in their databases.

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.

1.6 Applications of Computers


1. Word processing
 Word processing software enables users to read and write documents.
 Users can also add images, tables, and graphs for illustrating a concept.
 The software automatically corrects spelling mistakes and includes copy–paste features.

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

3. Digital video or audio composition


 Computers make audio or video composition and editing very simple.
 Graphics engineers use computers for developing short or full-length films and creating 3-D
models and special effects in science fiction and action movies.

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.

8. Geographic Information System and Remote Sensing


 A geographic information system (GIS) is a computer based tool for mapping and analysing
earth.
 It integrates database operations and statistical analysis to be used with maps.
 Remote sensing is a sub-field of geography, which can be applied in the following areas to
collect data of dangerous or inaccessible areas for the following: Monitoring deforestation,
Studying features of glaciers, etc.

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

10. Legal System


 Lawyers use computers to look through millions of individual cases and find whether similar or
parallel cases have been approved, denied, criticized, or overruled in the past.
11. Retail Business
 Computers are used in retail shops to enter orders, calculate costs, and print receipts.

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

13. Travel and Tourism


 Computers are used to prepare tickets, monitor the train’s or airplane’s route, and guide the
plane to a safe landing.

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

16. Industry and Engineering


 Computers are found in all kinds of industries, such as thermal power plants, oil refineries, and
chemical industries, for process control, computer-aided designing (CAD), and computer-aided
manufacturing (CAM).

17. Robotics
 Robots are computer-controlled machines mainly used in the manufacturing process in extreme
conditions where humans cannot work.

18. Decision Support Systems


 Computers help managers to analyse their organization’s data to understand the present scenario
of their business, view the trends in the market, and predict the future of their products.

19. Expert Systems


 Expert systems are used to automate the decision-making process in a specific area, such as
analysing the credit histories for loan approval and diagnosing a patient’s condition for
prescribing an appropriate treatment.

1.7 Basic Organization of a Computer


 A computer is an electronic device that performs five major operations:
 Accepting data or instructions (input)
 Storing data
 Processing data
 Displaying results (output)
 Controlling and coordinating all operations inside a computer.

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.

Categories of input devices

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.

Numeric keys: These include a set of keys,


arranged in the same configuration found on
calculators to speed up data entry of numbers.

Function keys: These are used by applications


and operating system to input specific commands. They are often placed on the top of the
keyboard in a single row.

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.

Advantages: Easy to use and inexpensive.


Disadvantages:
 Keyboard cannot be used to draw figures.
 The process of moving the cursor to some other position is very slow.
 Mouse and other pointing devices are more apt for this purpose

2.1.2 Pointing Devices


1. MOUSE
The mouse is the key input device to be used in a graphical user
interface (GUI). The users can use mouse to handle the pointer easily
on the screen to perform various functions like opening a program or
file.
With mouse, the users no longer need to memorize commands, which
was earlier a necessity when working with text-based command line
environment such as MS-DOS.
Advantages:
 Easy to use; Cheap; Can be used to quickly place the cursor anywhere on the screen;
 Helps to quickly and easily draw figures;
 Point and click capabilities makes it unnecessary to remember certain commands
Disadvantages:
 Needs extra desk space to be placed and moved easily.
 The ball in the mechanical mouse must be cleaned to remove dust from it

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.1.3 Handheld Devices


 A handheld device is a pocket-sized computing device with a display screen and touch input
and/or miniature keyboard.
1. JOYSTICK:
It is a cursor control device widely used in computer games and CAD/CAM
applications. It consists of a hand-held lever that pivots on one end and
transmits its coordinates to a whose position can also be read by the computer.

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.1.4 Optical Devices


 Optical devices, also known as data-scanning devices, use light as a source of input for
detecting or recognizing different objects such as characters, marks, codes and images. These
devices convert these objects into digital data and send it to the computer for further processing.
1. BARCODE READERS:
A barcode reader (or price scanner or point-of-sale scanner) is a hand-held
input device which is used to capture and read information stored in a
barcode. A barcode reader consists of a scanner, a decoder, and a cable used
to connect the reader with a computer.
The barcode reader merely captures and translates the barcode into numbers
and/or letters. To make use of the information captured it must be connected
to a computer for further processing. For this purpose, the barcode reader is
connected to a computer through a serial port, keyboard port, or an interface device called a
wedge.
Advantages:
Cheap
Portable
Used to read data stored in bar codes
Handy and easy to use

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.

3. Optical Character Recognition (OCR):


OCR is the process of converting printed materials into text or word processing files that can be
easily edited and stored. The steps involved in OCR include:
 Scanning of the text character-by-character.
 Analyzing the scanned-in image to translate the character image into character codes
(e.g. ASCII).
Advantages:
 Printed documents can be converted into text files.
 Advanced OCR can recognize handwritten text and convert them into computer readable
text files.

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.

4. OPTICAL MARK RECOGNITION:


OMR is the process of electronically extracting data from marked fields,
such as checkboxes and fill-infields, on printed forms. The optical mark
reader is fed with an OMR sheet to detect the presence of a mark by
measuring reflected light levels. The OM reader interprets this pattern
marks and spaces and stores the interpreted data in computer for storage,
analysis and reporting.
The error rate for OMR technology is less than 1%.
It is used for applications in which large numbers of hand-filled forms have to be quickly
processed with great accuracy, such as surveys, reply cards, questionnaires, ballots or sheets for
multiple choice questions.
Advantages:
 Optical mark readers works with a very fast speed. They can read up to 9,000 forms per
hour .
 They are accurate machines with error rates of just 1% .

5. MAGNETIC INK CHARACTER READER (MICR):


MICR is used to verify the legitimacy or originality of paper documents,
especially checks.
MICR consists of magnetic ink printed characters which can be recognized by
high speed magnetic recognition devices.
The printed characters provides important information (like check number,
bank routing number, checking account number and in some cases the amount
of the check) for processing to the receiving party.
MICR is widely used to enhance security, speed up the sorting of documents and minimize the
exposure to check fraud.

2.1.5 Audiovisual Input Devices


 Audio devices are used to either capture or create sound. They enable computers to accept
music, speech or sound affects for recording and/or editing. Microphone and CD player are
examples of two widely used audio input devices. Microphone feeds audio input to the
computer. The computer must have a sound card to convert analog signals generated through
microphone into digital data so that it can be stored in the computer. When the user wants to
hear the pre-recorded audio input, the sound card converts the digital data into analog signals
and sends it to the speakers.
Advantages:
 Audio devices can be used by people who have visual problems.
 It is best used in situations where users want to avoid i/p through keyboard or mouse.
Disadvantages:
 Audio input devices are not suitable in noisy places.
 With audio input devices it is difficult to clearly distinguish between two similar
sounding words like “sea” and “see”.

Video Input Devices:


Video input devices are used to capture video from the outside world into the computer.
Digital camera is used to capture images or videos. It digitizes the image or
video and stores them on a memory card. The data can then be transferred to the
computer using a cable which connects computer to the digital camera.

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.

2.1.6 Output Devices


 Any device that outputs/gives information from a computer is called an output device.
Output devices are electromechanical devices which accept digital data from the computer and
converts them into human understandable language.

SOFT COPY DEVICES:


Soft copy output devices are those output devices which produce an electronic version of an
output. For example, a file which is stored on hard disk, CD, pen drive, etc and is displayed on
the computer screen (monitor).
Features of a soft copy output include:
• The output can be viewed only when the computer is on.
• The user can easily edit the soft copy output.
• Soft copy cannot be used by people who do not have a computer.
• Searching data in a soft copy is easy and fast.
• Electronic distribution of a soft copy is cheaper. It can be done easily and quickly.
1. MONITORS:
The Monitor is a soft copy output device used to display video and graphics information
generated by the computer through the video card.

A. CATHODE RAY TUBE MONITORS


• CRT monitors work by firing charged electrons at a phosphorus film. When electron hit
the phosphor coated screen, it glows thereby enabling the user to see the output.
• In a cathode ray tube, the "cathode" is a heated filament which is placed in a vacuum
created inside a glass "tube." The "ray" is a stream of electrons which comes out from a
heated cathode into the vacuum.
• The focusing anode focuses the stream of electrons to form a tight beam which is then
accelerated by an accelerating anode.
• This tight, high-speed beam of electrons flies through the vacuum in the tube and hits
the flat screen at the other end of the tube.
• This screen is coated with phosphor, which glows when struck by the beam, thereby
displaying the picture which the user sees on the monitor.

Schematic diagram of a Cathode Ray Tube

B. LIQUID CRYSTAL DISPLAY MONITORS


LCD monitor is a thin, flat electronic visual display that uses the light modulating properties of
liquid crystals which do not emit light directly. LCD screens are used in a wide range of
applications ranging from computer monitors, television, instrument panels, aircraft cockpit
displays, signage, to consumer devices like such as video players, gaming devices, clocks,
watches, calculators, and telephones. Liquid crystal display technology is based on blocking
light. The LCD consists of two pieces of polarizing filters (or substrates) that contain a liquid
crystal material between them. A backlight creates light which is made to pass through the first
substrate. Simultaneously, the electrical currents cause the liquid crystal molecules to align to
allow varying levels of light to pass through to the second substrate and create the colors and
images are seen on the screen.
C. PLASMA MONITORS:

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

Schematic diagram of a Plasma Monitor


2. PROJECTOR:

A projector is a device which takes an image from a video source


and projects it onto a screen or other surface. These days,
projectors are used for a wide range of applications varying from
home theater e systems to organizations for projecting information
and presentations onto screens large enough for rooms filled with
people to see.

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.

(a) Speakers (b)headphone (c)headset

HARD COPY OUTPUT DEVICES:


Hard copy output devices produces a physical form of output. For example, the content of a file
printed on a paper is a form of hard copy output.

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.

DOT MATRIX 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 PRINTER

• 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

• It is a non-impact printer that works at a very high speed and


produces high quality text and graphics.
• It uses the photocopier technology. When a document is
sent to the printer, a laser beam "draws" the document on a drum
(which is coated with a photo-conductive material) using electrical
charges.
• After the drum is charged, it is rolled in toner (a dry powder type of ink).
• The toner sticks to the charged image on the drum.
• The toner is transferred onto a piece of paper and fused to the paper with heat and
pressure.
• After the document is printed, the electrical charge is removed from the drum and the
excess toner is collected.
• While color laser printers are also available in the market but users prefer only
monochrome printers because a color laser printer is up to 10 times more expensive than
a monochrome 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.

Figure 3.1. Structure of a monolithic program


2. Procedural Programming
 In procedural languages, a program is divided into subroutines that can access global data.
 To avoid repetition of code, each subroutine performs a well-defined task.
 A subroutine that needs the service provided by another subroutine can call that subroutine.
Therefore, with ‘jump’, ‘goto’, and ‘call’ instructions, the sequence of execution of
instructions can be altered.
 Examples FORTRAN and COBOL are two popular procedural programming languages

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

Figure 3.2. Structure of a procedural program

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

Figure 3.3. Structured program

4. Object-Oriented Programming (OOP)


 The object-oriented paradigm is task-based and data-based.
 In this paradigm, all the relevant data and tasks are grouped together in entities known as
objects.
 It treats data as a critical element in the program development and restricts its flow freely
around the system.
 For example, consider a list of numbers. In the object-oriented paradigm, the list and the
associated operations are treated as one entity known as an object. In this approach, the list is
considered an object consisting of the list, along with a collection of routines for manipulating
the list.
 The striking features of OOP include the following:
• Programs are data centred.
• Programs are divided in terms of objects and not procedures.
• Functions that operate on data are tied together with the data.
• Data is hidden and not accessible by external functions.
• New data and functions can be easily added as and when required.
• Follows a bottom-up approach for problem solving.

Figure 3.4. Object-oriented paradigm


3.2 Design and Implementation of Efficient Programs
 To design and develop correct, efficient, and maintainable programs, the entire program
development process is divided into a number of phases where each phase performs a well-
defined task.
 Output of one phase provides the input for its subsequent phase.
 The phases in the software development life cycle (SDLC) process is shown in Figure 3.5.

Figure 3.5. Phases in Software Development Life Cycle (SDLC)

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

5. Software Deployment, Training and Support:


 After testing the software is deployed in the production environment.
 Software Training and Support is a crucial phase which makes the end users familiar with
how to use the software.
 Moreover, people are often resistant to change and avoid venturing into an unfamiliar area, so as
a part of the deployment phase, it has become very crucial to have training classes for the
users of the software.

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.3 Program Design Tools: Algorithms, Flowcharts, Pseudocodes


3.3.1 Algorithms
 An algorithm provides a blueprint to writing a program to solve a particular problem.
or
The algorithm is a ‘step-by-step procedure’ to be followed in solving a problem.
 It is considered to be an effective procedure for solving a problem in a finite number of steps.
 A well-defined algorithm always provides an answer, and is guaranteed to terminate.
 Algorithms are mainly used to achieve software re-use.
 A good algorithm must have the following characteristics:
• Be precise.
• Be unambiguous.
• Not even a single instruction must be repeated infinitely.
• After the algorithm gets terminated, the desired result must be obtained.

Control Structures Used In Algorithms


1. Sequence: Sequence means that each step of the algorithm is executed in the specified order.
Example: Algorithm to Add two numbers
2. Decision: Decision statements are used when the outcome of the process depends on some
condition. For example, if x=y, then print “EQUAL”. Hence, the general form of the if construct
can be given as:
if condition then process.
Example: Algorithm to test Equality of two number

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.

2. Write an algorithm to find whether a number is even or odd.


3. Write an Algorithm to Swap two numbers.

4. Write an algorithm to print the grade obtained by a student using the following rules:

5. Write an algorithm to compute the simple interest.


Solution:
Step 1: [Initialize] Start
Step 2: [Input the values of P, T, R]
Read P, T, R
Step 3: [Compute the Simple Interest]
SI= (P*T*R)/100
Step 4: [Display the Simple Interest]
Print SI
Step 5: [Finished] Stop
6. Write an algorithm to compute the area and perimeter of a circle.
Solution:
Step 1: Start
Step 2: Read r
Step 3: a= 3.142*r*r
p= 2*3.142*r
Step 4: Print a,p
Step 5: Stop

7. Write an algorithm to compute the area and perimeter of a rectangle.


Solution:
Step 1: Start
Step 2: Read l,b
Step 3: a= l*b
p= 2*(l+b)
Step 4: Print a, p
Step 5: Stop

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

9. Write an algorithm to compute the compound interest.


Solution:
Step 1: Start
Step 2: Read P, T, R
Step 3:CI= P*(1+R/100)T-P
Step 4:Print CI
Step 5: Stop

10. Write an algorithm to simulate simple calculator or to perform arithmetic operations.


Solution:
Step 1: Start
Step 2: Read n1, n2
Step 3: sum = n1 + n2
sub = n1 - n2
mul = n1 * n2
div = n1 / n2
Step 4: Print sum, sub, mul, div
Step 5: Stop
11. Write an algorithm to calculate the area and volume of sphere.
Solution:
Step 1: Start
Step 2: Read r
Step 3: A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
Step 4: Print A, V
Step 5: Stop

12. Write an algorithm to calculate the area and volume of cube.


Solution:
Step 1: Start
Step 2: Read s
Step 3: A=6*s*s
V= s*s*s
Step 4: Print A, V
Step 5: Stop

13. Write an algorithm to convert degrees in Fahrenheit to degrees in Celsius.


Solution:
Step 1: Start
Step 2: Read f
Step 3: c=(5/9)*(f-32)
Step 4: Print c
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:

3. Draw a Flowchart to calculate the salary of a wager.


Solution:

4. Draw a Flowchart to determine the largest of three numbers.


Solution:
5. Draw the flowchart to compute Simple Interest.
Solution:
Start

Read P, T, R

SI= (P*T*R)/100

Print SI

Stop

6. Draw the flowchart to compute the area and perimeter of a circle.


Solution:
Start

Read r

A = 3.142*r*r
P = 2*3.142*r

Print A, P

Stop

7. Draw the flowchart to compute the area and perimeter of a rectangle.


Solution:
Start

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

9. Draw the flowchart to simulate the simple calculator.


Solution:
Start

Read n1, n1

sum=n1+n2
sub=n1-n2
mul=n1*n2
div=n1/n2
mod=n1%n2

Print sum, sub, mul, div,mod

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

4. Write a Pseudo code to compute the Simple Interest.


Solution:
Begin
Input P, T, R
SI= (P*T*R)/100
Print SI
End

5. Write a Pseudo code to compute the Compound Interest.


Solution:
Begin
Input P, T, R
CI= P*(1+R/100)T-P
Print CI
End

6. Write a Pseudo code to calculate area and perimeter of circle.


Solution:
Begin
Input r
A=3.142*r*r
P=2*3.142*r
Print A, P
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

9. Write a Pseudo code to calculate the area and perimeter of sphere.


Solution:
Begin
Input r
A= 4*3.142*r*r
V= (4/3)*3.142*r*r*r
Print A, V
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

3.4 Types of Errors


 While writing programs, very often we get errors in our program.
 These errors if not removed will either give erroneous output or will not let the compiler to
compile the program.

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

Figure 4.1. Taxonomy of C Language

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

4.4 Basic Concepts of a C Program or Structure of a C Program


 The basic concepts of a C program can be explained by writing the structure of a C program.
 The structure of a C program is nothing but the rules that are to be followed while writing a C
program.
 The structure of a C program is shown below:

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

4. Function declarations and Definitions


 In this section the functions are declared.
 Immediately after the functions are declared, the functions can be defined.

5. The program header: main()


 Every program must have a main function.
 Always the C program begins its execution from main.

6. Body of the program


 After the header or top lines is a set of braces ({ and }) containing a series of ‘C’
statements which comprise the ‘body’- this is called the action portion of the program.
Ex: #include<stdio.h>
main()
{
/* action portion of the program*/
}
 The body of the program contains two essential parts:
1. Declaration section
2. Executable section

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 “;”.

Example: Write a C program to display “Hello World”.


#include<stdio.h>
void main()
{
printf(“Hello World”);
}

4.5 Files used in a C Program


A C program uses four types of files as follows:

Figure 4.2. Files in a C program


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

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

DBIT-CSE 5
Standard header files
 C provides us with some standard header files which are available easily.

Common standard header files are:


 string.h – used for handling string functions.
 string.h – used for handling string functions.
 stdlib.h – used for some miscellaneous functions.
 stdio.h – used for giving standardized input and output.
 math.h – used for mathematical functions.
 alloc.h – used for dynamic memory allocation.
 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.

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

4.6 Compiling and Executing C Programs


 C is a compiled language.
 The programming process starts with creating a source file that consists of the statements of the
program written in C language. This source file usually contains ASCII characters and can be
produced with a text editor, such as Windows notepad, or in an Integrated Design Environment.
 The source file is then processed by a special program called a compiler.
 The compiler translates the source code into an object code.
 The object code contains the machine instructions for the CPU, and calls to the operating
system API (Application Programming Interface).
 However, even the object file is not an executable file. Therefore, in the next step, the object
file is processed with another special program called a linker.
 While there is a different compiler for every individual language, the same linker is used for
object files regardless of the original language in which the new program was written. The
output of the linker is an executable or runnable file. The process is shown in Figure 4.3.

Figure 4.3. Overview of compilation and execution process


DBIT-CSE 6
 In C language programs, there are two kinds of source files. In addition to the main (.c) source
file, which contains executable statements there are also header (.h) source files.
 Every C program uses standard header files, which are written as part of the source code for
modular C programs.
 The compilation process shown in Figure 4.4 is done in two steps. In the first step, the
preprocessor program reads the source file as text, and produces another text file as output.
The output of the preprocessor is a text file which does not contain any preprocessor statements.
This file is ready to be processed by the compiler.

Figure 4.4. Preprocessing before compilation


 The linker combines the object file with library routines (supplied with the compiler) to
produce the final executable file.
 In modular programming, the source code is divided into two or more source files. All these
source files are compiled separately thereby producing multiple object files. These object files
are combined by the linker to produce an executable file (Figure 4.5).

Figure 4.5. Modular programming-the complete compilation and execution process

4.7 Using Comments


 Many a time the meaning or the purpose of the file code is not clear to the reader.
 Therefore it is a good programming practice to place some comments in the code to help
the reader understand the code clearly.
 Comments are just a way of explaining what a program does.
 It is merely an internal program documentation.

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.

4.9 CHARACTER SET IN C


 Like in natural languages, computer languages also use a character set that defines the
fundamental units used to represent information.
 In C, a character means any letter from English alphabet, a digit or a special symbol used to
represent information.
 These characters when combined together form tokens that act as basic building blocks of a C
program.
 The character set of C can therefore be given as:
a. English alphabet: Include both lower case (a z) as well as upper case (A Z) letters
b. Digits: Include numerical digits from 0 to 9
c. Special characters: Include symbols such as, % & ) < > * S / ) [ " etc.,
d. White space characters: These characters are used to print a blank space on the screen.
They are shown in Figure 4.6.

Figure 4.6. White space characters in C


e. Escape sequence: ‘\n’ is an escape sequence and represents a newline character. It is used to
print the message on a new line on the screen. Like the newline character, the other escape
sequences supported by C language are shown in Table 4.1.

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

Rules for Forming ldentifier Names


Some rules have to be followed while forming identifier names. They are as follows:
 Identifiers cannot include any special characters or punctuation marks (like #, s, ^, ?, ., etc.)
except the underscore ‘_’.
 There cannot be two successive underscores.
 Keywords cannot be used as identifiers.
 The case of alphabetic characters that form the identifier name is significant. For example,
‘FIRST’ is different from ‘first’ and ‘First’.
 Identifiers must begin with a letter or an underscore. However, use of underscore as the first
character must be avoided because several compiler-defined identifiers in the standard C library
have underscore as their first character.
 Identifiers 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.

Examples of valid identifiers include:


roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code, DeptCode, RollNo,
EMP_NO

Examples of invalid identifiers include:


23 student, %marks, @name, #emp_number, basic.pay, -HRA, (DA), &dept_code, auto

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

Ex: float x,y,z;

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

Ex: void main( )


{

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

2. Floating Point Constants


 A floating point constant consists of an integer part, a decimal point, a fractional part, and
an exponent field containing an e or E (e means exponent) followed by an integer where the
fraction part and integer part are a sequence of digits. However, it is not necessary that every
floating point constant must contain all these parts. Some floating point numbers may have
certain parts missing. Some valid examples of floating point numbers are: 0.02, -0.23, 123.456,
+0.34 123, 0.9, -0.7, +0.8 etc.
 To make it a float type literal, you must specify it using Suffix F or f. Consider some valid
floating point literals given below. (Note that suffix L is for 1ong double.)
0.02F 0.34f 3.141592654L 0.002146 2.146E-3
 A floating point number may also be expressed in scientific notation. Therefore, the numbers
given below are valid floating point numbers:
0.5e2 14E-2 1.2e+3 2.1E-3 -5.6e-2

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.12.2 Declaring Constants


 To declare a constant, precede the normal variable declaration with “const” keyword and
assign it a value. For example,
const float pi = 3.14;
The const keyword specifies that the value of pi cannot change.
 However, another way to designate a constant is to use the pre-processor command define.
Example: #define PI 3.14159
#define service_tax 0.12
In these examples, the value of pi will never change but service tax may change. Whenever the
value of the service tax is altered, it needs to be corrected only in the define statement.
Some rules that need to be applied to a #define statement which defines a constant:
Rule 1: Constant names are usually written in capital letters to visually distinguish them from
other variable names which are normally written in lower case characters.
Rule 2: No blank spaces are permitted between the # symbol and define keyword.
Rule 3: Blank space must be used between #define and constant name and between constant
name and constant value.
Rule 4: #define is a pre-processor compiler directive and not a statement. Therefore, it does not
end with a semi-colon.

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

4.13.1 Rules for defining variables


Some rules have to be followed while forming variable names. They are as follows:
 Variables cannot include any special characters or punctuation marks (like #, s, ^, ?, ., etc.)
except the underscore ‘_’.
 There cannot be two successive underscores.
 Keywords cannot be used as variables.

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:

Variable Valid/Invalid Reason


principle_amount Valid
A Valid
Sum1 Valid
for1 Valid
if Invalid It is a keyword
for Invalid It is a keyword
3_factorial Invalid Should not start with digit
Sum,1 Invalid Comma should not be there
sum-of-digits Invalid Minus sign should not be there
sum_of_digits Valid
sum of digits Invalid No spaces are allowed
$sum Invalid $ sign should not be there
sum= Invalid = sign should not be there
one+two Invalid + sign should not be there
sum! Invalid ! sign should not be there
int Invalid It is a keyword
$roll no Invalid $ sign should not be there
_name1 Valid
James bond Invalid No spaces are allowed

4.13.2 Types of Variables


C language supports two basic kinds of variables numeric and character.

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: it can be int, float, char, double etc.


v1,v2,---,vn: is a list of variables, which are separated by commas.
Ex: int a,b,c;
float p,t,r,si;

4.13.4 Initializing the variables


 Initialization is the process of assigning values to the variables.
Syntax:
datatype var_name=data;

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;

4.14 Input/Output statements in C


 A Stream is the source of data as well as the destination of data.
 Streams are associated with a physical device such as a monitor or a file stored on the
secondary memory.
 C uses two forms of streams:
 Text stream: In a text stream, sequence of characters is divided into lines, each line
being terminated with a new character(\n).
 Binary stream: A binary stream contains data values using their memory
representation.

Figure 4.7. Input and output streams in C

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

Figure 4.8. printf() in C


The syntax of printf function:
printf(“control string”, variable list);
 The function accepts two parameters- control string & variable list.
 The control string may also contain the text to be printed like instructions to the user, captions,
identifiers or any other text to make the output readable.
 In some printf statements there may be only a text string that has to be displayed on the screen.
 The control characters can also be included in the printf statement like \n, \t, \a, etc.
 The prototype of control string:
%[flags][width[[.precision][length modifier] type specifier
 Each control string must begin with a % sign. The % sign specifies how the next variable in the
list of variables has to be printed.
 After % sign follows:

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

Table 4.3 Type specifiers for printf()

Guidelines/Rules for printf()


 A printf() always contains a string or format string in quotation marks.
 The control string may or may not be followed by some variables or expressions whose value
we want printed.
 Each value to be printed needs a ‘conversion specification’ like %d to hold its place in the
control string.
 This conversion specification describes the exact way the value is to be printed.
 When printf() is executed each conversion specification is replaced by the value of the
corresponding expression, then print according to the rules in specification.
 The symbols \n or \t in control string tell the machine to skip to new line or tab. It affects the
appearance of the output but not displayed as part of it.
 A word or blank space or punctuation symbols within the control string will print exactly as it
appears.

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

Ex: printf (“%d%d \n”,a,b);


and Both are same
printf (“%d%d \n”, a, b);

Control String or Newline character Variables to be printed


Format Specifiers

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

Rules to use a scanf function:


Rule 1: The scanf function works until:
o the maximum number of characters has been processed
o a white space character is encountered,
o or an error is detected.

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 6: Input data values must be separated by spaces.

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

2. Reading variables of different data types in one statement:


int num;
float fnum;
char ch;
char str[10];
scanf(“%d %f %c %s”, &num, &fnum, &ch, str);

Dr. DBIT-CSE 20

soprotection.com

You might also like