You are on page 1of 12

1

2 Programming in C

Storage It is the process of saving data and instructions ∑ Processor


permanently in the computer so that they can be used for ∑ Peripheral Devices/Input and Output Devices

Introduction to processing. The computer storage space not only stores


the data and programs that operate on that data but also
stores the intermediate results and the final results of
Memory

Programming
Memory is an internal storage area in the computer, which
processing.
is used to store data and programs either temporarily or
A computer has two types of storage areas: primary
permanently. Computer memory can be broadly divided
storage and secondary storage.
into two groups—primary memory and secondary
Processing The process of performing operations on the memory.
data as per the instructions specified by the user (program) While the main memory holds instructions and data
is called processing. Data and instructions are taken from when a program is executing, the auxiliary or the secondary
the primary memory and transferred to the arithmetic memory holds data and programs that are not currently in
and logical unit (ALU), which performs all sorts of use and provides long-term storage.
calculations. The intermediate results of processing may To execute a program, all the instructions or data that

s
Takeaways be stored in the main memory, as they might be required has to be used by the CPU has to be loaded into the main

es

es
again. When the processing completes, the final result memory. However, the primary memory is volatile and so
∑ Hardware ∑ Stored program concept ∑ Compiler, interpreter, linker, loader
is then transferred to the main memory. Hence, the data it can retain data only when the power is on. Moreover, it

Pr

Pr
∑ Application software ∑ Generation of programming languages ∑ Machine language
∑ Assembly language ∑ Procedural and non-procedural languages ∑ Design of efficient programs
may move from main memory to the ALU multiple times is very expensive and therefore limited in capacity.
before the processing is over. On the contrary, the secondary memory stores data or
ity

ity
∑ System software
instructions permanently, even when the power is turned off.
Output Output is the process of giving the result of data It is cheap and can store large volumes of data. Moreover,
rs

rs
processing to the outside world (external to the computer data stored in auxiliary memory is highly portable, as the
system). The results are given through output devices such users can easily move it from one computer to another. The
e

e
∑ Accepting data or instructions (input) as monitor and printer. Since the computer accepts data only drawback of secondary memory is that data can be
1.1 WHAT IS A COMPUTER?
iv

iv
only in the binary form and the result of processing is also accessed from it only at very low speeds as compared with
∑ Storing data
in the binary form, the result cannot be directly given to
Un

Un
A computer, in simple terms, can be defined as an electronic the data access speed of the primary memory.
∑ Processing data
device that is designed to accept data, perform the required the user. The output devices, therefore, convert the results Random access memory (RAM) and read only memory
mathematical and logical operations at high speed, and ∑ Displaying results (output) available in binary codes into a human-readable language (ROM) are the two types of primary memory.
∑ Controlling and coordinating all operations inside a
d

d
output the result. A computer accepts data, processes it, before displaying it to the user.
and produces information (see Figure 1.1). Here, data computer Random access memory RAM is a volatile storage area
or

or
Control The control unit (CU) is the central nervous within the computer that is typically used to store data
refers to some raw facts or figures, and information Refer to Figure 1.2, which shows the interaction between
system of the entire computer system. It manages and temporarily, so that it can be promptly accessed by the
xf

xf
implies the processed data. For example, if 12-12-92 is the the different units of a computer system.
controls all the components of the computer system. processor. The information stored in the RAM is basically
date of birth of a student, then it is data (a raw fact/figure).
O

O
The CU decides the manner in which instructions will loaded from the computer’s hard disk, and includes data
However, when we process this data (subtract it from the
be executed and operations performed. It takes care of related to the operating system and applications that are
present date) and say that the age of the student is 18 years,
the step-by-step processing of all operations that are currently being executed by the processor.
then the outcome is information.
performed in the computer.
RAM is considered random access because any memory
cell can be directly accessed if its address is known. When

Figure 1.1 Functions of computers


1.2 COMPONENTS OF A COMPUTER the RAM gets full, the computer system operates at a slow
SYSTEM speed. When multiple applications are being executed
Figure 1.2 Block diagram of a computer
Today, computers have become a crucial part of our simultaneously and the RAM gets fully occupied by
everyday lives, and we need computers just like we need Input This is the process of entering data and instructions The components of a computer system consist of: Hardware the application’s data, it is searched to identify memory
the television, telephones, or other electronic devices at (also known as programs) in to the computer system. The and Software. portions that have not been utilized. The contents of those
home. Computers are basically meant to solve problems data and instructions can be entered by using different locations are then copied onto the hard drive. This action
quickly and accurately. input devices such as keyboard, mouse, scanner, and 1.2.1 Hardware frees up RAM space and enables the system to load other
trackball. Note that computers understand binary language, pieces of required data.
Basic Computer Organization which consists of only two symbols (0 and 1), so it is the
Hardware of a computer system includes:
These days, the applications’ and operating system’s
A computer is an electronic device that basically performs responsibility of the input devices to convert the input data ∑ Memory demand for system RAM has drastically increased. For
five major operations: into binary codes. ∑ Disks example, in the year 2000, a personal computer (PC) had

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 1 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 2 31/07/18 5:17 PM


Introduction to Programming 3 4 Programming in C

only 128 MB of RAM, but today PCs have 1–2 GB of can then be rewritten with a process that again needs the The R/W head can pivot back and forth over the platters Processor
RAM installed, and may include graphics cards with their application of a higher voltage. Repeated exposure to to read or write data on them. Data is actually stored on the
A basic processor consists of two main parts—ALU and
own additional 512 MB or more of RAM. There are two ultraviolet light wears out the chip. surface of a platter in sectors and tracks.
control unit (CU). Besides these components, there are
types of RAM—static RAM (SRAM) and dynamic RAM • Electrically erasable programmable read-only memory also registers, an execution unit, and a bus interface unit
(DRAM). (EEPROM) It is based on a semiconductor structure (BIU) as shown in Figure 1.4.
• Static RAM This is a type of RAM that holds data similar to the EPROM, but allows the entire or selected
without an external refresh as long as it is powered. contents to be electrically erased, then rewritten
• Dynamic RAM This is the most common type of electrically, so that they need not be removed from the
memory used in personal computers, workstations, and computer (or camera, MP3 player, etc.). The process of
servers today. A DRAM chip contains millions of tiny writing an EEPROM is also known as flashing.
memory cells. Each cell is made up of a transistor and Secondary storage devices Secondary storage (also
a capacitor, and can contain 1 bit of information—0 known as external memory or auxiliary storage) differs
or 1. To store a bit of information in a DRAM chip, from main memory in that it is not directly accessible by
a tiny amount of power is put into the cell to charge the CPU. The secondary storage devices hold data even

s
the capacitor. Hence, while reading a bit, the transistor

es

es
when the computer is switched off. An example of such a
checks for a charge in the capacitor. If a charge is device is the hard disk.
present, then the reading is 1; if not, the reading is 0.

Pr

Pr
The computer usually uses its input/output channels to
access data from the secondary storage devices to transfer
Read only memory ROM refers to computer memory
ity

ity
the data to an intermediate area in the main memory.
chips containing permanent or semi-permanent data. Secondary storage devices are non-volatile in nature,
Unlike RAM, ROM is non-volatile; that is, the data is Figure 1.3 Schematic diagram of a hard disk Figure 1.4 Basic computer organization
cheaper than the primary memory, and thus can be used
rs

rs
retained in it even after the computer is turned off. to store huge amounts of data. While the CPU can read
The performance of a hard disk depends on its access
e

e
Most computers contain a small amount of ROM that the data stored in the main memory in nanoseconds, the Execution unit The execution unit mainly consists of the
time, which is the time required to read or write on the
iv

iv
stores critical programs such as the basic input/output data from the secondary storage devices can be accessed CU, ALU, and registers.
system (BIOS), which is used to boot up the computer disk. Access time is a combination of the following three
in milliseconds. ∑ Control unit The main function of the CU is to direct
Un

Un
when it is turned on. The BIOS consists of a few kilobytes components:
The secondary storage devices are basically formatted and coordinate the computer operations. It interprets the
of code that tells the computer what to do when it starts according to a file system that organizes the data into files ∑ Seek time This is the time taken to position the R/W instructions (program) and initiates action to execute
up, such as running hardware diagnostics and loading the and directories. The file system also provides additional head over the appropriate cylinder (usually around 8
d

d
them. The CU controls the flow of data through the
operating system into the RAM. Moreover, ROMs are used information to describe the owner of a certain file, the ms on an average). Seek time varies depending on the
computer system and directs the ALU, registers, buses,
or

or
extensively in calculators and peripheral devices such as access time, the access permissions, and other information. position of the access arm when the R/W command is
and input/output (I/O) devices. It is, therefore, called
laser printers, whose fonts are often stored in ROMs. received. Its value will be maximum when the access
xf

xf
the brain of the computer system. Similar to the human
Originally, ROMs were read-only. So, in order to Hard Disks arm is positioned over the innermost track while the data
brain, the CU controls all operations within the processor,
O

O
update the programs stored in them, the ROM chip had to The hard drive is a part of the computer that stores all the that has to be accessed is stored on the outermost track.
which in turn controls all other parts of the computer
be removed and physically replaced by another that had programs and files, so if the drive is damaged for some rea- Similarly, it will be zero if the access arm is already
system. In addition, the CU is responsible for fetching,
a newer version of the program. However, today ROM son, all the data stored on the computer is lost. The hard positioned over the desired track. On an average, the
decoding, executing instructions, and storing results.
chips are not literally read-only, as updates to the chip disk provides relatively quick access to large amounts of seek time varies from 10 to 100 milliseconds.
are possible. The process of updating a ROM chip is a ∑ Arithmetic and logic unit The ALU performs arithmetic
data stored on an electromagnetically charged surface or a ∑ Rotational delay This is the time taken to bring the
bit slower, as memory must be erased in large portions (add, subtract, multiply, divide, etc.), comparison (less
set of surfaces. Today, PCs come with hard disks that can target sector to rotate under the R/W head. Assuming
before it can be rewritten. Rewritable ROM chips include than, greater than, or equal to), and other operations.
store gigabytes of data. that the hard disk has 7,200 rpm, or 120 rotations per
PROMs, EPROMs, and EEPROMs. A hard disk is basically a set of disks, stacked together second, a single rotation is done in approximately 8 ms. Registers A processor register is a computer memory that
• Programmable read-only memory (PROM) It is also like phonograph records, that has data recorded electro- The average rotational delay is around 4 ms. provides quick access to the data currently being used for
called one-time programmable ROM, and can be magnetically in concentric circles known as tracks. ∑ Transfer time The time to transfer data or read/write to processing. The ALU stores all temporary results and the
written to or programmed using a special device called A single hard disk includes several platters (or disks) a disk is called the transfer rate. final result in the processor registers. As mentioned earlier,
a PROM programmer. that are covered with a magnetic recording medium. Each Thus, the overall time required to access data = seek registers are at the top of memory hierarchy and are always
• Erasable programmable read-only memory (EPROM) It platter requires two read/write (R/W) heads, one for each time + rotational delay + transfer time. preferred to speed up program execution. Registers are
is a type of ROM that can be erased and re-programmed. side. Note that in the figure, all the R/W heads are attached to The sum of the seek time and the rotational delay is also also used to store the instructions of the program currently
The EPROM can be erased by exposing the chip to strong a single access arm and so they cannot move independently. known as disk latency. Disk latency is the time taken to being executed. There are different types of registers, each
ultraviolet light, typically for 10 minutes or longer, and The parts of the hard disk are shown in Figure 1.3. initiate a transfer. with a specific storage function.

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 3 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 4 31/07/18 5:17 PM


Introduction to Programming 5 6 Programming in C

∑ Accumulator and general purpose registers These are tells the processor what it needs to do, from where to find
frequently used to store the data brought from the main data (register, memory, or I/O device), from where to find
memory and the intermediate results during program instruction, and so on. Nowadays, computers come with
execution. The number of general purpose registers a large set of instructions, and each processor supports
present varies from processor to processor. its own instruction set. Although the instructions across
∑ Special purpose registers These include the memory processors are almost the same, they may vary in their
address register (MAR) that stores the address of the internal design.
data or instruction to be fetched from the main memory,
the memory buffer register (MBR) that stores the data System clock A small quartz crystal circuit called
or instruction fetched from the main memory, the the system clock controls the timing of all operations
instruction register (IR) that stores the instructions within the computer system. The system clock regularly
currently being executed, the I/O register that is used generates ticks to control the functioning of the computer.
to transfer data or instructions to or from an I/O device, Every processor has a system clock to synchronize various
and the program counter that stores the address of the operations that take place within the computer system. Figure 1.6 Categories of input devices

s
next instruction to be executed. Many modern computers even have multiple system

es

es
clocks that vibrate at a specific frequency.
∑ Instruction cycle To execute an instruction, a processor
normally follows a set of basic operations that are

Pr

Pr
Processor speed The speed of PCs and minicomputers is Input Devices An input device is used to feed data and one to read or write text, but also enable the user to
together known as an instruction cycle. The operations
usually specified in MHz or GHz. However, the speed of instructions into the computer. Figure 1.6 categorizes record songs, view animated movies, etc. Hence, in
performed in an instruction cycle involve fetch, decode,
addition to having a keyboard and a mouse, audio–
ity

ity
a mainframe computer is measured in MIPS (millions of input devices into different groups.
execute, and store instructions.
instructions per second) or BIPS (billions of instructions video devices have become a necessity today.
∑ Keyboard The keyboard is the main input device for
per second) and that of a supercomputer is measured
rs

rs
Bus interface unit The BIU provides functions for transfer- computers. Computer keyboards look very similar to Output Devices Any device that outputs/gives information
ring data between the execution unit of the CPU and other in MFLOPS (millions of floating-point operations per
the keyboards on it and is used to access the options from a computer can be called an output device. Basically,
e

e
components of the computer system that lie outside the CPU. second), GFLOPS (giga or billions of floating-point
available by pressing the right mouse button. output devices are electromechanical devices that accept
iv

iv
Every computer system has three different types of busses to operations per second). The reason for the variations
∑ Pointing Devices A pointing input device enables the digital data (in the form of 0s and 1s) from the computer
in speed is that personal or minicomputers use a single
Un

Un
carry information from one part to the other. These are the and convert them into human-understandable language.
processor to execute instructions, whereas mainframes users to easily control the movement of the pointer to
data bus, control bus, and address bus (Figure 1.5). Monitors and speakers are two widely used output devices.
and supercomputers employ multiple processors to speed select items on a display screen, to select commands
from commands menu, to draw graphs, etc. Some These devices provide instant feedback to the user’s input.
up their overall performance.
d

d
examples of pointing devices include mouse, trackball, Output devices are classified based on whether they give a
or

or
light pen, joystick, and touchpad. hard copy or soft copy output (refer to Figure 1.7).
Pipelining and parallel processing Most of the modern
PCs support pipelining. Pipelining is a technique with ∑ Handheld Devices A handheld device is a pocket-sized
xf

xf
which the processor can fetch the second instruction before computing device with a display screen and touch input
O

O
completing the execution of the first instruction. Initially, and/or a miniature keyboard. Some common examples
a processor had to wait for an instruction to complete all of handheld devices include smartphones, PDAs,
stages before it could fetch the next instruction, thereby handheld game consoles, and portable media players
Figure 1.5 Buses with a computer system wasting its time. However, with pipelining, processors can (such as iPod).
operate at a faster pace as they no longer have to wait for one ∑ Optical Devices Optical devices, also known as data-
The BIU puts the contents of the program counter on the instruction to complete before fetching the next instruction. scanning devices, use light as a source of input for
address bus. Note that the content of the program counter Such processors that can execute more than one instruction detecting or recognizing different objects such as
is the address of the next instruction to be executed. Once per clock cycle are called superscalar processors. Figure 1.7 Classification of output devices
characters, marks, codes, and images. The optical
the memory receives an address from the BIU, it places
device converts these objects into digital data and sends
the contents at that address on the data bus, which is then Peripheral Devices/Input and Output Devices it to the computer for further processing. Some optical • Soft copy devices These devices produce an electronic
transferred to the IR of the processor through the MBR. At
In order to accomplish tasks, a computer must be able to devices include barcode readers, image scanners, optical version of an output—for example, a file that is stored
this time, the contents of the program counter are modified
interact with its users. For this purpose, we need input character recognition (OCR) devices, optical mark on a hard disk, CD, or pen drive—and is displayed on
(e.g., incremented by 1) so that it now stores the address of
and output devices, which are also known as peripheral readers (OMR), and magnetic ink character recognition the computer screen.
the next instruction.
devices. There are different types of input/output devices, (MICR) devices. • Hard copy devices These devices produce a physical
Instruction set The instruction set is a set of commands and each device has capabilities that differentiate it from ∑ Audio-visual Input Devices Today, all computers are form of output. For example, the content of a file printed
that instructs the processor to perform specific tasks. It the others. multimedia-enabled, that is, computers not only allow on paper is a form of hard copy output.

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 5 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 6 31/07/18 5:17 PM


Introduction to Programming 7 8 Programming in C

1.2.2 Computer Software The most widely used system software are discussed in
the following sections:
Computer software can be broadly classified into two
groups: system software and application software. Computer BIOS and Device Drivers The computer BIOS
∑ System software [according to Nutt, 1997] provides and device drivers provide basic functionality to operate
and control the hardware connected to or built into the
a general programming environment in which
computer.
programmers can create specific applications to suit their
needs. This environment provides new functions that are BIOS or Basic Input/Output System is a de facto
not available at the hardware level and performs tasks standard defining a firmware interface. BIOS is built into
related to execution of application programs. the computer and is the first code run by the computer
System software represents programs that allow the when it is switched on. The key role of BIOS is to load
hardware to run properly. System software is transparent and start the operating system.
to the user and acts as an interface between the hardware When the computer starts, the first function that BIOS
of the computer and the application software that users performs is to initialize and identify system devices such

s
need to run on the computer. Figure 1.8 illustrates the as the video display card, keyboard and mouse, hard disk,

es

es
relationship between application software, system CD/DVD drive, and other hardware. In other words, the
software, and hardware. code in the BIOS chip runs a series of tests called POST

Pr

Pr
(Power On Self Test) to ensure that the system devices are
∑ Application software is designed to solve a particular working correctly.
ity

ity
problem for users. It is generally what we think of when BIOS then locates software held on a peripheral device
we say the word ‘computer programs’. Examples of such as a hard disk or a CD, and loads and executes that
application software include spreadsheets, database
rs

rs
software, giving it control of the computer. This process is
systems, desktop publishing systems, program known as booting.
e

e
development software, games, web browsers, among BIOS is stored on a ROM chip built into the system and
iv

iv
others. Simply put, application software represents has a user interface like that of a menu (Figure 1.9) that Figure 1.9 BIOS menu
programs that allow users to do something besides
Un

can be accessed by pressing a certain key on the keyboard

Un
simply running the hardware. when the computer starts. The BIOS menu can enable the which give us clues about applications. We have a different Utility Software Utility software is used to analyse,
user to configure hardware, set the system clock, enable or icon for launching a web browser, e-mail application, or configure, optimize, and maintain the computer system.
disable system components, and most importantly, select
d

d
User 1 User 2 User N even a document preparation application. In other words, Utility programs may be requested by application
which devices are eligible to be a potential boot device
or

or
it is the human–computer interface which helps to identify programs during their execution for multiple purposes.
and set various password prompts.
and launch an application. The interface hides a lot of Some of them are as follows:
To summarize, BIOS performs the following functions:
xf

xf
Application programs (games, spreadsheets, details of the instructions that perform all these tasks.
word processors, database, web browsers) ∑ Initializes the system hardware Similarly, if we examine the programs that help us in using ∑ Disk defragmenters can be used to detect computer files
O

O
input devices like keyboard/mouse, all the complex details of whose contents are broken across several locations on
∑ Initializes system registers
the character reading programs are hidden from users. We the hard disk, and move the fragments to one location in
∑ Initializes power management system order to increase efficiency.
System Software (operating system) as users simply press buttons to perform the input operation
∑ Tests RAM
regardless of the complexity of the details involved. ∑ Disk checkers can be used to scan the contents of a hard
∑ Tests all the serial and parallel ports An operating system ensures that the system resources disk to find files or areas that are either corrupted in
Computer Hardware ∑ Initializes CD/DVD drive and hard disk controllers (such as CPU, memory, I/O devices) are utilized efficiently. some way, or were not correctly saved, and eliminate
(printer, mouse, scanner, keyboard, CPU, disk) ∑ Displays system summary information For example, there may be many service requests on a web them in order to make the hard drive operate more
server and each user request needs to be serviced. Moreover, efficiently.
Figure 1.8 Relationship between hardware, system Operating System The primary goal of an operating there may be many programs residing in the main memory. ∑ Disk cleaners can be used to locate files that are
software, and application software system is to make the computer system (or any other Therefore, the system needs to determine which programs either not required for computer operation, or take up
device in which it is installed like a cell phone) convenient are currently being executed and which programs need to considerable amounts of space. Disk cleaners help users
System Software and efficient to use. An operating system offers generic wait for some I/O operation. This information is necessary to decide what to delete when their hard disk is full.
services to support user applications. because the programs that need to wait can be suspended
System software is software designed to operate the ∑ Disk space analysers are used for visualizing the disk
computer hardware and to provide and maintain a platform From users’ point of view the primary consideration is temporarily from engaging the processor. Hence, it is space usage by getting the size for each folder (including
for running application software. always the convenience. Users should find it easy to launch important for an operating system to have a control policy subfolders) and files in a folder or drive.
an application and work on it. For example, we use icons and algorithm to allocate the system resources.

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 7 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 8 31/07/18 5:17 PM


Introduction to Programming 9 10 Programming in C

∑ Disk partitions utilities are used to divide an individual If the source code contains errors then the compiler will ∑ Loader It is a special type of program that copies ∑ Instructions written by the users are performed
drive into multiple logical drives, each with its own file not be able to perform its intended task. Errors resulting programs from a storage device to main memory, where sequentially until there is a break in the current flow.
system. Each partition is then treated as an individual from the code not conforming to the syntax of the they can be executed. However, in this book we will ∑ Input/Output and processing operations are performed
drive. programming language are called syntax errors. Syntax not go into the details of how a loader actually works. simultaneously. While data is being read/written, the
∑ Backup utilities can be used to make a copy of all errors may be spelling mistakes, typing mistakes, etc. This is because the functionality of a loader is generally central processing unit (CPU) executes another program
information stored on a disk. In case a disk failure Another type of error is logical error which occurs hidden from the programmer. As a programmer, it in the memory that is ready for execution.
occurs, backup utilities can be used to restore the entire when the program does not function accurately. Logical suffices to learn that the task of a loader is to bring the
disk. Even if a file gets deleted accidentally, the backup errors are much harder to locate and correct. program and all its related files into the main memory Note
utility can be used to restore the deleted file. The work of a compiler is simply to translate human from where it can be executed by the CPU. A stored program architecture is a fundamental computer
∑ Disk compression utilities can be used to enhance the readable source code into computer executable machine architecture wherein the computer executes the
capacity of the disk by compressing/decompressing the code. It can locate syntax errors in the program (if any) Application Software instructions that are stored in its memory.
contents of a disk. but cannot fix it. Until and unless the syntactical errors Application software is a type of computer software that
∑ File managers can be used to provide a convenient are rectified the source code cannot be converted into employs the capabilities of a computer directly to perform John W. Mauchly, an American physicist, and J. Presper
method of performing routine data management the object code. a user-defined task. This is in contrast with system Eckert, an American engineer, further contributed to the

s
tasks such as deleting, renaming, cataloguing, moving, ∑ Interpreter Like the compiler, the interpreter also software which is involved in integrating a computer’s stored program concept to make digital computers much

es

es
copying, merging, generating, and modifying data sets. executes instructions written in a high-level language. capabilities, but typically does not directly apply them in more flexible and powerful. As a result, engineers in England
built the first stored-program computer, Manchester Mark

Pr

Pr
∑ System profilers can be used to provide detailed Basically, a program written in a high-level language the performance of tasks that benefit users.
can be executed in any of the two ways. First by To better understand application software consider an I, in the year 1949. They were shortly followed by the
information about the software installed and hardware
compiling the program and second, to pass the program analogy where hardware would depict the relationship of Americans who designed EDVAC in the very same year.
attached to the computer.
ity

ity
through an interpreter. an electric light bulb (an application) to an electric power Today, a CPU chip can handle billions of instructions
∑ Anti-virus utilities are used to scan for computer viruses. per second. It executes instructions provided both the data
While the compiler translates instructions written in generation plant (a system) that depicts the software.
rs

rs
∑ Data compression utilities can be used to output a file and instructions are valid. In case either one of them or
high-level programming language directly into the The power plant merely generates electricity which
with reduced file size. both are not valid, the computer stops the processing of
e

e
machine language, the interpreter, on the other hand, is not by itself of any real use until harnessed to an
∑ Cryptographic utilities can be used to encrypt and instructions.
iv

iv
translates the instructions into an intermediate form, application like the electric light that performs a service
decrypt files.
which it then executes. This clearly means that the which actually benefits users.
Un

Un
∑ Launcher applications can be used as a convenient interpreter interprets the source code line by line. This Typical examples of software applications are word 1.3.1 Types of Stored Program Computers
access point for application software. is in striking contrast with the compiler which compiles processors, spreadsheets, media players, education software, A computer with a Von Neumann architecture (refer to
∑ Registry cleaners can be used to clean and optimize the the entire code in one go. CAD, CAM, data communication software, and statistical Figure 1.10) stores data and instructions in the same
d

d
Windows operating system registry by deleting the old Usually, a compiled program executes faster than an and operational research software. Multiple applications memory. There is a serial machine in which data and
or

or
registry keys that are no longer in use. interpreted program. However, the big advantage of an bundled together as a package are sometimes referred to as instructions are selected one at a time. Data and instructions
∑ Network utilities can be used to analyse the computer’s interpreted program is that it does not need to go through an application suite. are transferred to and from memory through a shared data
xf

xf
network connectivity, configure network settings, check the compilation stage during which machine instructions bus. Since there is a single bus to carry data and instructions,
O

O
data transfer, or log events. are generated. This process can be time consuming process execution becomes slower.
∑ Command line interface (CLI) and Graphical user if the program is long. Moreover, the interpreter can 1.3 STORED PROGRAM CONCEPT Later Harvard University proposed a stored program
interface (GUI) can be used to make changes to the immediately execute high-level programs. concept in which there was a separate memory to store data
All digital computers are based on the principle of stored
operating system. All in all, compilers and interpreters both achieve and instructions. Instructions are selected serially from the
program concept,which was introduced by Sir John von
similar purposes, but inherently different as to how they instruction memory and executed in the processor. When an
Neumann in the late 1940s. The following are the key
Compiler, Interpreter, Linker, and Loader achieve that purpose. instruction needs data, it is selected from the data memory.
characteristic features of this concept:
∑ Compiler It is a special type of program that transforms ∑ Linker (link editor binder) It is a program that combines Since there are separate memories, execution becomes faster.
∑ Before any data is processed, instructions are read into
the source code written in a programming language (the object modules to form an executable program.
memory.
source language) into machine language comprising Generally, in case of a large program, the programmers
∑ Instructions are stored in the computer’s memory for 1.4 PROGRAMMING LANGUAGES
just two digits, 1s and 0s (the target language). The prefer to break a code into smaller modules as this
resultant code in 1s and 0s is known as the object code. execution. A programming language is a language specifically
simplifies the programming task. Eventually, when the
The object code is the one which will be used to create source code of all the modules has been converted into ∑ Instructions are stored in binary form (using binary designed to express computations that can be performed
an executable program. object code, we need to put all the modules together. numbers—only 0s and 1s). by the computer. Programming languages are used to
Therefore, a compiler is used to translate source code This is the job of the linker. Usually, the compiler ∑ Processing starts with the first instruction in the create programs that control the behaviour of a system,
from a high-level programming language to a lower level automatically invokes the linker as the last step in program, which is copied into a control unit circuit. The to express algorithms, or as a mode of human–computer
language (e.g., assembly language or machine code). compiling a program. control unit executes the instructions. communication.

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 9 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 10 31/07/18 5:17 PM


Introduction to Programming 11 12 Programming in C

Address Bus - carries addresses ∑ High-level language (also known as third generation code can run very fast and efficiently, since it is directly
language or 3GL) executed by the CPU.
Main ∑ Very high-level language (also known as fourth However, on the downside, the machine language is
Processor Data Bus - carries data and instructions difficult to learn and is far more difficult to edit if errors
Memory generation language or 4GL)
occur. Moreover, if you want to add some instructions
into memory at some location, then all the instructions
1.5.1 First Generation: Machine Language
after the insertion point would have to be moved down
(a) Machine language was used to program the first stored to make room in memory to accommodate the new
program on computer systems. This is the lowest level of instructions.
programming language. The machine language is the only Last but not the least, the code written in machine
Instruction address Data address
language that the computer understands. All the commands language is not portable across systems and to transfer
and data values are expressed using 1 and 0s, corresponding the code to a different computer it needs to be completely
Instruction Data to the ‘on’ and ‘off’ electrical states in a computer. rewritten since the machine language for one computer
Instructions Processor Read/Write Data
memory memory
In the 1950s each computer had its own native could be significantly different from another computer.

s
language, and programmers had primitive systems for Architectural considerations made portability a tough

es

es
combining numbers to represent instructions such as add issue to resolve.
(b) and subtract. Although there were similarities between

Pr

Pr
each of the machine languages, a computer could not
Figure 1.10 V
 on Neumann architecture (a) Shared memory for instructions and data (b) Separate memories for 1.5.2 Second Generation: Assembly Language
instructions and data understand programs written in another machine language
ity

ity
(Figure 1.11). The second generation of programming language includes
the assembly language. Assembly languages are symbolic
Usually, programming languages have a vocabulary ∑ The type of program programming languages that use symbolic notation to
rs

rs
MACHINE LANGUAGE
of syntax and semantics for instructing a computer to ∑ The expertise of the programmer This is an example of a machine language program that will add represent machine-language instructions. These languages
e

e
perform specific tasks. The term programming language two numbers and find their average. It is in hexadecimal
are closely connected to machine language and the internal
For example, FORTRAN is a particularly good notation instead of binary notation because this is how the
iv

iv
usually refers to high-level languages, such as BASIC, computer presented the code to the programmer. architecture of the computer system on which they are
language for processing numerical data, but it does not
C, C++, COBOL, FORTRAN, Ada, and Pascal to name a used. Since they are close to the machine, assembly
Un

Un
lend itself very well to organizing large programs. Pascal D000000A D000
few. Each of these languages has a unique set of keywords language is also called low-level language. Nearly all
can be used for writing well-structured and readable
(words that it understands) and a special syntax for D000000F D009 computer systems have an assembly language available
programs, but it is not as flexible as the C programming
organizing program instructions. for use.
d

d
D000000B D009
language. C++ goes one step ahead of C by incorporating
While high-level programming languages are easy Assembly language developed in the mid 1950s
or

or
powerful object-oriented features, but it is complex and D009
for humans to read and understand, the computer D009 was a great leap forward. It used symbolic codes also
difficult to learn.
actually understands the machine language that consists known as mnemonic codes that are easy-to-remember
xf

xf
D0Q0
of numbers only. Each type of CPU has its own unique abbreviations, rather than numbers. Examples of these
FF55 CF FF54 CF FF53 CF C1 DOD0
O

O
machine language. 1.5 GENERATION OF PROGRAMMING codes include ADD for add, CMP for compare, MUL for
In between the machine languages and high-level FF24 CF FF27 CF D2 C7 D00C
LANGUAGES multiply, etc.
languages, there is another type of language known as D0E4 Assembly language programs consist of a series of
assembly language. Assembly languages are similar to We now know that programming languages are the Dd0D individual statements or instructions that instruct the
machine languages, but they are much easier to program primary tools for creating software. As of now, hundreds computer what to do. Basically, an assembly language
Dd3D
because they allow a programmer to substitute names for of programming languages exist in the market, some statement consists of a label, an operation code, and one
numbers. more used than others, and each claiming to be the best.
Figure 1.11 A machine language program or more operands.
However, irrespective of what language the programmer However, back in the 1940s when computers were being
Labels are used to identify and reference instructions in
uses, the program written using any programming developed there was just one language—the machine
In machine language, all instructions, memory locations, the program. The operation code (opcode) is a mnemonic
language has to be converted into machine language so language.
numbers, and characters are represented in strings of that specifies the operation that has to be performed such
that the computer can understand it. There are two ways to The concept of generations of programming languages
1s and 0s. Although machine-language programs are as move, add, subtract, or compare. The operand specifies
do this: compile the program or interpret the program (also known as levels) is closely connected to the advances
typically displayed with the binary numbers represented the register or the location in main memory where the data
The question of which language is the best depends on in technology that brought about computer generations.
in octal (base 8) or hexadecimal (base 16), these programs to be processed is located.
the following factors: The four generations of programming languages include:
are not easy for humans to read, write, or debug. However, like the machine language, the statement
∑ The type of computer on which the program has to be ∑ Machine language The main advantage of machine language is that the or instruction in the assembly language will vary from
executed ∑ Assembly language

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 11 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 12 31/07/18 5:17 PM


Introduction to Programming 13 14 Programming in C

machine to another because the language is directly where one statement would generate one machine language 1.5.4 Fourth Generation: Very High-Level Fourth generation programming languages are still
related to the internal architecture of the computer and is instruction. Third Generation Programming Languages Languages evolving, which makes it difficult to define or standardize
not designed to be machine independent. This makes the made programming easier, efficient, and less prone to errors. them. The only downside of a 4GL is that it does not
code written in assembly language less portable as the High-level languages fall somewhere between natu- With each generation, programming languages started make efficient use of the machine’s resources. However,
code written for one machine will not run on machines ral languages and machine languages. Third Generation becoming easier to use and more like natural languages. the benefit of executing a program fast and easily, far
from a different or sometimes even the same manufacturer. Programming Languages include languages such as FOR- However, fourth generation programming languages outweighs the extra costs of running it.
No doubt, the code written in assembly language will be TRAN (FORmula TRANslator) and COBOL (COmmon (4GLs) are a little different from their its prior generation
very efficient in terms of execution time and main memory Business Oriented Language) that made it possible for because they are basically non-procedural. When writing
usage as the language is also close to the computer. scientists and business people to write programs using fa- code using a procedural language, the programmer has to 1.5.5 Fifth Generation Programming Languages
Programs written in assembly language need a miliar terms instead of obscure machine instructions. tell the computer how a task is done—add this, compare
Fifth generation programming languages (5GLs) are cen-
The first widespread use of high-level languages in the that, do this if the condition is true, and so on, in a very
translator often known as assembler to convert them tred on solving problems using constraints given to the
early 1960s changed programming into something quite specific step-by-step manner. In striking contrast, while
into machine language. This is because the computer will program, rather than using an algorithm written by a pro-
different from what it had been. Programs were written in using a non-procedural language the programmers define
understand only the language of 1s and 0s and will not grammer. Most constraint-based and logic programming
statements like English language statements, making them only what they want the computer to do, without supplying
understand mnemonics like ADD and SUB. languages and some declarative languages form a part of
all the details of how it has to be done.

s
The following instructions are a part of assembly more convenient to use and giving the programmer more the fifth-generation languages. Fifth generation program-

es

es
time to address a client’s problems. There is no standard rule that defines what a 4GL is but
language code to illustrate addition of two numbers: ming languages are widely used in artificial intelligence
Although 3GLs relieve the programmer of demanding certain characteristics of such languages include:
research. Typical examples of 5GLs include Prolog,

Pr

Pr
MOV AX,4 Stores value 4 in the AX
details, they do not provide the flexibility available in low- ∑ the code comprising instructions are written in English- OPS5, and Mercury.
register of CPU
MOV BX,6 Stores value 6 in the BX
level languages. However, a few high-level languages like sentences; Another aspect of a 5GL is that it contains visual tools
ity

ity
like C and FORTRAN combine some of the flexibility to help develop a program. A good example of a fifth
register of CPU ∑ they are non-procedural, so users concentrate on ‘what’
of assembly language with the power of high-level generation language is Visual Basic.
ADD AX,BX Adds the contents of AX and BX instead of the ‘how’ aspect of the task;
languages, but these languages are not well suited to an
rs

rs
registers. Stores the result in So taking a forward leap than the 4GLs, 5GLs are
amateur programmer. ∑ the code is easier to maintain; designed to make the computer solve a given problem
AX register
e

e
While some high-level languages were designed to serve ∑ the code enhances the productivity of the programmers without the programmer. While working with a 4GL, the
Although assembly languages are much better to pro-
iv

iv
a specific purpose (such as controlling industrial robots as they have to type fewer lines of code to get something programmer had to write specific code to do a work but
gram as compared to the machine language, they still require with 5GL, the programmer only needs to worry about
or creating graphics), other languages were flexible and done. It is said that a programmer becomes 10 times
Un

Un
the programmer to think on the machine’s level. Even today, what problems need to be solved and what conditions need
considered to be general-purpose languages. Most of the more productive when he writes the code using a 4GL
some programmers still use assembly language to write parts to be met, without worrying about how to implement a
programmers preferred to use general-purpose high-level than using a 3GL.
of applications where speed of execution is critical, such as routine or algorithm to solve them.
d

d
languages like BASIC (Beginners’ All-purpose Symbolic
video games but most programmers today have switched to A typical example of a 4GL is the query language Generally, 5GLs were built upon Lisp, many originating
Instruction Code), FORTRAN, PASCAL, COBOL, C++, or
or

or
third or fourth generation programming languages. that allows a user to request information from a database on the Lisp machine, such as ICAD. Then, there are many
Java to write the code for their applications.
with precisely worded English-like sentences. A query frame languages such as KL-ONE.
xf

xf
Again, a translator is needed to translate the instructions language is used as a database user interface and hides the
1.5.3 T hird Generation Programming written in high-level language into computer-executable
In the 1990s, 5GLs were considered to be the wave of
specific details of the database from the user. For example, the future, and some predicted that they would replace all
O

O
Languages machine language. Such translators are commonly known when working with structured query language (SQL), other languages for system development (except the low-
A third generation programming language (3GL) is as interpreters and compilers. Each high-level language the programmer just needs to remember a few rules of level languages). In 1982 to 1993 Japan had put much
a refinement of the second-generation programming has many compilers. syntax and logic, and it is easier to learn than COBOL research and money into their fifth generation computer
language. The 2GL languages brought logical structure to For example, the machine language generated by one or C. systems project, hoping to design a massive computer
software. The third generation was introduced to make the computer’s C compiler is not the same as the machine Let us take an example in which a report has to be network of machines using these tools. But when larger
languages more programmer friendly. language of some other computer. Therefore, it is necessary generated that displays the total number of students programs were built, the flaws of the approach became
Third Generation Programming Languages spurred the to have a C compiler for each type of computer on which enrolled in each class and in each semester. Using a 4GL, more apparent. Researchers began to observe that starting
great increase in data processing that occurred in the 1960s the C program has to be executed. the request would look similar to one that follows: from a set of constraints for defining a particular problem,
and 1970s. In these languages, the program statements Third generation programming languages have made then deriving an efficient algorithm to solve the problem
are not closely related to the internal architecture of the it easier to write and debug programs, which gives TABLE FILE ENROLLMENT is a very difficult task. All these things could not be
computer and is therefore often referred to as high-level programmers more time to think about its overall logic. SUM STUDENTS BY SEMESTER BY CLASS automated and still requires the insight of a programmer.
languages. The programs written in such languages are portable However, today the fifth-generation languages are
Generally, a statement written in a high-level program- between machines. For example, a program written in So we see that a 4GL is much simpler to learn and work back as a possible level of computer language. Software
ming language will expand into several machine language standard C can be compiled and executed on any computer with. The same code if written in C language or any other vendors across the globe currently claim that their software
instructions. This is in contrast to assembly languages, that has a standard C compiler. 3GL would require multiple lines of code to do the same meets the visual ‘programming’ requirements of the 5GL
task. concept.

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 13 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 14 31/07/18 5:17 PM


Introduction to Programming 15 16 Programming in C

of actions is made before the actual development process an organization knows how to use it or fix up certain Control Structures used in Algorithms
1.6 DESIGN AND IMPLEMENTATION
could start. This plan will be followed throughout the problems, then no one would like to use it. Moreover,
OF EFFICIENT PROGRAMS An algorithm has a finite number of steps and some steps
development process. Moreover, in the design phase the people are often resistant to change and avoid venturing
may involve decision-making and repetition. Broadly
The design and development of correct, efficient, and core structure of the software/program is broken down into an unfamiliar area, so as a part of the deployment
speaking, an algorithm can employ any of the three control
maintainable programs depends on the approach adopted into modules. The solution of the program is then specified phase, it has become very crucial to have training classes
structures, namely, sequence, decision, and repetition.
by the programmer to perform various activities that need for each module in the form of algorithms, flowcharts, or for the users of the software.
to be performed during the development process. The entire pseudocodes. The design phase, therefore, specifies how
program or software (collection of programs) development the program/software will be built. Sequence
1.6.6 Maintenance
process is divided into a number of phases where each Sequence means that each step of the algorithm is executed
phase performs a well-defined task. Moreover, the output 1.6.3 Implementation Maintenance and enhancements are ongoing activities in the specified order. An algorithm to add two numbers is
of one phase provides the input for its subsequent phase. which are done to cope with newly discovered problems given in Figure 1.13. This algorithm performs the steps in
The phases in software development process (as shown In this phase, the designed algorithms are converted into or new requirements. Such activities may take a long time a purely sequential order.
in Figure 1.12) can be summarized as below: program code using any of the high level languages. The to complete as the requirement may call for addition of
particular choice of language will depend on the type new code that does not fit the original design or an extra
Requirements
of program like whether it is a system or an application Step 1: Input the first number as A

s
analysis piece of code required to fix an unforeseen problem. As a
Step 2: Input the second number as B

es

es
program. While C is preferred for writing system general rule, if the cost of the maintenance phase exceeds Step 3: SET SUM = A + B
programs, Visual Basic might be preferred for writing an 25% of the prior-phases cost then it clearly indicates that Step 4: PRINT SUM

Pr

Pr
Design application program. The program codes are tested by the Step 5: END
the overall quality of at least one prior phase is poor. In
programmer to ensure their correctness. such cases, it is better to re-build the software (or some
This phase is also called construction or code generation
ity

ity
Implementation modules) before maintenance cost is out of control. Figure 1.13 Algorithm to add two numbers
phase as the code of the software is generated in this
phase. While constructing the code, the development
rs

rs
team checks whether the software is compatible with Decision
Testing 1.7 PROGRAM DESIGN TOOLS:
e

e
the available hardware and other software components Decision statements are used when the outcome of the
ALGORITHMS, FLOWCHARTS,
that were mentioned in the Requirements Specification
iv

iv
Software process depends on some condition. For example, if
Document created in the first phase. PSEUDOCODES x=y, then print “EQUAL”. Hence, the general form of the
deployment,
Un

Un
training and This section will deal about different tools which are used if construct can be given as
support 1.6.4 Testing to design solution(s) of a given problem at hand. if condition then process
An algorithm to check the equality of two numbers is
d

d
In this phase, all the modules are tested together to ensure shown in Figure 1.14.
Maintenance 1.7.1 Algorithms
or

or
that the overall system works well as a whole product.
Although individual pieces of codes are already tested In general terms, an algorithm provides a blueprint to
Figure 1.12 Phases in software development life cycle
xf

xf
by the programmers in the implementation phase, there writing a program to solve a particular problem. It is Step 1: Input the first number as A
is always a chance for bugs to creep in the program when considered to be an effective procedure for solving a Step 2: Input the second number as B
O

O
1.6.1 Requirements Analysis the individual modules are integrated to form the overall problem in a finite number of steps. That is, a well-defined
Step 3: IF A = B
Then PRINT "EQUAL"
In this phase, users’ expectations are gathered to know why program structure. In this phase, the software is tested algorithm always provides an answer, and is guaranteed ELSE
the program/software has to be built. Then all the gathered using a large number of varied inputs also known as test to terminate. PRINT "NOT EQUAL"
requirements are analysed to pen down the scope or the data to ensure that the software is working as expected Algorithms are mainly used to achieve software re- Step 4: END

objective of the overall software product. The last activity by the users’ requirements that were identified in the use. Once we have an idea or a blueprint of a solution, we
in this phase includes documenting every identified requirements analysis phase. can implement it in any high-level language, such as C, Figure 1.14 Algorithm to test for equality of two numbers
requirement of the users in order to avoid any doubts or C++, Java, and so on. In order to qualify as an algorithm,
uncertainty regarding the functionality of the programs. 1.6.5 S oftware Deployment, Training, a sequence of instructions must possess the following
Repetition
The functionality, capability, performance, availability of and Support characteristics:
Repetition, which involves executing one or more
hardware and software components are all analysed in this ∑ Be precise
After the code is tested and the software or the program has steps for a number of times, can be implemented using
phase.
been approved by the users, it is then installed or deployed ∑ Be unambiguous constructs such as while, do-while, and for loops. These
in the production environment. Software Training and ∑ Not even a single instruction must be repeated infinitely loops execute one or more steps until some condition is
1.6.2 Design Support is a crucial phase which is often ignored by most true. Figure 1.15 shows an algorithm that prints the first
∑ After the algorithm gets terminated, the desired result 10 natural numbers.
The requirements documented in the previous phase acts of the developers. Program designers and developers
must be obtained
as an input to the design phase. In the design phase, a plan spend a lot of time to create software but if nobody in

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 15 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 16 31/07/18 5:17 PM


Introduction to Programming 17 18 Programming in C

bottlenecks, and other less obvious features within it. sheet diagrams to substitute for arrows. For each label, 1.7.3 Pseudocodes
Step 1: [INITIALIZE] SET I = 0, N = 10
Step 2: Repeat Step while I<=N When designing a flowchart, each step in the process is the ‘outflow’ connector must have one or more ‘inflow’
connectors. A pair of identically labelled connectors Pseudocode is a compact and informal high-level
Step 3: PRINT I depicted by a different symbol and is associated with a
Step 4: SET I = I + 1 issued to indicate a continued flow when the use of lines description of an algorithm that uses the structural
short description. The symbols in the flowchart (refer
Step 5: END becomes confusing. conventions of a programming language. It is basically
Figure 1.16) are linked together with arrows to show the
meant for human reading rather than machine reading,
flow of logic in the process.
Figure 1.15 Algorithm to print first 10 natural numbers Example 1.1 so it omits the details that are not essential for humans.
Start or end Input/Output Such details include variable declarations, system-specific
symbol symbol Draw a flowchart to calculate the salary of a daily wager. code, and sub-routines. Pseudocodes are an outline of a
Selecting the Most Efficient Algorithm
Solution program that can be easily converted into programming
Many a times, you may formulate more than one algorithm
for a problem. In such cases, you must always analyse statements. They consist of short English phrases that
Arrows Decision symbol START
all the alternatives and try to choose the most efficient explain specific tasks within a program’s algorithm. They
algorithm. should not include keywords in any specific computer
Analysing an algorithm means determining the amount Input the no_of_hrs, language. The sole purpose of pseudocodes is to enhance
Processing step Connector
of resources (such as time and memory) needed to execute pay_per_hr, and human understandability of the solution. They are

s
travel_allowance commonly used in textbooks and scientific publications

es

es
it. Algorithms are generally designed to work with an Figure 1.16 Symbols of flowchart
arbitrary number of inputs, so the efficiency or complexity for documenting algorithms, and for sketching out the

Pr

Pr
of an algorithm is stated in terms of time and space Calculate SALARY = (no_of_hrs × program structure before the actual coding is done. This
The symbols of a flowchart include: helps even non-programmers to understand the logic of
complexity. pay_per_hr) + travel_allowance
The time complexity of an algorithm is basically the • Start and end symbols are also known as the terminal the designed solution. There are no standards defined
ity

ity
running time of a program as a function of the input size. symbols and are represented as circles, ovals, or for writing a pseudocode, because a pseudocode is not
Similarly, the space complexity of an algorithm is the rounded rectangles. Terminal symbols are always the Print SALARY an executable program. Flowcharts can be considered as
rs

rs
amount of computer memory that is required during the first and the last symbols in a flowchart. graphical alternatives to pseudocodes, but require more
program execution as a function of the input size. space on paper.
e

e
• Arrows depict the flow of control of the program. They
In other words, the number of machine instructions END
illustrate the exact sequence in which the instructions
iv

iv
which a program executes is called its time complexity. are executed. Example 1.3
Un

Un
This number is primarily dependent on the size of the • Generic processing step, also called as an activity, Example 1.2
program’s input and the algorithm used. Write a pseudocode for calculating the price of a product
is represented using a rectangle. Activities include after adding sales tax to its original price.
Generally, the space needed by a program depends on Draw a flowchart to determine the largest of three numbers.
instructions such as add a to b, save the result.
d

d
the following two parts: Therefore, a processing symbol represents arithmetic Solution Solution
or

or
∑ Fixed part: It varies from problem to problem. It 1. Read the price of the product
and data movement instructions. When more than
includes the space needed for storing instructions, START 2. Read the sales tax rate
one process has to be executed simultaneously, they
xf

xf
3. Calculate sales tax = price of the item ×
constants, variables, and structured variables (like can be placed in the same processing box. However,
sales tax rate
arrays and structures).
O

O
their execution will be carried out in the order of their Read the values 4. Calculate total price = price of the product
∑ Variable part: It varies from program to program. It appearance. of A, B, and C + sales tax
includes the space needed for recursion stack, and for • Input/output symbols are represented using a 5. Print total price
Print B
structured variables that are allocated space dynamically parallelogram and are used to get inputs from the users 6. End
during the runtime of a program. or display the results to them. Variables: price of the product, sales tax
YES rate, sales tax, total price
However, running time requirements are more critical • A conditional or decision symbol is represented using a
than memory requirements. Therefore, choose the diamond. It is basically used to depict a Yes/No question
algorithm that has less running time complexity. or a True/False test. The two arrows coming out of it, NO NO Example 1.4
Is A > B? Is B > C? Print C
one from the bottom vertex and the other from the right
YES
Write a pseudocode to read the marks of 10 students.
1.7.2 Flowcharts vertex, correspond to Yes or True, and No or False,
If marks are greater than 50, the student passes, else the
respectively. The arrows should always be labelled. A NO
A flowchart is a graphical or symbolic representation of Is A > C? Print C student fails. Count the number of students who pass and
decision symbol in a flowchart can have more than two
the number who fail.
a process. It is basically used to design and document arrows, which indicate that a complex decision is being YES
virtually complex processes to help the viewers to taken. Print A Solution
visualize the logic of the process, so that they can gain • Labelled connectors are represented by an identifying 1. Set pass to 0
a better understanding of the process and find flaws, label inside a circle and are used in complex or multi- 2. Set fail to 0
END
3. Set no of students to 0

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 17 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 18 31/07/18 5:17 PM


Introduction to Programming 19 20 Programming in C
4. WHILE no of students < 10 Semantic Errors Semantic errors are those errors which tests and then system test is applied to test this entire system Design In this phase, write an algorithm that gives a
a. input the marks may comply with rules of the programming language but as one system. solution to the problem.
b. IF marks >= 50 then
are not meaningful to the compiler. For example, if we
Set pass = pass + 1 Note Step 1: Enter the marks obtained as M
ELSE
write, a * b = c; it does not seem correct. Rather, if written
Testing should not be restricted to just execution testing. Step 2: If M > 75 then print “O”
Set fail = fail + 1 like c = a * b would have been more meaningful.
Step 3: If M >= 60 and M < 75 then print “A”
ENDIF
Logical Errors Logical errors are errors in the program Debugging, on the other hand, is an activity that includes Step 4: If M >= 50 and M < 60 then print “B”
ENDWHILE
5. End code that result in unexpected and undesirable output execution testing and code correction. The main aim of Step 5: If M >= 40 and M < 50 then print “C”
Variables: pass, fail, no of students, marks which is obviously not correct. Such errors are not detected debugging is locating errors in the program code. Once else
by the compiler, and programmers must check their code the errors are located, they are then isolated and fixed to print “D”
line by line or use a debugger to locate and rectify the produce an error-free code. Different approaches applied Step 6: End
errors. Logical errors occur due to incorrect statements. for debugging a code includes:
Implementation Write the C program to implement the
1.8 TYPES OF ERRORS For example, if you meant to perform c = a + b; and by Brute-Force Method In this technique, a printout of proposed algorithm.
mistake you typed c = a * b; then though this statement is CPU registers and relevant memory locations is taken,
While writing programs, very often we get errors in our #include <stdio.h>

s
syntactically correct, it is logically wrong. studied, and documented. It is the least efficient way of
program. These errors if not removed will either give int main()

es

es
debugging a program and is generally done when all the { int marks;
erroneous output or will not let the compiler to compile Linker Errors These errors occur when the linker is not
other methods fail. char grade;

Pr

Pr
the program. These errors are broadly classified under four able to find the function definition for a given prototype.
printf("\n Enter the marks of the student
groups as shown in Figure 1.17. For example, if you write clrscr(); but do not include Backtracking Method It is a popular technique that : ");
conio.h then a linker error will be shown. Similarly, even is widely used to debug small applications. It works by
ity

ity
scanf("%d", &marks);
Types of errors if you have defined a function display_data() but while locating the first symptom of error and then trace backward if (marks<0 || marks >100)
calling if you mistakenly write displaydata() then again a across the entire source code until the real cause of error { printf("\n Not Possible");
rs

rs
linker error will be generated. is detected. However, the main drawback of this approach exit(1);
Run-time Compile-time Linker Logical
e

e
is that with increase in number of source code lines, the }
errors errors errors errors possible backward paths become too large to manage.
iv

iv
if(marks>=75)
1.8.1 Testing and Debugging Approaches grade = 'O';
Un

Un
Figure 1.17 Types of Errors Cause Elimination In this approach, a list of all possible
Testing is an activity that is performed to verify correct else if(marks>=60 && marks<75)
behaviour of a program. It is specifically carried out with causes of an error is developed. Then relevant tests are grade = 'A';
Run-time Errors As the name suggests, run-time errors
an intent to find errors. Ideally testing should be conducted carried out to eliminate each of them. If some tests indicate else if(marks>=50 && marks<60)
occur when the program is being run executed. Such errors
d

d
at all stages of program development. However, in that a particular cause may be responsible for an error then grade = 'B';
occur when the program performs some illegal operations
or

or
the implementation stage, three types of tests can be the data are refined to isolate the error. else if(marks>=40 && marks<50)
like grade = 'C';
conducted:
xf

xf
• Dividing a number by zero Example 1.5 else
Unit Tests Unit testing is applied only on a single unit grade = 'D';
• Opening a file that already exists
O

O
or module to ensure whether it exhibits the expected Let us take a problem, collect its requirement, design the printf("\n GRADE = %c", grade);
• Lack of free memory space solution, implement it in C and then test our program. }
behaviour.
• Finding square or logarithm of negative numbers
Test The above program is then tested with different test
Run-time errors may terminate program execution, Integration Tests These tests are a logical extension of
Problem Statement To develop an automatic system that data to ensure that the program gives correct output for all
so the code must be written in such a way that it handles unit tests. In this test, two units that have already been
accepts marks of a student and generates his/her grade. relevant and possible inputs. The test cases are shown in
all sorts of unexpected errors rather terminating it tested are combined into a component and the interface
the table given below.
unexpectedly. This ability to continue operation of a between them is tested. The guiding principle is to test Requirements Analysis Ask the users to enlist the rules
program despite of run-time errors is called robustness. combinations of pieces and then gradually expanding the for assigning grades. These rules are:
component to include other modules as well. This process Test Case ID Input Expected Output Actual Output
Compile-time Errors Again as the name implies, compile- Marks Grade 1 -12 Not Possible Not Possible
is repeated until all the modules are tested together. The
errors occur at the time of compilation of the program. Above 75 O
main focus of integration testing is to identify errors that 2 112 Not Possible Not Possible
Such errors can be further classified as follows: 60-75 A
occur when the units are combined. 3 32 D D
Syntax Errors Syntax error is generated when rules of C 50-60 B 4 46 C C
System Tests System testing checks the entire system. For 40-50 C
programming language are violated. For example, if we 5 54 B B
example, if our program code consists of three modules
write int a: then a syntax error will occur since the correct Less than 40 D 6 68 A A
then each of the module is tested individually using unit
statement should be int a;

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 19 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 20 31/07/18 5:17 PM


Introduction to Programming 21 22 Programming in C

Test Case ID Input Expected Output Actual Output Note in the above table, we have identified test cases • In the testing phase, all the modules are tested together deployed in the production environment.
for the following, to ensure that the overall system works well as a whole • Maintenance and enhancements are ongoing activities
7 91 O O
product. which are done to cope with newly discovered problems
8 40 C C 1. “Not Possible” Combinations
2. A middle value from each range • After the code is tested and the software or the program or new requirements.
9 50 B B has been approved by the users, it is then installed or
3. Boundary values for each range
10 60 A A
11 75 O O
12 100 O O GLOSSARY
13 0 D D

Backtracking method The technique used to debug small output which is obviously not correct. Such errors are not
applications which works by locating the first symptom of detected by the compiler.
POINTS TO REMEMBER error and then tracing backward across the entire source Runtime errors Errors that occur when the program is being
code until the real cause of error is detected. executed

s
Cause elimination The technique in which list of all possible Semantic errors Errors which may comply with rules of
∑ A computer has two parts—computer hardware which ∑ The fourth generations of programming languages

es

es
causes of an error is developed. the programming language but are not meaningful to the
does all the physical work and computer software which are: machine language, assembly language, high-level
tells the hardware what to do and how to do it. language, and very high-level language. Compile errors Errors that occur at the time of compilation compiler

Pr

Pr
of the program Syntax Errors Errors that are generated when rules of C
∑ A program is a set of instructions that are arranged in ∑ Machine language is the lowest level of programming
a sequence to guide a computer to find a solution for a language that a computer understands. All the instructions Debugging An activity that includes execution testing and programming language are violated
ity

ity
given problem. The process of writing a program is called and data values are expressed using 1s and 0s. code correction. The main aim of debugging is locating System testing A testing technique that checks the entire
programming. errors in the program code. system
∑ Assembly language is a low-level language that uses symbolic
∑ Computer software is written by computer programmers Integration testing A testing technique in which two Testing An activity performed to verify correct behaviour of
rs

rs
notation to represent machine language instructions.
using a programming language. units that have already been tested are combined into a a program. It is specifically carried out with the intent to find
∑ Third-generation languages are high-level languages in
e

e
component and the interface between them is tested. errors.
∑ Modern-day computers are based on the principle of the which instructions are written in statements like English
iv

iv
stored program concept, which was introduced by sir language statements. Each instruction in this language Linker error Errors that may occur when the linker is not able Unit testing A testing technique applied only on a single
John van Neumann in the late 1940s. expands into several machine language instructions. to find the function definition for a given prototype unit or module to ensure whether it exhibits the expected
Un

Un
∑ Application software is designed to solve a particular ∑ Fourth-generation languages are non-procedural Logical errors Errors that result in unexpected and undesirable behaviour.
problem for users. languages in which programmers define only what they
∑ System software represents programs that allow the want the computer to do, without supplying all the details
d

d
hardware to run properly. It acts as an interface between of how it has to be done.
EXERCISES
or

or
the hardware of the computer and the application • In requirements elicitation phase, users’ expectations are
software that users need to run on the computer. gathered to know why the program/software has to be
xf

xf
∑ The key role of BIOS is to load and start the operating built. Fill in the Blanks an ________, and ________.
11. In _______ phase user’s expectations are collected and
O

O
system. The code in the BIOS chip runs a series of tests • Course of actions is planned in the design phase. 1. ________ tells the hardware what to do and how to do
called POST (Power On Self Test) to ensure that the system • An algorithm provides a blueprint to writing a program to it. documented.
devices are working correctly. BIOS is stored on a ROM solve a particular problem. 2. The hardware needs a ________ to instruct what has to 12. The documented requirements act as an input to the
chip built into the system. • The time complexity of an algorithm is basically the be done. _____ phase.
∑ Utility software is used to analyse, configure, optimize, running time of a program as a function of the input size. 3. The process of writing a program is called _______. 13. Modularization of the program is done in ______ phase.
and maintain the computer system. Similarly, the space complexity of an algorithm is the 4. ________ is used to write computer software. 14. A conditional or decision symbol is represented using a
∑ A compiler is a special type of program that transforms amount of computer memory that is required during the 5. ________ transforms the source code into binary _______.
source code written in a programming language (the program execution as a function of the input size. language. 15. _______ phase is also called construction or code
source language) into machine language comprising of • A flowchart is a graphical or symbolic representation of a 6. ________ allows a computer to interact with additional generation phase.
just two digits—1s and 0s (the target language). The process. hardware devices such as printers, scanners, and video 16. _______ errors may terminate program execution.
resultant code in 1s and 0s is known as the object code. • A pseudocode is a compact and informal high-level cards. 17. Debugging is an activity that includes _______ and
∑ Linker is a program that combines object modules to form description of an algorithm that uses the structural 7. ________ helps in coordinating system resources and _______.
an executable program. conventions of a programming language. allows other programs to execute. 18. Structured programming follows a _______ approach
∑ A loader is a special type of program that copies programs • In the implementation phase, the designed algorithms 8. ________ provides a platform for running application for problem solving.
from a storage device to main memory, where they can be are converted into program code using any of the high software.
19. ________ concept was introduced by sir John van
executed. level languages. 9. ________ can be used to encrypt and decrypt files.
Neumann in the late 1940s.
10. An assembly language statement consists of a ________,

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 21 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 22 31/07/18 5:17 PM


Introduction to Programming 23 24 Programming in C

Multiple Choice Questions 12. In which phase are algorithms, flowcharts, pseudocodes 13. Start and end symbols are also known as the terminal 16. Can a program written in a high-level language be
prepared? symbols. executed without a linker?
1. BIOS is stored in
(a) Requirements analysis 14. A decision symbol in a flowchart cannot have more than 17. Give a brief description of generation of programming
(a) RAM (b) ROM
(b) Design two arrows. languages. Highlight the advantages and disadvantages
(c) Hard disk (d) None of these
(c) Implementation 15. Variable declarations are not included in the psuedocode. of languages in each generation.
2. Which language should not be used for organizing large
(c) Testing 16. Logical errors are detected by the compiler. 18. What are the advantages of modularization?
programs?
13. Algorithms should be 19. Briefly explain the phases in software development project.
(a) C (b) C++
(a) Precise (b) Unambiguous Review Questions 20. Explain the significance of an algorithm.
(c) COBOL (d) FORTRAN
(c) Clear (d) All of these 1. Broadly classify the computer system into two parts. 21. What are the features of an ideal algorithm?
3. Which language is a symbolic language?
14. To check whether a given number is even or odd, you Also make a comparison between a human body and 22. What are the different control structures that are
(a) Machine language (b) C will use which type of control structure? the computer system thereby explaining what each part frequently used while writing algorithms?
(c) Assembly language (d) All of these (a) Sequence (b) Decision does. 23. Why is it recommended to draw a flowchart before
4. Which language is a 3GL? (c) Repetition (d) All of these 2. Differentiate between computer hardware and software. implementing a program?
(a) C (b) COBOL 15. Which among the following is represented using a 3. Define programming. 24. Explain the significance of different symbols used in a

s
(c) FORTRAN (d) All of these rectangle? flowchart.

es

es
4. Define source code.
(a) Terminal symbols (b) Processing steps 25. What do you understand by a pseudocode?
5. Which language does not need any translator? 5. What is booting?
(c) Input/output symbols (d) Decision symbol 26. Is it permissible to use keywords in a pseudocode?

Pr

Pr
(a) Machine language (b) 3GL 6. What criteria are used to select the language in which
16. Trying to open a file that already exists, will result in Justify your answer.
(c) Assembly language (d) 4GL which type of error? the program will be written?
27. What factors determine the efficiency of an algorithm?
ity

ity
6. Choose the odd one out. (a) Run time (b) Compile time 7. Explain the role of operating system.
28. Testing is an unavoidable phase in software development
(a) Compiler (b) Interpreter (c) Linker error (d) Logical error 8. Give some examples of computer software. life cycle. Comment.
rs

rs
(c) Assembler (d) Linker 17. Which among the following is an ongoing activity in 9. Differentiate between the source code and the object 29. What are the different types of errors which frequently
7. Which one is a utility software? software development? code. occur in programs?
e

e
(a) Word processor (a) Requirements analysis 10. Why are compilers and interpreters used? 30. Differentiate between syntax and semantic errors.
iv

iv
(b) Implementation 11. Is there any difference between a compiler and an
(b) Antivirus 31. Differentiate between unit test, integration test, and
Un

Un
(c) User training interpreter? system test.
(c) Desktop publishing tool
(d) Maintenance 12. What is application software? Give examples. 32. What are the different techniques for debugging a
(d) Compiler
13. What is BIOS? computer program?
8. POST is performed by State True or False
d

d
14. What do you understand by utility software? Is it a must 33. Suppose you are given a problem to find all composite
(a) Operating system (b) Assembler
or

or
1. Computer hardware does all the physical work. to have it? numbers in range provided by users. Perform all the
(c) BIOS (d) Linker phases of software development on this problem.
2. The computer hardware cannot think and make 15. Differentiate between syntax errors and logical errors.
xf

xf
9. Printer, monitor, keyboard, and mouse are examples of decisions on its own.
(a) Operating system 3. A software is a set of instructions that are arranged in a
O

O
(b) Computer hardware sequence to guide a computer to find a solution for the
(c) Firmware given problem.
(d) Device drivers 4. Word processor is an example of educational software.
10. Windows VISTA, Linux, Unix are examples of 5. Desktop publishing system is a system software.
(a) Operating system 6. BIOS defines firmware interface.
(b) Computer hardware 7. Pascal cannot be used for writing well-structured
programs.
(c) Firmware
8. Assembly language is a low-level programming language.
(d) Device drivers
9. Operation code is used to identify and reference
11. The functionality, capability, performance, availability of
instructions in the program.
hardware and software components are all analysed in
which phase? 10. 3GLs are procedural languages.
(a) Requirements analysis 11. Each phase in software development has a well-defined
set of tasks to be performed.
(b) Design
12. Course of actions is planned in requirements analysis
(c) Implementation
phase.
(d) Testing

© Oxford University Press. All rights reserved. © Oxford University Press. All rights reserved.

11011_Programming in C AICTE.indb 23 31/07/18 5:17 PM 11011_Programming in C AICTE.indb 24 31/07/18 5:17 PM

You might also like