CS101Lecture_Notes
CS101Lecture_Notes
A computer can be formally defined as a device which works under the control of a stored
program, automatically accepting and processing data to produce information which is the result
of that processing. In this line, computer science is concerned with the application of scientific
principles to the design, construction and maintenance of systems based upon the use of
computers. It therefore includes a study of what computers are, how they work and how they are
used.
1
1.2 THE EVOLUTION OF COMPUTER SYSTEMS
Most modern Computers are based upon general design principles which were established during
the 1940s and which have not changed greatly since then. In striking contrast, changes in
technology have revolutionized the ways in which Computers are made. The origins of
Computers can be stressed to the ancient times when different methods were used to represent and
store data. For example, the herdsmen used pebbles, sticks, or scratches on stones to count and
represent the number of animals in their care. The use of pebbles was latter on replaced with
stylized pictures or symbols to represent objects, numbers and ultimately languages. Such
representations provided a means of storing information for subsequent retrieval and use.
The first true calculating (adding) machine, a precursor of the digital computer, was devised in
1642 by the French philosopher and mathematician Blaise Pascal.. This device employed a series
of ten-toothed wheels, each tooth representing a digit from 0 to 9. The wheels were connected so
that numbers could be added to each other by advancing the wheels by a correct number of teeth.
It consisted of a series of six numbered dials and a ratchet ‘carry” mechanism. Multiplication and
division using this device were quite slow and laborious. On the other hand addition and
2
subtraction were straight forward. In the 1960s Pascal’s contribution to computing was
recognized when a renowned mathematician professor Niklaus Wirth of Zurich named his new
programming language “ Pascal” after Blaise Pascal. The laborious processes in multiplication
and division experienced using Pascal’s device was simplified when a German mathematician,
Gottfried Von Leibniz invented a calculating machine capable of true multiplication and
division in 1671. The machine was a development of Pascal’s idea. The new feature was a shift
mechanism. Pascal had already devised a method of number complements for use in subtraction.
Early in the nineteenth century, a French textile manufacturer made a brilliant imaginative efforts.
Between 1802 and 1804 the French inventor Joseph Marie Jacquard perfected a mechanical
means of automatically controlling weaving looms to facilitate the production of woven cloth
with complex patterns. The machine, called “ the Jacquard loom”, was programmed by means of
special punched cards which stored information about the required patterns in the cloth. These
punched cards were strung tightly together side by side in a long continuous strip. They were
automatically fed through a loom mechanism in sequence with the purpose of controlling the
loom’s weaving action. It is generally accepted that Jacquard’s loom was the start of a chain of
developments which led to the robot operated factory production lines of today. Jacquard’s work
had led also to the automation of calculations. Within a few years of Jacquard’s invention, a
professor of mathematics at Cambridge University, Charles Babbage in 1822 demonstrated a
small working model of his “Difference Engine” to the Royal Society. Babbage’s demonstration
won him government backing who wished to produce a larger machine able to generate reliable
astronomical and mathematical tables containing values accurate to 20 decimal places. The
machine was never completed because of mechanical difficulties. In 1884 Babbage designed and
developed the concept of an “Analytic Engine”. It was essentially a general purpose automatic
calculator. Its design owed much to Jacquard’s invention and incorporated many features present
in modern computers inter alia
1) Data and program instructions fed in via a device using a suitable medium (punched cards)
2) Storage facilities for data and instructions
3) A mechanized unit for calculation- a ”mill”
4) A suitable output device.
3
An amateur mathematician and friend or associate of Babbage produced supporting material for
the analytic engine in the form of programs and explanatory documentation. This was a woman
called Lady Ada lovelace, 1815-52 ( the British mathematician Augusta Ada Byron). She was the
daughter of the English poet Lord Byron. Arguably she is considered to be the first programmer.
Many considered Babbage and Lady lovelace to the true inventors of the modern digital
computer. The programming language “ada” has been named after her. The technology of their
time was not capable of translating their sound concepts into practice; but one of their inventions,
the Analytical Engine, had many features of a modern computer as already stated above.. It was
mentioned that it had a an input stream in the form of a deck of punched cards, a “store” for
saving data, a “mill” for arithmetic operations, and a printer that made a permanent record.
Between 1847 and 1854 George Boole, an English Logician devised an algebraic system, now
called “Boolean Algebra”. It was an important theoretical development. The Boolean Algebra is
used for representing and manipulating logical expressions. As at his time the full significance of
the developments was not realized. Between 1880 and 1890 U.S. census bureau had a problem of
completing the census count. The next census was scheduled for 1890. Dr Herman Hollerith who
was a census statistician at the U.S. census bureau in the mid 1880’s proposed a mechanized
solution to the problem. This solution was based upon equipment handling punched cards. His
idea was to ‘code’ the data by representing it by punched hole combinations on the cards. The
devices called tabulators were able to process the data by detecting holes in the cards. Electrical
contacts brushed the cards and made contact through the device. The tabulators were also used for
semi-automatic selection and sorting of cards. Hollerith discovery had a very positive impact.
This was glaring as the census of 1880 on t50 million citizens had taken over 7 years to complete,
the census of 1890 on 63 million citizens with Hollerith device took only 3 years to complete.
Later in the years with other developments continued in the commercial application of the
machines by Babbage and others Hollerith set up the computing Tabulating Recording company.
This company later became the International Business Machines Corporation (IBM).
4
later, electrical analog computing systems were used as torpedo course predictors in submarines
and as bombsight controllers in aircraft. Another system was designed to predict spring floods in
the Mississippi River basin.
In the 1940s, Howard Aiken, a Harvard University mathematician, created what is usually
considered the first digital computer. This machine was constructed from mechanical adding
machine parts. The instruction sequence to be used to solve a problem was fed into the machine
on a roll of punched paper tape, rather than stored in the computer. In 1945, however, a computer
with program storage was built, based on the concepts of the Hungarian-American mathematician
John von Neumann. The instructions were stored within a so-called memory, freeing the
computer from the speed limitations of the paper tape reader during execution and permitting
problems to be solved without rewiring the computer.
When the architecture for a computer was first proposed by John von Neumann , he visualized the
machine as a fast calculating device. He suggested a five- unit system for the computer:
1) Input Unit; 2) Output Unit; 3) Memory; 4) Arithmetic Logic Unit; and 5) Control Unit.
Over the past forty years or so, dramatic increases in computing speeds were achieved, largely
due to the use of inherently fast electronic components. The memory and arithmetic logic units
were designed by semiconductor devices first. Thus the “first generation” computers were valve
based machines based upon Von Neumann design principles.
5
basic techniques he had developed were used in this computer.) called ENIAC, for Electronic
Numerical Integrator And Computer, the device contained 18,000 vacuum tubes and had a speed
of several hundred multiplications per minute. Its program was wired into the processor and had
to be manually altered.
The use of the transistor in computers in the late 1950s marked the advent of smaller, faster, and
more versatile logical elements than were not possible with vacuum-tube machines. Because
transistors use much less power and have a much longer life, this development alone was
responsible for the improved machines called second –generation computers. Components
became smaller, as did intercomponent spacings, and the system became much less expensive to
build. During the second generation, manufacturers moved towards making computers of
modular construction. A suitable combination of processing, storage, input and output units
could be assembled from a range of possible modules in order to meet the particular needs of each
customer. Also at that time there were major advances in computers language away from codes
directly usable by the machine(i.e. machine language) and towards the ‘natural’ languages of
English and mathematics. The first of the “high level languages” called FORTRAN( FORmula
TRANslation) was released in 1957.
In the early and mid-1970s the circuit integration technology made great strides with
microprocessor become a reality in the mid-1970s with the introduction of the large scale
6
integrated(LSI) circuit and, later the very large scale integrated(VLSI) circuit, with many
thousands of interconnected transistors etched into a single silicon substrate. The
microprocessor, invented by TED HOFF of the Intel Company Laboratory, in 1971, was a major
breakthrough in VLSI technology. The computers designed using microprocessors are called
microcomputers. The microcomputers and other computers that use VLSI circuit design are
called “fourth-generation” computers.
In 1974, ED Roberts, of MIT, built a microcomputer which he called Altair. It was the first
personal computer(PC). Then Apple Macintosh and IBM PCs entered the market. They were very
fast and efficient in handling data. The Pentium is a 64-bit processor.
The development of processors that can handle 16, 32, and 64 bits of data at a time has increased
the speed of computers. The complete collection of recognizable patterns- the total list of
operations- of which a computer is capable is called its instruction set. Both factors- number of
bits at a time, and size of instruction sets- continue to increase with the ongoing development of
modern digital computers.
A Japanese team of scientists thought that for satisfying the computing needs of future society in
the field of artificial intelligence, the capabilities of computers with the present architecture
would be inadequate. In 1979, the Japanese government appointed a committee headed by Tohru
Moto Oka, to envisage the computing needs of society in the 1990s. The committee consisted of
three subcommittees. The first studied the type of computer needed in the future. The second
7
studied the architecture of the computer needed. The third worked on the fundamental concepts
of the future computer. These three subcommittees submitted their proposals, and chairman Oka
formulated the final proposal for the future computers, which came to be known as the “ fifth-
generation” computer. The fifth-generation computers when they come to the market they will
not be effective for ordinary applications. However, they will be used for Information
Management, natural language processing, Speech, Character and Image Recognition, and other
artificial intelligence applications. The architecture of fifth-generation computers will be entirely
different from that of present-day computers of Von Neumann architecture. The data and
instructions in fifth-generation computers are stored in computer’s memory. Whenever processing
has to take place, data are retrieved from memory. If we consider any of our day-to-day activities,
a similar procedure is followed by almost all of us.
8
by John Presper Eckert (1919-1995) and John W. Mauchly (1907-1980), ENIAC, unlike the
Colossus and Mark I, was a general-purpose computer that computed at speeds 1,000 times faster
than Mark I.
In the mid-1940's John von Neumann (1903-1957) joined the University of Pennsylvania team,
initiating concepts in computer design that remained central to computer engineering for the next
40 years. Von Neumann designed the Electronic Discrete Variable Automatic Computer
(EDVAC) in 1945 with a memory to hold both a stored program as well as data. This "stored
memory" technique as well as the "conditional control transfer," that allowed the computer to be
stopped at any point and then resumed, allowed for greater versatility in computer programming.
The key element to the von Neumann architecture was the central processing unit, which allowed
all computer functions to be coordinated through a single source. In 1951, the UNIVAC I
(Universal Automatic Computer), built by Remington Rand, became one of the first commercially
available computers to take advantage of these advances. Both the U.S. Census Bureau and
General Electric owned UNIVACs. One of UNIVAC's impressive early achievements was
predicting the winner of the 1952 presidential election, Dwight D. Eisenhower.
First generation computers were characterized by the fact that operating instructions were made-
to-order for the specific task for which the computer was to be used. Each computer had a
different binary-coded program called a machine language that told it how to operate. This made
the computer difficult to program and limited its versatility and speed. Other distinctive features
of first generation computers were the use of vacuum tubes (responsible for their breathtaking
size) and magnetic drums for data storage.
9
contained all the components we associate with the modern day computer: printers, tape storage,
disk storage, memory, operating systems, and stored programs. One important example was the
IBM 1401, which was universally accepted throughout industry, and is considered by many to be
the Model T of the computer industry. By 1965, most large business routinely processed financial
information using second generation computers.
It was the stored program and programming language that gave computers the flexibility to finally
be cost effective and productive for business use. The stored program concept meant that
instructions to run a computer for a specific function (known as a program) were held inside the
computer's memory, and could quickly be replaced by a different set of instructions for a different
function. A computer could print customer invoices and minutes later design products or calculate
paychecks. More sophisticated high-level languages such as COBOL (Common Business-
Oriented Language) and FORTRAN (Formula Translator) came into common use during this
time, and have expanded to the current day. These languages replaced cryptic binary machine
code with words, sentences, and mathematical formulas, making it much easier to program a
computer. New types of careers (programmer, analyst, and computer systems expert) and the
entire software industry began with second generation computers.
10
computer manufacturers sought to bring computers to general consumers. These minicomputers
came complete with user-friendly software packages that offered even non-technical users an
array of applications, most popularly word processing and spreadsheet programs. Pioneers in this
field were Commodore, Radio Shack and Apple Computers. In the early 1980's, arcade video
games such as Pac Man and home video game systems such as the Atari 2600 ignited consumer
interest for more sophisticated, programmable home computers.
In 1981, IBM introduced its personal computer (PC) for use in the home, office and schools. The
1980's saw an expansion in computer use in all three arenas as clones of the IBM PC made the
personal computer even more affordable. The number of personal computers in use more than
doubled from 2 million in 1981 to 5.5 million in 1982. Ten years later, 65 million PCs were being
used. Computers continued their trend toward a smaller size, working their way down from
desktop to laptop computers (which could fit inside a briefcase) to palmtop (able to fit inside a
breast pocket). In direct competition with IBM's PC was Apple's Macintosh line, introduced in
1984. Notable for its user-friendly design, the Macintosh offered an operating system that allowed
users to move screen icons instead of typing instructions. Users controlled the screen cursor using
a mouse, a device that mimicked the movement of one's hand on the computer screen.
As computers became more widespread in the workplace, new ways to harness their potential
developed. As smaller computers became more powerful, they could be linked together, or
networked, to share memory space, software, information and communicate with each other. As
opposed to a mainframe computer, which was one powerful computer that shared time with many
terminals for many applications, networked computers allowed individual computers to form
electronic co-ops. Using either direct wiring, called a Local Area Network (LAN), or telephone
lines, these networks could reach enormous proportions. A global web of computer circuitry, the
Internet, for example, links computers worldwide into a single network of information. During the
1992 U.S. presidential election, vice-presidential candidate Al Gore promised to make the
development of this so-called "information superhighway" an administrative priority. Though the
possibilities envisioned by Gore and others for such a large network are often years (if not
decades) away from realization, the most popular use today for computer networks such as the
Internet is electronic mail, or E-mail, which allows users to type in a computer address and send
messages through networked terminals across the office or across the world.
1.3.5 Fifth Generation (Present and Beyond)
Defining the fifth generation of computers is somewhat difficult because the field is in its infancy.
The most famous example of a fifth generation computer is the fictional HAL9000 from Arthur
C. Clarke's novel, 2001: A Space Odyssey. HAL performed all of the functions currently
envisioned for real-life fifth generation computers. With artificial intelligence, HAL could reason
well enough to hold conversations with its human operators, use visual input, and learn from its
own experiences. (Unfortunately, HAL was a little too human and had a psychotic breakdown,
commandeering a spaceship and killing most humans on board.)
Though the wayward HAL9000 may be far from the reach of real-life computer designers, many
of its functions are not. Using recent engineering advances, computers may be able to accept
spoken word instructions and imitate human reasoning. The ability to translate a foreign language
is also a major goal of fifth generation computers. This feat seemed a simple objective at first, but
11
appeared much more difficult when programmers realized that human understanding relies as
much on context and meaning as it does on the simple translation of words.
Many advances in the science of computer design and technology are coming together to enable
the creation of fifth-generation computers. Two such engineering advances are parallel
processing, which replaces Von Neumann's single central processing unit design with a system
harnessing the power of many CPUs to work as one. Another advance is superconductor
technology, which allows the flow of electricity with little or no resistance, greatly improving the
speed of information flow. Computers today have some attributes of fifth generation computers.
For example, expert systems assist doctors in making diagnoses by applying the problem-solving
steps a doctor might use in assessing a patient's needs. It will take several more years of
development before expert systems are in widespread use.
A summary of the computer generations characteristics and features is as follows:
1ST GENERATION 2ND GENERATION 3RD G ENERATION 4TH GENERATION 5TH GENERATION
(1951-1958) (1959-1963) (1964-1958) (1979-PRESENT)
SIZE(Typical Room size Closet size Desk-size Desktop and Laptop Credit card-size
Computers) Mainframe mainframe Minicomputer Micro?
CIRCUITRY Vacuum tubes Transistors Integrated semi- Large-Scale(LSI) Very-Large-Scale
conductor circuit Semi-Conductor Integrated(VLSI)
circuits superconductor
circuits?
DENSITY(Circuits One Hundreds Thousands Hundreds of Millions?
per component) Thousands
SPEED(Instruction Hundreds Thousands Millions Tens of Millions Billions?
s/Second)
RELIABILITY(Fai Hours Days Weeks Months Years?
lure of Circuits)
MEMORY(Capacit Thousands Tens of Thousands Hundreds of Millions Billions?
y in characters) Thousands
COST(Per million $10(N1440) $1.00(1440) $0.10 $0.001 $0.0001?
instructions)
12
CHAPTER TWO: COMPUTER COMPONENTS
A Computer System is the integration of physical entities called hardware and non-physical
entities called software. Hardware is the physical components (electronic and
electromechanical) of the computer, such as the memory, the central processing unit (CPU), and
input/output devices. Software refers to the sets of instructions (programs) that direct the
computer to perform operations to process data. Software therefore, is used generally to describe
all the various programs which may be used on a computer system together with their associated
documentation. For a data to become information, both the hardware and software must work
together.
2.1 HARDWARE
In what follows we are looking at the computer in terms of a set of basic elements each with a
specific function. The basic elements which make up a computer system are as follows.
13
2.1.1 Input Devices
Computers need to receive data and instructions in order to solve any problem. Therefore we need
to put the data and instructions into the computer. The input unit consists of one or more input
device. The keyboard and mouse of a computer are the most commonly used input devices.
However there are other input devices such as Scanner, Optical Mark Reading and
Recognition(OMR), digitizers, Magnetic Ink Character Recognition (MICR), Light Pen etc.
Key Board
The most common input device is the Keyboard. It is used to input letters, numbers, and
commands from the user.
Mouse
Mouse is a small device held in hand and pushed along a flat surface. It can move the cursor in
any direction. In a mouse a small ball is kept inside and the ball touches the pad through a hole at
the bottom of the mouse. When the mouse is moved, the ball rolls. This movement of the ball is
converted into electronic signals and sent to the computer. Mouse is very popular in the modern
computers that use Windows and other Graphical User Interface (GUI) applications.
14
ink characters. This method eliminates the need to manually enter data from cheques into a
floppy. Besides saving time, this method ensures accuracy of data entry and improves security.
15
The advantage of this method is that information is entered at its source and no further
transcription is required.
Barcode Reader
In this method, small bars of varying thickness and spacing are printed on packages, books,
badges, tags etc., which are read by optical readers and converted to electrical pulses. The patterns
of bars are unique and standardized. For example, each grocery product has been given unique
10-digit code and this is represented in bar code form on every container of this product.
16
Speech Input Unit
A unit, which takes spoken words as its input, and converts them to a form that can be understood
by a computer is called a speech input unit. By understanding we mean that the unit can uniquely
code (as a sequence of bits) each spoken word, interpret the word and initiate action based on the
word.
17
called a Working Storage area and an area being used for data awaiting processing or output is
called a buffer area
Each location in main storage consists of a set of devices called bits each of which can be in one
of two states at any one time (e.g. ON or OFF). The two states of each device are used to
represent binary 0(OFF) and 1(ON). This complete set of two-state bits in each location is used to
code data. Bits therefore is a system of representing data by the binary digits “0” and “1”. BITS
means Binary digITS . Each location in main storage is said to hold a unit of data called a word.
Words are then subdivided into smaller units called bytes. A byte consists of 8 bits long.
The main storage is of two types. The Random Access Memory(RAM) and the Read Only
Memory(ROM). As the name implies, data can be access from any location with going through
the locations serially. RAM is subdivided into Static and Dynamic RAMS. RAM memory is
volatile(i.e. data is lost if power supply is removed or tuned off). The ROM is non-volatile(i.e no
data is lost when power supply is turned off). Here all cells states are set permanently during
18
manufacture. A set of instructions stored in this way is said to be “hard-wired”, and is often called
firmware.
PROM(Programmable Read Only Memory). In contrast to normal ROM, in which the pattern of
stored data is permanently incorporated into the chip. The PROM can be programmed by the user
of PROM. However, the data is held permanently once the PROM has been programmed.
EPROM(Erasable Programmable Read Only Memory). It is like PROM but has the advantage
that it may be erased and reprogrammed.
EAROM(Electrically Alterable Read Only Memory). These memories can be read, erased and
rewritten without removing them from the computer.
Cache Memory is a temporary holding area for data which is currently subject to repeated access.
The processor can access this data more quickly and there is therefore an overall speed
improvement. The cache effectively sits between main storage and the processor acting as a
holding area through which data and instruction pass.
Main storage has several names such as Immediate access Memory, internal storage, primary
storage, or core storage. The main storage size is mostly described in terms of kilobytes. (K= 210
= 1024 bytes).e.g. 32K words = 32 x 1024 words. 1000K is written as M for Mega. 1000000K is
written as G for Giga. Note that computers with longer word lengths operate faster then
computers with shorter word lengths because data and instructions can be moved in out of main
storage in bigger units.
In addition to the main storage is the backing storage provided for the mass storage of programs
and files, i.e. those programs and files not currently being operated on but which will be
transferred to the main storage when required. Although data in the form of files held on backing
storage is not immediately accessible as it would be if held in main storage, it is nevertheless
within the computer system. Ideally, all data for processing is suppose to be stored in main
storage so that all internal operations can be carried out at maximum speed, but because main
19
storage is relatively expensive it is therefore only used for storing the necessary instructions and
the data currently being operated on.
Some examples of backing storage are: magnetic tape .magnetic disk ,magnetic diskette(floppy
disk),optical disk, etc. The backing storage is also known as the auxiliary storage. It is to
supplement main storage. The main auxiliary storage media are in magnetic form. The magnetic
disks can e on-line(being accessible to and under the control of the processor) or off-line(not
accessible to or under the control of the processor).
It is the main part of a computer system like the heart of a human being. It interprets the
instructions in the program and executes one by one. It consists of three major units.
Control Unit: This is the component of the CPU which fetches instructions from main storage,
interprets them, and issues the necessary signals to the components making up the system,
depending on the type of instruction. It controls the actions of the other components so that
instructions are executed in the correct sequence.
Arithmetic and Logic Unit (ALU): This is the component that performs Arithmetic operations
like (+,-,*,^,/), logical operations like (AND, OR, NOT) and relational operations like
(<,>,<=,>=) on data.
Registers: registers are high-speed storage areas where instructions/data are temporarily stored
before execution.
Between any 2 parts of the CPU is a pathway, called internal bus, which allows for the transfer
of binary information between them. On the other hand, the CPU is connected by external buses
to other parts of the computer. A bus is basically a collection of parallel conducting lines (or
wires).
20
The functions of the CPU are
21
A CRT monitor Figure 5.7 (a)
Printer
The printer presents information on paper. Such information on paper is called hard copy. All
printers can print out information in form of text, many can produce drawings and graphics and
22
some can produce colour images.
There are many types of printer with different technologies. As a result, printers differ in the
mechanisms they use to print out images. Some printers are hereby presented.
23
An Ink Jet Printer Figure 5.11
Laser Printer
The laser printer is the best in terms of quality printing. It has a working mechanism similar to
that of a photocopying machine. Charged toner (Carbon Powder) is electro-statically attracted and
transferred into paper by the oppositely charged drum. The toner is then fused into the paper
texture by means of heat and pressure. The laser printer produces a whole page at a time, and is
therefore known as a page printer. Other printers discussed earlier are known as line printers.
24
A Laser Printer Figure 5.12
The programs and data the computer needs at any given moment are read into the main memory
while the rest are stored on auxiliary storage devices. Apart from that, the main memory only
holds data temporarily (i.e. it is volatile), but secondary storage devices hold data permanently. If
you edit a document on a computer, you have to save it on a secondary storage device, before
switching off the computer, else you will lose the document.
Another advantage of secondary storage devices is that they have higher storage capacity than
main memory, and therefore hold more data. However, the main memory is much faster in terms
of access speed.
The most common secondary storage media are the magnetic disk, magnetic tape and the compact
disk.
25
DID YOU KNOW?
That auxiliary storage device permanently hold programs and data not
needed by the computer at any given time.
Magnetic Disk(MD)
As the name implies, a magnetic disk is a round, flat object whose surfaces are coated with a
magnetic material (ferric oxide). Read/Write heads, which are similar to the heads of a tape
recorder float above and below the disk near its surfaces as it spins around its center. The MD
usually has concentric tracks, on which data item as are stored. These tracks are further
sub-divided into sectors as seen in fig.17.
Data items stored on the disk can be accessed directly, hence the magnetic disk is referred to as a
direct access storage medium. Like other magnetic media, the magnetic disk should be kept away
from strong magnetic fields. The device that hold the disk and carries out read/Write operations
is called a disk drive. There two types of magnetic disk:
- The Floppy Disk
- The Hard Disk
For a diskette to be accessed by the computer it has to be placed in a device called a floppy disk
drive (of course each of the diskettes mentioned earlier has a drive that matches its size). The
floppy disk drive (FDD) has two movable read/write magnetic heads for reading and writing data
on both sides of the disk, one on each surface. The diskette is suitable for transferring data and
programs from one computer to another, and for making backup copies of data on the hard disk.
Most personal computers have one or two floppy disk drives and a hard disk drive (HDD). The
FDD is usually labeled “A” and if there is a second one it is labeled “B”.
26
A 31/2 inch floppy disk
Figure 5.15
Hard Disk
The hard disk (also called Winchester) consists of several rigid concentric metallic disks coated
with a magnetic material. The disks are attached to a central spindle which revolves at a high
speed. The hard disk is permanently fixed to the Hard Disk Drive (HDD) and therefore cannot be
removed like the diskette. The hard disk drive has several read/write heads i.e one for each
surface. In order to protect it form dirt., the HDD is sealed.
The hard disk has a longer storage capacity (several gigabytes) and a higher data transfer rate
(10 MB per second) than the diskette.
The hard disk permanently stores programs and data used by the computer.
27
A Hard Disk Figure 5.16
Magnetic Tape
The magnetic tape is a thin plastic material, which can be magnetized to store data.
Data items are stored on the magnetic tape sequentially (i.e one after the other) and that makes it
to be referred to as a sequential access medium. As a result, the magnetic tape has a long access
time, and is therefore not suitable for storing data files that are used frequently.
Such data are better stored on direct access media like the magnetic disk, where access to data is
much faster.
However, the magnetic tape is inexpensive and can store large quantities of data. It is therefore
used as a back-up storage medium. The capacity of the magnetic tape depends on its length and
storage density.
Although mainly found with large computers, magnetic tapes can be used with all types of
computers.
28
A Magnetic Tape Figure 5.17
Cassette
The cassette is a plastic case containing a magnetic tape and resembles the cassette used for audio
recording. Cassette tapes are inexpensive, but cannot hold much data, and access to data stored on
them is fairly slow. Cassette tapes are commonly used with personal computers.
29
CD ROM
It stands for Compact Disc Read Only Memory. This means that data/information stored on the
disk are permanently stored and can only be accessed(read) but no data can be written to it. The
cells of the disk are set permanently during manufacture. However, there are ReWritable CDs
(CD-RW), which look almost like a CD-ROM and are distinguishable from CD-ROM discs by
their metallic gray color. They act like CD-ROM during reading, but also allow data recording for
thousands of times.
30
CHAPTER THREE: TYPES OF COMPUTERS
3.1 THE MAIN TYPES OF COMPUTER
Two main types of computers are in use today, analog and digital, although the term computer is
often used to mean only the digital type. Analog computers exploit the mathematical similarity
between physical interrelationships in certain problems, ands employ electronic or hydraulic
circuits to simulate the physical problem. Digital computers solve problems by performing sums
and dealing with each number digit by digit.
Installations that contain elements of both digital and analog computers are called hybrid
computers. They are usually used for problems in which large numbers of complex equations,
known as time integrals, are to be computed. Data in analog form can also be fed into a digital
computer by means of analog-to-digital converter, and the same is true of the reverse situation.
An example of hybrid computer is the missile projector.
31
second. A computer with a “ clock speed” of 33mHz is capable of executing 33 million discrete
operations each second. Business microcomputers can perform 60 to 100 million operations per
second, and supercomputers used in research and defense applications attain speeds of billions of
cycles per second. For example ,Personal Computers- laptop, desktop, etc.
Digital computer speed and calculating power are further enhanced by the amount of data handled
during each cycle. If a computer checks only one switch at a time, that switch can represent only
two commands or numbers; thus ON would symbolize one operation or number, and OFF would
symbolize another. By checking groups of switches linked as a unit, however, the computer
increases the number of operations it can recognize at each cycle. For example, a computer that
checks two switches at one time can represent four numbers( 0 to 3) or can execute one of four
instructions at each cycle, one for each of the following switch patterns: OFF-OFF(0); OFF-
ON(1); ON-OFF(2); or ON-ON(3).
Counting on ones fingers is probably the simplest digital operation we all know. Digital watches
have special tiny digital computers within them.
3.2.2 Mainframes. Large general purpose computers with extensive processing, storage and
input/output capabilities. It is expensive with the capability of serving the needs of major business
enterprises, governments, scientific research establishments, or the like. They are usually multi-
user systems accommodating hundreds of users at a time with each having his terminal(monitor
and keyboard).
32
3.2.3 Minicomputers Physically smaller computers compared with mainframes. They are used
for special purposes or smaller scale general purpose work e.g. VAX range. It is an appliance-
sized computer, generally too expensive for personal use, with capabilities suited to a business,
school, or laboratory.
33
CHAPTER FOUR: COMPUTER SOFTWARE AND DATA
4.1 SOFTWARE
We defined software earlier as the general term used to describe all the various programs which
may be used on a computer system together with their associated documentation. A computer
hardware is just like the dead body. It is the software that breathes life into it to perform
function(S). There are two main classes of software:
4.1.2 Application Software. This is software designed for specific practical use. This may be
further sub-divided into
a) Specialist applications software i.e. programs with associated documentation specifically
to carry out particular tasks e.g., solving sets of mathematical problems (scientific
workplace, mathematica, matlab, etc)
b) Application packages, i.e., suites of programs with documentation, used for a particular
type of problem. For example, Word processors(e.g. Microsoft Word, WordPerfect, etc),
34
Spreadsheets(Microsoft Excel, Lotus 1-2-3, etc), Desktop publishing software (Microsoft
PageMaker) Presentation software( e.g. PowerPoint), payroll packages.
For data to become information instructions have to be laid down and obeyed. A set of
instructions which describe the steps to be followed in order to carry out an activity is called an
algorithm or procedure. In other words, an algorithm is a step by step way of solving a problem.
If the algorithm is written in the computer language then the set of instructions is called a
program. The task of producing computer program involves going through several stages not all
of which involve writing in the computer’s own language. The complete task is called
programming. Programs consist of sequences of instructions specifying controlled and ordered
operations on data which are to be performed by a computer.
Integers are the positive and negative whole numbers, and zero. The positive integers are called
the Natural Numbers. Or Cardinal Values. They are also called “Unsigned integer”(1,2,3,…).
Real Numbers are all the numbers on the number scale(including those between the integers).
They include all the integers and all the fractions. The usual way of representing real numbers is
to write the number with the decimal point fixed in its correct position e.g. 13.75. This is fixed
point representation. On the other hand the decimal points can be moved or floated along the
digits to position it between the first and second nonzero most significant digits. This is called the
35
Floating point Representation of Real Numbers. There are three components to a floating point
representation.
1. the mantissa sometimes called the argument
2. the radix or base
3. the exponent sometimes called the characteristic.
e.g. 1.375 x103 here 1.375 is the mantissa or argument; 10 is the base or radix; 3 is the exponent.
Note: 1.3753 handwritten has a computerised version as +1.375 E + 3 and 3.8624-7 is +3.8624E-7.
Characters. Sequences of characters such as “James”, or “Alex” treated as single data is called
character Strings. Every character has an ordinal value e.g. ASCII ‘A’ has ordinal value 65.
Boolean(Logical) Data Types. These data types take only one or two possible values at any one
time. The two values are “True” and “False”. The name “Boolean” comes from the name of a
logician called George Boole who did much pioneering work in the algebra of logic.
2. Pure Binary- in which the whole number is converted to binary e.g. 39 decimal is represented
as 10011.
36
4.2.2 Operations, Operands, and Operators
An operation is a defined action upon data, e.g. 3 + 5 is an arithmetic operation on two integers.
The operator used to signify this operation has the symbol ‘ +’. The operands are the data items
operated upon i.e. here are 3 and 5. Operations which act upon two operands are called dyadic or
binary operations and operations upon single operand are called Unary operations. E.g 3 + 5
and 5-3- dyadic but +3 and –5 are unary or monadic operations.
4.2.4 Logic Relation Operators- These give Boolean values when applied to data types such
as integers, reals and characters. These operators are
= equal to
≠ or <> or != not equal to
< less than
> greater than
≥ or >= greater than or equal to
≤ or <= less than or equal to
37
4.2.5 Expressions
Expressions are formula containing operations or combinations of operations e.g. 3+4 * 5 is an
expression. It is necessary to have rules which govern the order in which the operations are
carried out. Such rules are called rules of precedence.
Precedence Rules for Arithmetic expressions
1. Operators of higher precedence are evaluated before operators of lower precedence.
2. Operators of equal precedence are evaluated in the order they appear when scanning the
expression from left to right.
3. The inclusion of parentheses in the expression requires that the expression within parentheses
be evaluated first by applying rules 1 and 2.
E.g. The precedence rules can be applied on the following expression: ((3+5)*2^3)/ (10-6)
4.2.5 Functions
Representing operations by means of operand and operator symbols proves to be unsatisfactory
when devising new operations on a regular basis. In such case the functional notation is used. E.g.
the operation “3 + 5” could be written in functional notation as “Add(3,5). The operands 3 and 5
here are called arguments or parameters. Other examples include Functions which perform
mathematical computations, such as Sine or Absolute value. These functions use numeric
arguments and evaluate to numeric results.
38
4.3 PROGRAMMING STATEMENTS
The forms in which program components are constructed, organized and interrelated are called
program structured. To understand how instructions are given to the computer there is need to
have the background knowledge of programming languages and the forms in which programs are
written. When learning a programming language we need to learn about two important aspects of
the language. 1) it Syntax and 2) its Semantics. The syntax of a language are the grammatical
rules which govern the ways in which words, symbols; expressions and statements may be formed
and combined. The semantics is defined in terms of what happens when the program is executed.
There are two types of languages: Natural Languages. Languages used for everyday
communication such as English, French and Chinese. They have complexities which make them
unsuitable as computer programming languages. Instructions in such languages often suffer from
ambiguities. For example, “calculate 4 and 6 divided by 2” could mean add 4 to 6 and then divide
the answer by 2, or divide 6 by 2 then add the result to 4, or divide 4 by 2 then divide 6 by 2, and
so on. Formal Languages. These languages have precise semantics. Properly defined
programming Languages are formal. Every instruction written in such languages has just one
meaning. When we learn a programming language, we must learn both its syntax(how to write it
down correctly) and its semantics(what will happen when it is executed) so that we use it
sensibly.
Computer languages are viewed at different levels. At machine level, the operations performed on
data are very simple. For each operation there will be one corresponding program, instruction
called machine language. In the early days of computers all programs were written in machine
language. These days, programs are most frequently written in “High level Languages”. The
program instructions in high level languages are much closer to sentences in English or
expressions in Mathematics. This makes them easier to use than machine languages. Programs
written in high level language have to be first of all translated into machine language by the
computer. This is because the computer can only operate using the instructions in machine
language. At times instructions are written in English like statements akin to high level languages.
This form of language is a kind of Pseudocode. Instructions written in high level language or
pseudocode are normally called Statements.
39
4.4 PROGRAM LEVEL VIEW OF THE COMPUTER
When writing programs we need some concept of what the computer is doing when the program
is used. The main features of the computer are still visible in features of the languages.
1) Storage. In all but the lowest level programming languages data items are identified by name
rather than by their location addresses in main storage. The names which we associate with stored
data values are called identifiers. An identifier is a “constant” if it is always associated with the
same data value and it is a “variable” if its associated data value is allowed to vary or change.
Changing a variable’s value implies changing what is stored. When referring to letters or names
in programs we must be careful to specify whether we mean them to be taken literally or be
treated as identifiers. When names or letters are used literally we called them literals. They are
placed within quotation marks. E.g. PRINT “N” means print the letter N, but PRINT N means
print the value associated with N.
4.4.1 Data Declarations. The data types of constants and variables must be defined
within a program so that appropriate operations may be performed upon the data values. Such
information should be given at the start of each program. The declarations are done specifying
each variable to a data type such as , integer, real, Boolean, character, etc. An example of
declaration is as follows.
Constants
Pi = 3.141592654
Variables
i, quantity_required, product : integer
area, rate, unit_cost : real
rate_code : character
rate_code_valid : Boolean
40
2) Input and Output. Programming languages have special functions for dealing with input and
output e.g. input, read, get accept, output , write, prints, put, display, etc.
3) Operations on Data. The price for all products is calculated by multiplying the unit price by
the quantity required as
products_price := unit_price * quantity _required.
This statement is an example of assignment statement. It has 3 components.
a) An assignment operator represented by some symbols. In the example “:=” is
used.
b) A result, with an identifier(e.g. “products_price); to the left of the assignment
operator;
c) An expression to the right of the assignment operator.
The exact form of the assignment statement varies from language to language.
4) Control. All programming problems, no matter how complex, may be reduced to combinations
of controlled sequences, selections or repetitions of basic operations on data. This fact was
established by two Italian Computer Scientists, C.Bohm and G. Jacopini in 1966. It is part of the
important theory which is behind the concept of “structured programming”, a term first used by
professor E. Diskstra in the mid 1960s.
Control Structures. Program control structures are used to regulate the order in which program
statements are executed. They are
a) Sequences. Statements are executed in sequence in the absence of selections or
repetitions program statements. They appear as
Statement_1
Statement_2
Statement_3
.
.
.
Statement n
b) Selections. Selections allow alternative actions to be taken according to the conditions
which exist at particular stages in program executions. Conditions are normally in the
41
form of expressions which when evaluated give Boolean results(true or false). E.g. The
if_then_else statement. A typical form of syntax for this statement is
If
Condition
then
Statement_sequence_1
else
Statement_sequence_2
Endif
The semantics of this statement is as follows. When the statement is executed, the condition’s
expression is evaluated. If the result of the evaluation is true then statement_ sequence_1 will be
executed otherwise statement_equence_2 will be executed. After either statement_sequence_1 or
statement_sequence_2 has been executed the statement “endif” is executed. This can be
visualized diagrammatically in the Fig.21
if
Condition
?
Statement_sequence_2 Statement_sequence_1
endif
Example. Consider a part of a program which two real numbers representing the two sides of a
rectangle are to be used to determine the area of the rectangle and to indicate whether or not the
sides form a square .
42
if
(side_one <= 0) OR ( side_two <= 0)
then
output(“the sides do not form a rectangle.”)
else
area := side_one * side_two
Output(“The area is “, area)
if
Side_one = side_two
then
Output(“the sides form a square.”)
else
Output(“The sides form a rectangle.”)
endif
endif
Within the first if_then_else statement there is another if_then_else statement. This is an example
of “nesting” i.e. a structure containing other structures of the same type.
CASE statement. A more general form of selection is the CASE statement. A simple case
statement could have syntax like the one below.
i) Syntax of a typical case statement.
Selectcase
Expression
Case case_list_1
Statement_sequence_1
Case case_list_2
Satement_sequence_2
. .
. .
. .
case case_list_n
statement_sequence_n
case else
statement_sequence_n+1
endselectcase
43
ii) Semantics of a case statement.
Select case
Expression
Example. Consider the cost of a telephone call to be calculated from the formula
Charge:= Units_used * Unit_cost * rate
With the summary b/w “rate_code” and “rate”.
Rate_code rate
L(Local) 2
A(Short distance) 2
B(Long distance) 2.5
C(Overseas) 4.0
Selectcase
Rate_code
Case “L”, “A”
Rate:= 2.0
Case “B”
Rate:= 2.5
Case “C”
Rate:= 4.0
Case else
Output(“ERROR_no such rate code!”)
44
Rate:= 0.
endselectcase
c) Repetitions.
There are many programming problems in which the same sequence of statement needs to be
performed again and again some definite or indefinite number of times. The repeated
performance of the same statements is often called “looping”.
There are three common “loop constructs” for performing repetitions. They are “while”,
“repeat” and “for” loops. The “while” and ‘repeat” loops are used for indefinite repetitions.
That s , they do not define the number of repetitions which will occur when the loop is
executed. They merely give conditions for looping to stop. The “for” loop is used for definite
repetition. It defines the number of repetitions which will occur during execution.
i) THE “WHILE” LOOP
while
while condition
statement_sequence
endwhile Statement_sequence
Condition
?
true
false
endwhile
Condition
?
false
true
45
iii) THE “FOR” LOOP
for
For control_value := expression to endvalue
Statement_sequence
Control value:=expression
endfor
Control_value:= control_value +1
Statement sequence
Control_value
> endvalue
false
true
endfor
Example
i) Output( “key in integer. Key in 99 to stop”)
input(i)
while i <> 99
product := i * 16
output(i, “times”, 16, “is”, product)
output(“key in an integer. Key in 99 to stop.”)
input(i)
endwhile
ii) repeat
output((“key in an integer. Key in 99 to stop.”)
input(i0
product:= i * 16
output(“i, times”, 16, “is”, product)
until i:= 99
iii) for i:= 1 to 5
46
product: i * 16
output(i. “times”, 16, “is” product)
endfor
N.B. The number 99 is called a sentinel or rogue value as it is being used in the example. Any
other number can be used. It does not belong to the data instead it signifies that the data has come
to an end.
4.5 SUBPROGRAMS
It is an aspect of program structuring. It is used to describe a part of a program. The term refers
to any set of statements forming art of a program used to perform a specific task. There are two
basic types of subprograms I) functions and ii) procedures
Now consider a function for calculating the area of a rectangle. A program which will use the
function will contain a declaration of the function. The declaration defined the function. The
function will also be used or “called” with the sequence of executable statements.
Program Rectangle
Variables
Side_one,
Side_two,
Area : real
Function rectangular_area(first_side: real, second_side: real) : real
47
(* the function calculates the area of a rectangle from the lengths of its two sides. If
the value of either side is not positive it assigns the value zero to the area*).
Begin
if (first_side <=0) OR (second_side <=0)
then
Rectangular area:= 0
else
Rectangular_area := fisrt_side * second_side
endif
end
(*Now the procedural part of the program*)
Begin
.
.
.
area:= rectangular_area(side_one, side_two)
end
Formal arguments- as in the example the arguments “first_side “ and second_side” used in the
function declaration are termed formal arguments. On the other hand the argumentws “side_one
and side_two” used in the function call are known as actual arguments.
4.6 Procedures
Literally, a “procedure” is any defined way of carrying out some actions. But more precisely,
programming procedures are defined operations on defined data and may be used as program
components.
The function and procedure definitions are similar but there is a difference. A procedure call is a
program statement whereas a function call appears in a program as expression. E.g. in the
example above.
Function call:
area := rectangular_area(side_one, side_two)
If on the other hand a procedure is to be called, then it will take the form:
Call rectangular_area(side_one, side_two, area)
48
Procedure rectangular_area(IN first_side, second_side : real
OUT area : real)
Begin
If
(first_side <= 0 ) OR (second_side<=0)
then
area:=0
else
area:= first_side * second_side
endif
endif
i.e
“IN” ⎨ first_side: real
parameters ⎨ second_side: real procedure rectangular_area area: real } an “OUT”
parameter
Parameters. In the preceding procedure example, “side_one”, “side_two”,and “area” are “actual
parameters” of the procedure Similar to the “actual arguments” of functions. The IN parameters
of the procedure correspond to the arguments of a function just as OUT parameter of the
procedure is as the value returned by a function.
49
CHAPTER FIVE: APPLICATION AREAS
5.1 REASONS FOR USING COMPUTER
Virtually computers are employed to solve problems in almost every areas of human endeavour.
There are certain criteria for using computers such as: -
(1) Volumes. The computer is particularly suited to handling large amounts of data .
(2) Accuracy. The need for a high degree of accuracy is satisfied by the computer and the
consistency be relied upon.
(3) Repetitiveness. Once programmed the computer happily goes on and on automatically
performing as many cycle as required.
(4) Complexity. The computer can perform the most complex calculations as programmed
(5) speed computers work at phenomenal speeds.
(6) common data. One item of input data can affect several different procedures. For example a
customers order for a particular stock could involve production of an invoice, updating of the
customers record, updating the stock record, and initiating a recorder for the stock item.
50
b. Mathematical and Statistical Analysis e.g. research in Physics, Chemistry, Geology,
Archaeology, medicine, Astronomy, etc.
c. Design Work e.g. CAD( Computer Aided Design) with growing importance in Electronic,
Electrical, architecture; also Computer graphics.
d. Manufacturing. CAM(Computer Aided Manufacture) and CADMAT(Computer Aided Design
Manufacture and Testing).
e. Robots. The word “Robot” comes from Czech word meaning “ to labour” and first appeared in
a play written by Karel Capek in 1920. A robot can be programmed to carry out a complex task
and then reprogrammed to carry out another complex task.
51
CHAPTER SIX: NUMBER SYSTEMS AND COMPUTER ARITHMETICAL
PROCEDURES
6.1 NUMBER SYSTEMS
The number systems use in computer for data representation and data transmission are Binary
numbers which are used by digital computers when they store and process data; Decimal or
Denary numbers, or numbers in base 10 which make use of the ten digit symbols, 0, 1, 2, 3, 4,…,
9; the octal numbers or numbers in base 8 which uses the symbols 0, 1, 2, 3, …, 7; the
Hexadecimal numbers usually abbreviated to “Hex” or numbers in base 16 which uses the
symbols 0, 1, 2, …,9, A, B, C, D, E, and F. Thus A, B, C, D, E, and F are equivalent to 10, 11, 12,
13, 14, and 15 DECIMAL. The binary number system uses just two symbols, 0 and 1, and place
values increasing in powers of two. Similarly for octal and Hex numbers values are placed
increasing in powers of 8 and 16 respectively. The octal and Hexadecimal numbers are used as a
shorthand for binary. This numbering system can be summarized as follows.
Number system Symbol used
Binary 0,1
Octal 0,1,2,3,4,5,6,7.
Decimal 0,1,2,3,4,5,6,7,8,9.
Hexadecimal 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.
E.g.
a) Conversion from
i) 11011012 → Decimal = 1x26 + 1 x 25 +0 x 24 +1x23 +1x22 +0x21 +1x20 = 109
ii) 109 → Binary
= 2 109
2 54 R 1
2 27 + 0
2 13 + 1
2 6 +1
2 3+0
2 1 +1
2 0 + 1 ↑ = 11011012
52
Similarly conversion from octal to decimal and back to octal takes the same format. Likewise
conversion from Hexadecimal to decimal and back to Hexadecimal.
E.g 109 → Hexadecimal is 16 109
16 6 + 13
0 + 6 i.e. 10910 = 6D16
and 6D16 → Decimal is 0x 162 + 6 x 161 + D x 160 = 109
Hex Number 6 D
Binary digits 0110 1101 = 6D16 = 011011012
Now Hex → Octal is from Binary → Octal
53
Binary Digits 001 101 101
Octal Number 1 5 5
6.1.2 Complements
There are two types of number complements:
1. The radix-minus-one complement (or diminished radix complement).
a) It is called the nines complement when in decimal system
b) in the binary system it is called the ones complement
2. The radix complement( or the true or noughts complement)
a) called the tens complement in the decimal system
b) in the binary system is called the twos complement
Complements are used mainly for representing negative numbers and for subtraction.
54
Rules for finding complements of numbers
1. To add the radix-minus-one complement of a number, subtract each digit of the number from
one less than the radix(base) e.g. for octal subtract each digit from 7.
2. To obtain the radix complement add one to the radix-minus-one complement.
Example. Find the complement of 30962 and 101102
(i) 999999 --- one less than the radix i.e 9
030962 --- subtract to be complemented
969037 --- i.e. Nines complement
Now add 1 to obtain Tens complement
969037
1
969038
(ii) 111111 ----- one less than the radix i.e 1
010110 ----- subtract to be complemented
101001 ----- Ones complement
Now add 1 to give twos complement i.e 101010.
But it can be noticed that for binary numbers, the rules simplify to: (a) change ones to zeros and
zeros to ones to obtain the ones complement (b) add one to this result for the twos complement.
The negative numbers can be represented using binary with the most significant(i.e. leftmost) bit
indicating the numbers sign( 0 for ‘+’ and 1 for ‘-‘ ). This is called the sign bit. For example,
using 3 bit to represent numbers from the range +3 to –3.
a) Sign
+3 0 1 1
+2 0 1 1
+1 0 0 1
0 0 0 0
(Redund-
ant) -0 1 0 0
-1 1 0 1
-2 1 1 0
-3 1 1 1
55
b) Ones Complement method
Sign
+3 0 1 1
+2 0 1 0
+1 0 0 0
0 0 0 0
(Redund-
ant) -0 1 0 0
-1 1 1 0
-2 1 0 1
-3 1 0 0
c) Twos complement method
Sign
+3 0 1 1
+2 0 1 0
+1 0 0 1
0 0 0 0
-1 1 1 1
- 1 1 0
-3 1 0 1
-4 1 0 0
Range: +3 to -4
Noticed that there is no redundant representation of zero using twos complement representation.
As a result the range of representation is extended by one bit. In like manner, representations
using a greater number of bits can be constructed.
E.g. represent 107 and –107 in twos complement using 12 bit representation with the leftmost bit
as sign bit.
+107 000001101011
-107 111110010101 i.e. the ones complement of +107 is first obtained
then its twos complement by adding 1.
Note that Twos complement arithmetic is more straight forward than ones complement arithmetic
E.g. when adding two negative numbers:
1112 1102
1112 1102
11102 11002
ignore 1 Add carry
1012
56
6.2 Binary Fractions
Examples. 1. Convert 11.1012 to Decimal value
1 x21 + 1 x 20 + 1x 2-1 + 0 x 2-2 + 1 x 2-3 = 3.625
2. Convert 0.62510 to binary.
The steps are (i) multiply by 2. (ii) remove digit before the point of the result to form the binary
fraction. (iii) repeat the process until a zero fraction value occurs, or the required accuracy is
reached.
i.e. .625 x 2 = 1.25
.25 x 2 = 0.5
.5 x 2 = 1.0
.02 x 2
∴ the required result is 101
3. Convert –1/3 to binary using 5 bits for your representation and twos complement form.
We first of all convert +1/3 then find its complement.
1/3 x 2 = 0 + 2/3
2/3 x 2 = 1 + 1/3
1/3 x 2 = + 2/3
2/3 x 2 = 1 + 1/3
1/3 x 2 [Repeats]
Thus we have .0101…
Now 1/3 to 5 BITS including sign 0.0101
1.1010 --- Ones complement
1.1022 – Twos complement
Exercises
1. Use 4 bit representation and twos complements to do the decimal subtraction in binary: 7-4 = 3
2. Evaluate the following (a) D5F + 4AC (b) BCA + E23 (c) 278 + 538
3. Give the 8 digit binary ones and twos complement representation of (a) –2110 b) -3910
4. Convert from decimal to binary (a) .3125 (b) .9375
5. Convert these octal fractions to binary (a) .36 (b) .745
57
6. Convert C4F.B16 and EB4.516 to binary subtract the larger value from the smaller one using two
complement and then express your answer in base 10.
58
CHAPTER SEVEN: DATA STRUCTURES
7.1 DATA STRUCTURE DEFINED
A data structure is an organized grouping of data items treated as a unit. Or it is a structure in
which data items can be stored and retrieved. Data structures are sometimes termed as data
aggregates and at times are regarded ad complex data types. The common data structures amongst
others are ARRAYS, STRINGS, RECORDS, LISTS and TREES. There are so many different
types of data structure.
7.1.1 Arrays
Sets of data items of the same data conveniently arranged into a sequence is called an array. For
example the set represented by a single identifier say PASS of pass marks obtained by some
students in CS 101 class. E.g. PASS = ( 56 42 89 65 48 60). The individual marks i.e.
individual data items in the array may be referred to separately by stating their positions using
subscripts in the array. E.g. PASS(1) refers to 56, PASS(3) refers to 89, PASS(6) refers to 60. The
subscripts are enclosed in the parentheses “(“ and “)”. Variables such as PASS(i) where i= 2
refers to 42, and when i = 6 refers to PASS(6) i.e. 60.
Note that when variables are declared and used only within a procedure or function, they are
called local variables. When they are defined throughout the program the variables are called
global variables. In general terms it is bad practice to use variables globally. They should
always be passed into procedures as parameters if they are to be used there.
Array Elements. The individual data items in an array are called its elements. However, a
data item occupies an element, i.e. elements, rather like pigeon holes, are regarded as
locations into which data-items may be placed and removed. The main storage can be
regarded as an array in which
a) Locations correspond to elements, and
b) Locations addresses correspond to subscripts.
7.1.2 Matrices
Matrices are arrays containing only numbers and no alphabetic data.
59
An array can be two-dimensional. For example, the examination marks of a class for several
courses could be placed in a two dimensional array.
Student CS 101 MTH 101
Column 1 Column 2
1 A(1,1) = 56 A(1,2) = 44
2 A(2,1) = 42 A(2,2) = 36
3 A(3,1) = 89 A(3,2) =73
4 A(4,1) = 65 A(4,2) = 86
5 A(5,1) = 48 A(5,2) = 51
7.1.3 Strings
Strings are used for text handling and related problems. A string is a sequence of characters
handled as a single unit of data. For example, “ ABC-, 3gh” and “THE CAT SAT ON THE
MAT” are literal strings. When strings are joined together they are said to be concatenated e.g.if
A = “Best” and B= “Excel” the assignment; C = A & B concatenates A and B where C = “
BestExcel”. A = “Best” and B= “Excel” are substrings of C= “ BestExcel”, or part of string C =
“ BestExcel”.
Fixed Length Strings have a fixed number of character places available for data storage.
E.g. The following shows five fixed length strings concatenated into a single string. Each string is
5 characters long.
Character 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
position
Contents J A M E S K A T Y A N N A L E X
Comment 1ST STRING 2ND STRING 3RD STRING 4TH STRING
60
Variable length strings provide the data with just the number of spaces it needs.
E.g. The following diagram shows five variable length strings concatenated into a single string.
Character 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
position
Contents J A M E S * K A T Y * A N N * A L E X *
comment 1ST STRING 2ND STRING 3RD STRING 4TH STRING
7.1.4 Records
Records are like one dimensional arrays in that they are comprised of a series of related data
items. Whereas all elements in an array have the same Type, the successive data items in a record
may differ in type.
Suppose we wish to organize the following three items of data relating to an individual
examination candidate into a single data structure:
Candidate_number : integer
Candidate_name : string
Average_mark : real
These data items belong together but they cannot be stored in an array because they are of
different types. Rather they are to be stored in a record. A suitable record declaration could take
the form:
Candidate:= record
Candidate_number : integer
Candidate_name : string
Average_mark : real
Endrecord
Thus a record called “candidate” was declared. The three elements of the record each had their
own identifiers, unlike array elements which are merely referred to by subscripts. The elements of
a record are called fields.
61
Example. If now a record is to be created for candidate 1505, named Samson who got an average
mark of 60.5, then these values could be assigned to the three fields as above of the record called
Candidate. This can be done in 2 ways:
1. Using the “dot” notation. Now the Pseudocode:
begin
candidate. Candidate_number := 1505
candidate.candidate_name := “Samson”
candidate. Average_mark := 60.5
end
Each record is identified by the record name followed by a “dot” followed by the field name. But
this notation is clumsy when several fields from the same record are to be referenced. In place of
this method the following method is preferred.
2. The “ with” notation.
Begin
With candidate
Candidate_number := 1505
Candidate_name := “Samson”
Average_mark : 60.5
endwith
end
The facilities for creating records are only in some high level languages such as Pascal, Cobol,
Modula, etc.
62
This data could be stored in an array of records declared in the following way:
Variables
Candidate: array[1..6] of record
Number: integer
Name: string
Average : real
Endrecord
The following pseudocode could be used to output the data suppose the data had already been
assigned to records in the array. “ i” is an integer.
Begin
For I: 1 to 6
With candidate(i)
Output(number, name, av-mark)
Endwith
Endfor
end
7.1.6 Lists
Lists provide a flexible way of handling data items in order. Changes to the order can be achieved
with minimal data movement and little loss of storage space.
E.g. The sentence “Alex does not like Mango” is written as a list.
We regard each word in the sentence as a data- item or datum which is linked to the next datum
by a pointer. Datum plus pointer make one element of the list. The last pointer in the list is a
terminator. A datum in a list can be deleted or inserted.
7.1.7 Trees
Trees are hierarchical data structures liken to the family tree. They are constructed using a rule of
precedence for the data items e.g. using alphabetic or numerical sequence. The elements of a tree
are called nodes and each element consists of a datum and at least two pointers. Let us now
consider numbers 56, 42, 89, 65, and 48 to be placed into a tree. Considering their numerical
order each element looks like this:
63
LEFT POINTER DATUM RIGHT POINTER
START
56
2 3
42 89
-1 -1 -1 -1
4) 65 is added next, then
5) 48 next.
64
START
56
2 3
89
42
5 4
-1 48 -1 65
65
CHAPTER EIGHT:FLOWCHARTS
8.1 FLOWCHART SYMBOLS
There are two types of flowchart symbols: System Flowchart symbols and Program Flowchart
symbols. A flowchart also called flow diagram is a diagram that shows the connections between
the different stages of a process or parts of a system. Here we are considering program flowchart
symbols.
start stop
end
e.g.
Add Number to Calculate profit
subtotal
The process symbol
e.g.
The decision symbol No Is Transaction Yes There is only one entry
A credit ? point and at least
Two exits.
e.g.
Input
Name
66
Used where data input or output is to
be performed
The input/ output symbol
or
exit to, or entry from, another part of the chart
(connector symbol).
Flowcharts were originally introduced as aids to a systematic process of analyzing problems and
developing suitable computer based solutions. In recent years flowcharts have been heavily
criticized as being cumbersome and inefficient tools for the job. Flowcharts are therefore
traditional means of showing, in diagrammatic form, the sequence of steps in performing a
programming task.
67
CHAPTER NINE: BASIC AS A PROGRAMMING LANGUAGE
9.1 BASIC
BASIC(Beginner’s All-purpose Symbolic Instruction Code) is a carefully constructed English-
like language used for writing computer programs. All programming languages must be translated
into machine instructions called machine language. There are basically two types of high-level
language translators, called interpreters and Compilers. An interpreter translates an instruction
into machine code each time it is to be carried out; compiler translates an entire program into
machine code only once. Interpreters and compilers are themselves computer programs called
systems programs because they are an integral part of the computer system itself. Other system
programs include those that allow the use of a disk unit as an external storage device. These
include programs to store information on diskettes, to retrieve any information on a diskette, and
to perform several other useful tasks involving disk units. Together, all systems programs
designed to carry out disk operations are called the disk operating system(DOS).
68
If the following set of numbers 4, 5, 3, 6,6, 2, 1, 8, 7, 3 is considered then the orderly way to do
this is as follows.
Algorithm step L N
1 4
2 5
4 5
2 3
2 6
4 6
2 6
2 2
2 1
2 8
4 8
2 7
2 3
69
150 LET Z = 23
160 LET A = ( X+ Y + Z ) / 3
170 PRINT “ AVERAGE IS “ , A
180 END
The output of the commands will be AVERAGE is 31.
BASIC programs are labeled with line numbers( but in some versions such as Microsoft q-BASIC
line numbers are not compulsory) that determine the order in which commands are carried out
by the computer. BASIC programs have keywords such as REM, to include remarks or
comments as part of the program; LET(not compulsory in q-BASIC), to assign or associate
certain numerical values with certain symbols; PRINT, to print the results; END, to terminate the
program, etc. These keywords are called reserved words which can not be used as variables
names
.
9.3.1 Numerical constants and Variables
There are three types of numerical constants allowed in BASIC
Type Examples
Integer 726, -726, +423
Decimal 726, -133.50, +10.001, 0.201, .201
Floating point 1E4, -13.6E-2, .12345E03, +2.345E-01
(Exponential)
The use of commas and dollar or naira sign in numbers is not allowed e. 99,234 to represent
99234 will result in an error. The general form for a floating- point constant, together with its
meaning, is
nEm = n x 10m. Here n may be any integer or decimal, but m must be an integer, E stands for “
exponent”. E.g. 1E4 = 1 X 104; -13.6E-2 = -13.6 X 10-2; .12345E03 = .12345 X 103.
As numerical variable names, BASIC allows sequences of alphanumeric characters(letters A-Z
and digits 0-9) beginning with a letter e.g. x, SUM, AVERAGE, T3275, DEPT17 are allowed but
3RD (begins with a digit), S-200 ( contains a dash, SSN. (period is not allowed); RATE(AT is a
reserved word); SCORE( OR is a reserved word) are inadmissible variable names.
70
The variables just described re called real variables. In addition to these variables BASIC
provides integer variables which involves only integers from –327667 to 32767. Integer variable
names differ from real variable names in one way only: their last character must be the percent
symbol(%). E.g. LET A% = 15.987. The integer values for such variables are obtain by
truncation. Thus A% = (.987 is discarded).
Any meaningful combination of constants, variable names, and operation symbols is called
expression. In an Expression, the order in which the operations are performed is determined first
71
by the indicated priority, then within the same priority class, from left to right. E.g.1. 5* 2 ^ 2 + 3
^ 2 = 5 * 4 + 3 ^ 2 = 5 * 4 + 9 = 20 + 9 = 29.
(2) –5 ^ 2. Since negation (-) has highest priority, it is performed first. Thus –5 ^ 2 = (-5)2 = 25.
Parentheses are used in BASIC expressions just as in ordinary algebra. E.g. 5 * 2/3 can be written
as (5 * 2 ) / 3.
Problems
1. Evaluate the following
(a) –2 * 3 / 2* 3 (b) 75E-5 (c) 1.23E7 (d) (2 + (3 * 4 – 5 )) ^ 0.5
2. For A=2, B=3, and X=2, evaluate each of the following (a) B/(A*X) (b) B/A/X
72
E.g. , LET A = 2 + 5 has line 100 and contains the BASIC command LET A= 2 + 5. This line will
cause the computer to evaluate the sum 2 + 5 and then assign this value to the variable A.
The general form of the first BASIC statement, the LET statement, is ln LET a = e or more
simply, ln a = e (LET is optional) where ln stands for line number, a denotes a variable name,
and e denotes a BASIC expression that may simply be a constant. This statement directs the
computer to evaluate the expression e and then assign this value to the variable a. Only numerical
values may be assigned numerical variables and only strings to string variable.
Explanation: The END command causes program execution to terminate. Clearly written
programs seldom do what they were meant to do. The programmer must find and correct all
errors. The error are called bugs, and making the corrections is referred to as debugging the
program.
73
Example. Assigning of String values:
The program After Execution of each statement
Value of A$ Value of B$ Value of C$
200 LET A$ = “AND” AND
210 LET B$ = “ SO” AND SO
220 LET C$ = B$ AND SO SO
230 LET B$ = A$ AND AND SO
240 LET A$ = C$ SO AND SO
250 END
Explanation: Strings appearing in LET statements must be quoted. Note, however, that it is the
string and not the quoted string that is assigned to the variable. An empty string is written “ ”.
74
are all admissible. When a PRINT statement is executed, the value of the expression is printed
and then a carriage return is executed- this means that the cursor is positioned at the beginning of
the next display line. Now if x has value 703.25 and A$ has the string value END OF MESSAGE,
lines 100 to 130 will produce the following output:
THIS IS A MESSAGE
59
703.25
END OF MESSAGE
BASIC allows you to print the values of more than one expression on a single line.
75
the program will produce exactly the same output.
Example
100 REM **DETERMINE THE RATE OF RETURN
110 REM GIVEN THE CURRENT RICE
120 REM AND EARNINGS OF A SECURITY**
130 REM P DENOTES PRICE.
140 REM E DENOTES EARNINGS.
150 REM R DENOTES RATE OF RETURN.
160 LET P = 80.00
170 LET E = 6.00
180 REM ** CALCULATE RATE OF RETURN
190 REM AND PRINT SUMMARY RESULTS **
200 LET R = 100 * E/P
210 PRINT “PRICE”, P
220 PRINT “ EARNINGS”, E
230 PRINT “ RATE OF RETURN”, R
240 END
The output is
PRICE 80
EARNINGS 6
RATE O RETURN 7.5
76
2. Unlike quoted messages in PRINT statements, comments included in REM statements cause
nothing to be printed when the program is executed by a computer. Their sole purpose is to
document program.
3. In this program, REM statements are used for three different purposes: to give a brief
description of the program ( lines 100 to 120),and to describe the action of certain groups of
programming lines( 180 and 190). Using REM statements in this manner is an excellent
programming practice. Your programs will be easier to read and understand, easier to modify at
some later date ( should that be required), and easier to debug.
Problems
1. Write LET statements to perform the indicated tasks
a) Assign the tenth power of 1 + R to A
b) Store the contents of P$ in Q$
c) Double the value assigned to H
d) Assign the string ***** to S$.
77
b. 20 LET Z = 4E2.5
c. 30 LET “DEPT#7” = D$
78
30 LET A = T ^ 2
40 PRINT “ SQUARE IS “,A
END
is a program to print the square of any number.
Example: Here is program to compute the cost C of renting a car for D days and driving it K
kilometers. The rental rate is N 12 per day and 11K per kilometer.
10 PRINT “ ENTER NUMBER OF DAYS.
20 PRINT “ AND NUMBER OF KILOMETERS, “
30 PRINT “ SEPARATED BY A COMMA.”
40 INPUT D, K
50 LET C = 12 * D + .11 * k
60 PRINT “ total cost is “, c
70 END
RUN
Example:. INPUT command can be used to input string values for string variables.
10 PRINT “ENTER A NAME.”
20 INPUT N$
30 “PRINT ENTER THE DATE.”
40 INPUT D$
50 PRINT
60 PRINT N$
70 PRINT “ INITIATION:”, D$
80 END
Note consider the statement
200 INPUT “ WEEKLY INCOME : $ “; I
When the value of I is input as 500 the result will appear as
WEEKLY INCOME : $500
The use of the semicolon means that the value will be printed on the same line with the statement
being separated by the semicolon.
79
The general forms of command INPUT are
INPUT input list
INPUT quoted string ; input list
Where input list denotes a list of variable names separated by commas. The semicolon in the
second form is required. When executed, the first form displays the input prompt(?) and the
second form displays the included string. In either case, you must respond by typing a value for
each variable in the input list and separate them by commas.
80
150 GOTO 110
The PRINT statement of the form: PRINT expression1, expression2will print the values in two-
column. It is the comma in this PRINT command that causes the values of expression1 and
expression2 to line up in columns. The PRINT statements of the same form is used to print the
column headings.
Example: Prepare a table showing the equivalent annual salaries for persons working 40 hours a
week if their hourly rates are N 4.50, N 4.60, N 4.70, …, N 5.50
Problem analysis. The weekly pay W for a person working 40 hours a week at H naira an hour is
W = 40 X H naira; the annual salary A for this person is A = 52 X W naira. The hourly rates H =
4.50, 4.60, 4.70, and so on should not be input. Since successive H values differ by the same
amount (0.10), start with H = 4.50 and keep adding 0.10 to the (LET H= H + 0.10) to get the other
values.
Algorithm.
a. Print the two column headings
b. Let H = 4.50
c. Evaluate W = 40 X H and then A = 52 X W.
d. print H and A on one line
e. Add 0.10 to H and go to step (c )
The program.
100 REM SALARY TABLE PROGRAM
110 PRINT
120 PRINT “HOURLY’, “ANNUAL”
130 PRINT “RATE”, “ SALARY”
140 PRINT “ ----“, “----“
150 LET H = 4.50 :REM HOURLY RATE
160 LET W = 40 * H: REM WEEKLY SALARY
170 LET A = 52 * W : REM ANNUAL SALARY
81
180 PRINT H, A
190 LET H= H + 0.10
200 GOTO 160
.
.
.
5.5 11440
Note; There is need for these programming practices.
1. To discover a correct algorithm for a given problem statement, carry out a complete problem
analysis and record it in writing. The first step should be to determine precisely what is being
asked. Determine the input and output values is a good way to begin.
2. Use PRINT statements for ( or INPUT statements containing strings) to tell the user what
values are to be input during program execution. Also use PRINT statements to label all output
values. The precise form of these statements is usually determine during the coding process – i.e.
after the algorithm has been described.
3. Use REM statements to make the program more readable and to clarify what is being done at
every point.
Problems
1. Show the output generated by this program
100 LET A =1
110 PRINT A
120 LET B =1
130 PRINT B
140 LET C = A +B
150 PRINT C
82
160 LET A =B
170 LET B = C
180 GO TO 140
3. Write a program to print the table described. Begin with a PRINT statement describing the
table. Print the column headings.
You require an accurate sketch of the graph of
y= 1.09x3 - 3 8.51x2 + ( 1.314/ 1.426)x – 0.8 on the interval 1≤ x≤ 3. To make this task
easier, produce a table of the y values where the x’s in increments of 0.1.
BASIC contains several statements , called control statements. These allow the control order in
which program statements are executed. The GO TO statement earlier stated is an example.
83
9.11.1 The IF Statement
Its purpose is to override the normal sequential execution of the statement in a program – but only
if a certain condition, specified by the programmer, is satisfied.
E.g. 1. A program to print 6% of any input value , but only if the input value is positive:
9 NPUT “ AMOUNT? “ ; A
20 IF A > 0 THEN PRINT “ TAX IS “ , 0.06 * A
30 END
After a value of A is input, the condition A > 0 in line 20 is tested. If it is true, the PRINT
statement following the keyword THEN is executed. If false the PRINT statement is not executed.
Example: A program to print 6% of each of many positive input values and to stop when the
number typed is not positive:
100 INPUT “ AMOUNT ? “ ; A
110 IF A <= 0 THEN GO TO 160
120 PRINT “ TAX IS “, .06 * A
130 PRINT
40 INPUT “ NEXT AMOUNT?”; A
150 GO TO 110
160 PRINT “ INVALID AMOUNT “
170 END
Explanation: 1. When the command following the keyword THEN is a GOTO command, BASIC
allows the omission of GOTO or THEN, but not both. Thus the following are equivalent ways of
writing line 110:
110 IF A <= 0 THEN 160
110 IF A <= 0 GOTO 160
2. When writing an IF statement you must not precede the keyword THEN by the letter A. Doing
so introduce the reserved word AT into the program. For instance
110 IF 0 >= a THEN GOTO 160
84
Examples 1 & 2 illustrate the two very different uses of IF statements: to construct
loops(example 2) and to make decisions(example 1). When the IF statement is used to construct
loops, certain difficulties encountered with the GOTO statements are easily avoided.
In BASIC, more than one command can follow the keyword THEN in an IF
statement. For example:
70 IF X > 0 THEN PRINT X : GOTO 30
50 IF A = 0 THEN PRINT “ DONE “ : END
65 IF X > 60 THEN S = S+ X : N = N + 1
These examples illustrate here different forms of the IF statement:
IF condition THEN ln
IF condition GOTO ln
IF condition THEN command { : command}
Expressions such as these are called relational expressions and they are used in IF statements.
Example. Write a program to input two numbers A and B and print the message BOTH if both
are negative and the message NOT BOTH otherwise.
Here’s an algorithm for doing this:
a. Input values for A and B.
b. If A is not negative, print NOT BOTH and stop.
85
c. If B is not negative, print NOT BOTH and stop.
d. Print BOTH and stop.
The program:
10 INPUT A, B
20 IF A >= 0 THEN 60
30 IF B>= 0 THEN 60
40 PRINT “BOTH “
50 GOTO 70
60 PRINT “ NOT BOTH “
70 END
Example
a. The logical expression ( A < B) AND (B < C ) is true if both expressions A < B and B < C are
true; otherwise it is false.
b. (A<B) OR (A< C) is true if either or both of the expressions are true. This expression is false
only if the expression (A >= B) AND (A>= C) IS TRUE.
c. The logical expression NOT (A < B) is true if the A < B is not true, otherwise it is false. The
expression NOT(A<B) is equivalent to the relational expression A >= B.
Example.
a. The statement IF (A>0) AND (B> 0) THEN 200 will transfer control to line 200 if both A and
B are positive. Otherwise ,control passes to the line following the IF statement.
b. The statement IF (G.= 80) AND ( G <= 89) THEN PRINT “B” will cause the letter B to be
printed only if G is between 80 and 89, inclusive.
c. IF ( G < 80 ) OR ( G > 89 ) THEN 300 will cause a transfer to line 300 only if G is not between
80 and 89, inclusive.
86
A logical expression may contain more than one of the operators NOT, AND, and OR. An
expression such as (M = 0) OR (A < B) AND (A< C) IS ADMISSIBLE. IN BASIC, the following
priorities are used:
Logical operator Priority
NOT highest
AND intermediate
OR lowest
Parentheses may be used to override this order or simply to clarify what order is intended. Thus
the logical expression (M = 0) OR ( A < B) AND ( A< C) is equivalent to the expression (M = 0)
OR (( A < B ) AND ( A < C)). It is an excellent programming practice to use parentheses
consistently to clarify what is intended in an expression even when they are not required
Here is the rule governing the order in which BASIC carries out the operations in any logical,
numerical, or string expression.
BASIC operators Priority
- (negation), NOT 1(highest)
^ 2
*, / 3
+, - (Subtraction) 4
>, >=, <, <=, <>, = 5
AND 6
OR 7(lowest)
In any expression, the operations are carried out from highest to lowest priority and operations
having the same priority are carried out from left to right.
Exercises
1. If A =1, B= 2, C = 3, which of the following logical expressions are true?
a. NOT((A> B) OR ( C > A)
b. –A – B – C <= -(A+B+C) * B
c. A / C * B <= 5
87
2. Explain what is wrong with each statement. The problem may be a syntax error, or it may
serve no purpose whatever.
a. 90 IF 2 < y <4 THEN 27
b. 40 if A1 > A2 PRINT A1
c. 60 IF M – N < 27, THEN 13
3. Write a program to perform the task specified. The operators NOT, AND, and OR are not
required.
a. Two numbers X and Y are to be typed. If the sum of X and Y is greater than 42, print 42. If not,
increase X by 10 and Y by 3, print the next X and Y, and again check to see if the sum is greater
than 42. Continue until the sum is greater than 42.
b. input a positive integer N, and determine the first positive integer I whose cube is greater than
N.
4. write a program to perform the following tasks. You may find the logical operators NOT,
AND, and OR helpful.
a. For any two numbers M and N, print POSITIVE if both are positive and NEGATIVE IF BOTH
ARE NEGATIVE. Otherwise, print NEITHER.
b. Find the first positive integer N for which 33N-28 > 24N + 200 and 5N – 63 ≥ 2N + 21 .
88
START
LET S= 0
LET N = 1
N > 10
Print S
LET S = S+ N
LET N = N+ 1
STOP
Note:
The process of preparing a flowchart is called flowcharting. Flowchart is simply another way to
describe an algorithm. There is no fixed rules on how to proceed in a flowchart- flowcharting
89
must be practiced. Once a flowchart is prepared, the task of writing the program is reasonably
straight forward; it consists only of coding the steps indicated in the flowchart.
Example. Construct a flowchart for a program to determine the number of years required for an
investment of N 1000 earning 7.5% compounded annually to double in value.
Problem analysis
The compound interest formula is
A = P(1+R)n in which
P = principal(P = 1000)
R = rate per period(R = 0.075)
N = number of periods
A = value after N periods
We begin the flowchart construction by assigning initial values to P, R, and N:
START
LET P = 1000
LET R = 0.075
LET N = 0
Next the value of a after 1 year is compared with 2P. We now add the following segment to our
partial flowchart:
LET N = N+1
P(1+R)n T
≥ 2P
90
If the condition is true, print N and stop. Otherwise increase N by 1 and repeat the comparison.
Adding these two steps the complete algorithm is obtained.
START
LET P = 1000
LET R = 0.075
LET N = 0
LET N + 1
P(1+R)n ≥ 2P
Print N
STOP
If this flowchart is coded, a GOTO statement will be needed following the IF statement. The
GOTO can be avoided using < rather than ≥ in the decision box. The flowchart will have exactly
the same structure, but the program will be easier to read.
The Program
100 LET P = 1000
110 LET R = 0.075
120 LET N = 0
130 LET N = N + 1
91
140 IF P * (1 + R ) ^ N < 2 * P THEN 130
150 PRINT “YEARS TO DOUBLE “, N
160 END
Exercises
Prepare a flowchart and then a program to accomplish each task specified in each of the
following. Try to avoid GOTO statement in your program.
1. Input one number. If it is b/w 3 and 21, print BETWEEN. Otherwise, print NOT BETWEEN.
2.Input two numbers. If either one is positive, print EITHER. Otherwise, print NEITHER.
3. In put three distinct numbers. If the second is the largest, print LARGEST. If it is the smallest,
print SMALLEST. Otherwise, print neither.
4. For any input list, determine how many times a number is strictly larger than the one just
before it. For example, if the list is 17, 3, 19, 27, 23, 25, the answer will be three, because 19>3,
27>19, and 25>23.
5. Several pairs(X,Y) of numbers are to be input. Any pair with X = Y serves as the end of data
(EOD) tag. Determine and print counts of how many pairs satisfy X<Y and how ,any pairs satisfy
X>Y.
Example. Construct a flowchart and write a program to evaluate the following sum where N is to
be specified by the user. If the input value N is less than 1, the sum is zero.
S = 12 + 22 + 32 + … N2
Problem analysis: Here’s a simple algorithm for this task:
a. Input N.
b. Calculate the sum S = 12 + 22 + 32 + … N2 .
c. Print S and stop.
92
To carryout step (b) you can start with a sum S of zero and add the squares of the numbers 1, 2,
…, N to S, one at a time. The following flowchart describes this process.
START
Input N
LET S = 0
LET J = 1
J> N T
F Print S
LET S = S+ J ^ 2
LET J = J + 1 STOP
93
N1 = count of numbers whose sum is S1
N2 = count of numbers whose sum is S2. START
The Flowchart:
I
Input X
X = 999
Print Result
F T
60≤ x ≤ 80
Stop
LET S2 = S2 + X LET S1 = S1 + X
LET N2 = N2 + 1 LET N1 = N1 + 1
STOP
The double inequality in the second decision box suggests that we use an IF statement with the
condition( 60 <= X) AND (X <= 80).
The Program:
100 PRINT “ BEGIN DATA ENTRY-“
110 PRINT “TYPE 999 WHEN DONE”
120 INPUT X
130 IF X = 999 THEN 220
140 REM *** PROCESS X ***
94
150 IF(60 <= X) AND (X <= 80 ) THEN 190
160 LET N2 = N2 + 1
170 S2 = S2 +X
180 GOTO 120
190 LET N1 = N1 + 1
LET S1 = S1 + 1
200 LET S1 = S1 + X
210 GOTO 120
220 REM *** PRINT RESULTS ***
230 LET A1 = S1/N1
240 LET A2 = S2 /N2
250 PRINT “AVERAGE:”
260 PRINT “ NUMBERS 60 TO 80: “ , A1
270 PRINT “ ALL OTHER NUMBERS : “ , A2
280 END
9.14 LOOPS
Loops occur in all but the most elementary computer programs. In addition to providing the IF
and GOTO statements to construct loops, BASIC contains the FOR and NEXT statement.
95
Example . Here is a program to calculate and print the price of one, two, …, and six items selling
at seven for N1.00.
Explanation. The FOR/NEXT loop instruct the computer to execute the statements
LET P = U * K
PRINT K, P
Six times – once for each integer K from 1 to 6. These two statements are called the body or
range of the loop.
Example. Here is a loop to print 5, 4, 3, 2, 1 :
100 FOR N = 5 TO 1 STEP -1
110 PRINT N; “ “ ;
120 NEXT N
130 END
The general form or syntax of a FOR/NEXT loop is
FOR v = a TO b STEP c
.
. ( body of the loop)
.
NEXT v
96
Where v called the control variable denotes a simple numerical variable name, a, b, and c are
called initial, terminal, and step values, respectively denote arithmetic expressions. These
numbers can be any numbers, not just integers.
I
INPUT X
LET S = S + 1
S/1S/10
STOP
Note that if the value is more than or less than 1, the “STEP” is used.
97
Example. FOR M = 2 TO 9 STEP 3
.
. (body of loop)
.
NEXT M
And
FOR X = 10 TO 0 STEP – 0.5
.
. (body of loop)
.
NEXT X
Exercises
1. Show the output of the following programs
(a) 10 FOR J = 2 TO 4
20 PRINT J + 2
30 NEXT J
40 END
(b)
10 LET C = 0
20 LET X = 1
30 FOR Q = 1 TO 4.9 STEP 2
40 LET C = C +1
50 LET X = X * Q
60 NEXT Q
70 PRINT “ TIMES THROUGH LOOP = “; C
80 PRINT X
90 END
(C)
10 FOR K = 5 TO 1
20 PRINT “LOOP”
30 NEXT K
40 END
2. Each of the following programs contains an error either a syntax error that will cause an error
message to be printed or a programming error that the computer will not recognise but that will
cause incorrect results. In each case find the error and tell which of the two types it is
a.
10 REM 6% PROGRAM
20 FOR N = 1 TO 6
98
30 INPUT X
40 PRINT X, 0.06 * X
50 NEXT X
60 END
b.
10 REM PRINT THE NUMBERS
20 REM 1 3 6 10 15
30 LET S = 1
40 FOR N = 1 TO 15 STEP S
50 PRINT N
60 LET S = S +1
70 NEXT N
80 END
99
FOR X = …
.
.
NEXT X FOR I = …
. .
. .
FOR X = … FOR J = …
. .
. .
. .
c. correct FOR Y = … d. correct FOR K = …
. .
. .
. .
NEXT Y NEXT K
. .
. .
. .
NEXT I NEXT J
.
.
.
NEXT I
15 FOR I = 1 TO 3
20 FOR J = 1 TO 10
25 PRINT I;
30 NEXT J
35 PRINT
40 NEXT I
45 END
100
Exercises
ii. 10 FOR X = 1 TO 4
20 FOR Y = X + 1 TO 5
30 PRINT Y; “ “ ;
40 NEXT Y
50 PRINT
60 NEXT X
70 END
2. Each of the following programs contains an error- either a syntax or a programming error. Find
the error in each case and tell which of the two types it is.
i. A program to print: 1 2
1 3
1 4
2 3
2 4
3 4
10 FOR I = 1 TO 4
20 FOR J = 2 TO 4
30 IF I = J THEN 50
40 PRINT I; “ “; J
50 NEXT J
60 NEXT I
70 END
101
40 PRINT I; “ TIMES”; J; “=”; I*J
50 NEXT I
60 NEXT J
70 END
Examples :
1. Here is a program to “read” two numbers(17 and 18) and print their sum:
10 READ A
20 READ B
30 PRINT A + B
40 DATA 17, 8
50 END
When the program is run the result will be 25
The result: 7
-123
40
In a flowchart, the READ statements such as READ Q and READ M, N, P would appear in a
flowchart as follows:
READ M,N,P
READ Q
102
9.16 THE RESTORE statement
10 READ A, B
20 RESTORE
30 READ C
40 RESTORE
50 READ D, E, F
60 DATA 1,2, 3, 4, 5, 6
This program assigns values to A, B, C, D, E, and F as follows.
Line 10 assigns the first two data values 1 and 2 to A and B, respectively.
Line 20 positions the pointer back to the first datum
Line 30 assigns the first datum i.e. 1 to C
Line 40 once again restores the pointer to the first datum
Line 50 assigns the values 1, 2, and 3 to D, E, and F, respectively.
2. The following program displays two lists obtained from a single data list.
10 PRINT “ SCORES 70 OR MORE
20 FOR M = 1 TO 10
30 READ X
40 IF X >= 70 THEN PRINT “ “; X;
50 NEXT M
60 PRINT : RESTORE
70 PRINT “ SCORES LESS THAN 70 : ”;
80 FOR M = 1 TO 10
90 READ X
100 IF X < 70 THEN PRINT “ “ ; X ;
110 NEXT M
120 DATA 78, 84, 65, 32, 93, 58, 88, 76, 68, 83
130 END
The Result: SCORES 70 OR MORE: 78 84 93 88 76 83
SCORES LESS THAN 70: 65 32 58 68
Exercises:
1. Read and correct each error.
a. 10 READ X, X$ b. 10 READ B$
20 PRINT X$; X 20 IF B$ = HELLO THEN 10
30 DATA “1”; A 30 PRINT B$
40 END 40 DATA HELLO, GOODBYE
103
50 PRINT A3, A2, A1 50 LET M$ = B$
60 DATA 10, 20, 30 60 LET B$ =M$
70 END 70 PRINT B$
80 DATA 6, CAT, MOUSE
90 DATA 8, “WOMAN”, “MAN”
99 END
c. 10 FOR I = 1 TO 4 d. 10 LET I= 2
20 READ A, B, C 20 READ Y
30 IF A = 7 THEN 50 30 PRINT Y
40 PRINT C 40 LET I = I + 2
50 NEXT I 50 IF I <= THEN 20
60 DATA 2, 7, 4, 3, 4, 7, 7 60 RESTORE
70 DATA 6, 9, 12, 7, 1, 6 70 DATA 9, 3, 5, 8, 12
80 END 80 END
3. The following programs do not what they claim .Find and correct all errors.
i. 100 REM SUM = 5 ii. 100 REM AVERAGE N NUMBERS
110 LET S = 0 110 READ X
120 FOR I = 1 TO 5 120 IF X = 1E-30 THEN 160
130 READ I 130 LET S=0
140 LET S = S+ I 140 LET S = S+X
150 NEXT I 150 GO TO 120
160 PRINT S 160 PRINT “ AVERAGE IS”, S/N
170 DATA 7, 12, 14, -3, 6 170 DATA 18, 23,, 17, 22
180 END 190 END
Example. A program to print only the strings that contain exactly three characters.
10 FOR I=1 TO 6
20 READ X$
30 IF LEN(X$)=3 THEN PRINT X$
40 NEXT I
104
50 DATA “THE”,”I DO”,”ONE”,”OLD”,”THERE”,”127”
60 END
The Results:
THE
ONE
OLD
127
b) The string function LEFT$ - If S denotes a string and N a positive integer, then LEFT$(S,N) is
the string consisting of the first N characters contained in S. E.g LEFT$(“JOHN AND MARY”,4)
has the value “JOHN”.
Example.
10 LET Y$=”SEVEN”
20 FOR N=1 TO LEN(Y$)
30 PRINT LEFT$(Y$,N)
40 NEXT N
50 END
The Results:
S
SE
SEV
SEVE
SEVEN
c) The string function MID$ : This function can be used in two forms: If S is a string and M and
N are integers, then:
Example:
MID$(“JOHN AND MARY”,6,3) has the value AND
105
40 IF MID$(A$,I,1)=”A” THEN C=C+1
50 NEXT I
60 PRINT “NUMBER OF A’s IS”,C
70 END
The results:
? ABRACADABRA
NUMBER OF A’s IS 5
Function
Purpose
ABS(x) Gives the absolute value of x e.g ABS(-3)=3, ABS(7)=7
INT(x) Gives the greatest integer less than or equal to x e.g INT(2.6)=2, INT(7)=7, INT(-
4.35)=-5. For this reason INT is called the greatest-integer function INT(7-3.2)=3
SGN(x) Returns the value 1 if x is positive, -1 if x is negative, and 0 if x is 0. e.g SGN(15)=1,
SGN( -15)=-1, SGN(0)=0
SQR(x) Calculate the square root of x if x>=0. If x is negative, then result is error.
D=SQR(B^2-4*A*C)
SIN(x) Calculate the SIN of x, where x is in radians
COS(x) Calculate the COS of x, where x is in radians
TAN(x) Calculate the TAN of x, where x is in radians
ATN(x) Calculate the ARCTANGENT of x, where x is in radians: -π/2 ≤ x ≤ π/2
LOG(x) Calculate the Natural Logarithm ln(x); x must be positive
EXP(x) Calculate the exponential ex where e = 2.71828.. is the base of the natural logarithm
RND(x) Returns a pseudo random number between 0 and 1
Exercises
1. show the output of each of these programs.
a) 10 LET A$=”CYBERNETIC”
20 PRINT LEFT$ (A$, LEN(A$)/2)
30 END
b) 10 LET A$=”BIOLOGY”
20 LET B$=”PHYSICS”
30 LET C$=LEFT$(A$,3)
40 FOR I=1 TO LEN(A$,3)
50 LET C$=C$+MID$(B$,I,1)
60 NEXT I
106
70 PRINT C$
80 END
c) 10 LET B$=”A TO Z”
20 PRINT RIGHT$(B$,1) ; TO ; LEFT$(B$,1)
30 END
The SIN(x), COS(x), TAN(x) and ATN(x) are trigonometric functions such that they evaluate to
the Sine, Cosine, tangent and Arctangent of the numerical expression x. If the value of x denotes
an angle, it must be in radians.
For example 10 DEF FN Q(x)=x+x^3 defines a function with the name Q having the value
x+x^3 for any number x. DEF is a keyword which stands for define and FN is for function. Now
if the expression FN Q(2) is used in the program its value will be
2+23 =10. In a similar manner if Y is assigned the value 2, then FN Q(Y) will also be 10.
107
9.17.4 Conversion Functions
1. The CHARACTER function CHR$
The function CHR$ converts numeric codes to their corresponding characters. E.g.
CHR$(65)=”A” and CHR$(43)=”+”. (i.e. the ASCII numeric codes for “A” is 65, and “+” is 43.
9.18 ARRAYS
Arrays are used to store, examine , and retrieve ordered collection of items. As mentioned under
data structures, an array elements are arranged in sequence and are of the same data types.
The value of a subscripted variable is referenced in a program just as the values of simple
variables are referenced. For example,
LET G(2) =55
LET G(7) = G(2) + 10
Are two statements that assign 55 to the variable G(2) and 65 to G(7)
108
Examples:
1. The following program segment assigns values to G91), …G95), and G(6).
110 FOR I = 1 TO 6
120 READ G(I)
130 NEXT I
140 DATA 60, 55, 98, 80, 75, 93
2. The program segment below calculates the sum s of the odd-numbered entries in array G. The
sum is then stored in G(7).
110 LET S=0
120 FOR K=1 TO 3
130 LET S=S+G(2*K-1)
140 NEXT K
150 LET G(7) = S
Example 2: The control variable k is 1 on the first pass through the loop such that 2 *k-1 is the
subscript with value 1, which is added to s. Similarly, on second pass and on third pass. In line
150, the value of s after the third pass is assigned to G(7).
Note that subscripted variables can also be assigned values by INPUT statements just as with the
READ and LET statements. For example, the loop
FOR I = 1 TO 5
INPUT G(I0
NEXT I
can be used to input values for G(1) through G(5).
3. The following program segment illustrates that values assigned to subscripted variables are
retained until changed in another program statement, just as is the case with simple variables.
100 FOR I = 1 TO 5
101 READ G(I)
102 NEXT I
103 PRINT G(1), G(6)
104 LET G(6) = G(10
105 PRINT G(1), G(6)
106 DATA 60, 55, 98, 80, 75, 93
When the program is executed, the result printed will be
60 93
60 60
Note that in line 140, the value of G(1) is assigned to G(6).
109
4. The program segment below increases each entry of the array G by 3 and stores the resulting
values in a second array .P, in reverse order
100 FOR I = 1 TO 5
101 LET G(I) = G(I) + 3
102 NEXT I
103 FOR J= 1 TO 6
104 LET P(J) = G(7-J)
105 NEXT J
Now let’s look at the second loop lines 130 to 150. This loop creates a new array P. For J = 1, the
assignment statement is LET P(1) = G(6); for J=2, LET P(2) = G(5); ETC. Thus at the end of the
second loop execution, P becomes:
1 2 3 4 5 6
P 96 78 83 101 58 63
From the foregoing examples, it is can be seen that arrays provide a significant advantage over
simple variables, i.e., the subscripts may be variables or other numerical expressions rather than
just integer constants.
Q 1 2 3
1 207 93 41
2 165 110 33
3 93 87 15
4 51 65 8
This is a 4 X 3 array Q.
The value of a doubly subscripted variable is referenced in a program just as values of singly
subscripted variables are referenced. The subscripts can be integer constants, variables, or
expressions. For example, the following loop
FOR J = 1 TO 3
LET Q(1,J) = 5 * J
NEXT
Assigns the values 5, 10, and 15 to the first row, Q(1,1), Q(1,2), Q(1,3). In a similar manner, the
following loop adds 6 to each entry in the third column
Q(1,3), Q(1,3), Q(3,3), Q(4,3) of Q.
LET K = 3
FOR I = 1 TO 4
LET Q(I,K) = Q(I,K) + 6
110
NEXT
Examples:
1. The following program segment to read the votes data into an array Q.
100 REM READ VALUES FOR THE 4 BY 3 ARRAY Q
101 FOR I = 1 TO 4
102 REM READ VALUES FOR THE ITH ROW OF Q
103 FOR J = 1 TO 3
104 READ Q(I,J)
105 NEXT J
106 NEXT I
107 DATA 207, 93, 41, 165, 110, 33
108 DATA 93, 87, 15, 51, 65, 8
When I=1, the values are read into the first row of Q. Similarly for I = 2, values are read into the
second row, and so on until all the 12 values have been assigned to Q.
2. The following program segment uses the program in example 1, to count the number of votes
in each polling boot.
For this problem, we can develop an algorithm as follows:
i. Read the votes into array Q( as in example 1 )
ii. Determine and print how many votes in each polling boot.
Since all three entries in any row of Q correspond to votes by one of the four candidates, the task
in step(ii) is to add the three entries in each row of Q and print these four sums . Let S(1), S(2),
S(3), and S(4) denote the sum of the entries in the four rows. Thus
LET S(1) = Q(1,1) + Q(1,2) + Q(1,3)
LET S(2) = Q(2,1) + Q(2,2) + Q(2,3)
LET S(3) = Q(3,1) + Q(3,2) + Q(3,3)
LET S(4) = Q(4,1) + Q(4,2) + Q(4,3)
Now the program:
100 REM READ VALUES FOR THE 4 BY 3 ARRAY Q
101 FOR I = 1 TO 4
102 REM READ VALUES FOR THE ITH ROW OF Q
103 FOR J = 1 TO 3
104 READ Q(I,J)
105 NEXT J
106 NEXT I
107 REM DETERMINE AND PRINT THE ROW SUMS OF Q
108 PRINT “ PARTICIPATION IN VOTING BY VOTERS”
109 PRINT “ -------------------------------------------------------“
110 FOR I = 1 TO 4
111 LET S(I) = 0
112 NEXT I
113 FOR I = 1 TO 4
114 FOR J = 1 TO 3
115 LET S(I) = S(I) + P(I,J)
111
116 NEXT J
117 IF (I=1) THEN PRINT “ CANDIDATE A”,
118 IF (I=2) THEN PRINT “ CANDIDATE B”,
119 IF (I=3) THEN PRINT “ CANDIDATE C”,
120 IF (I=4) THEN PRINT “ CANDIDATE D”,
121 PRINT S(I)
122 NEXT I
123 DATA 207, 93, 41, 165, 110, 33
124 DATA 93, 87, 15, 51, 65, 8
125 END
Results:
PARTICIPATION IN VOTING BY VOTERS
--------------------------------------------------------
CANDIDATE A 341
CANDIDATE B 308
CANDIDATE C 195
CANDIDATE D 124
Example.
Write a program segment to interchange rows M and Q of an N x N array P.
The program:
100 FOR I = 1 TO N
120 LET X = P(M,I)
140 LET P(M,I)-P(Q,I)
160 LET P(Q,I) = X
180 NEXT I
Explanation: When I = 1 , the statements in lines 120 to 160 cause P(M,1) and P(Q,1), the first
entries in the Mth and Qth rows of P, to be interchanged. When I = 2, the second entries P(M,2)
and P(Q,2) are interchanged. Similarly for I = 3, 4, …, N.
Example: Write a program segment that reads values for N variables A(1), A(2), …, A(N).
The Program:
100 DIM A(40)
109 INPUT N
110 FOR I = 1 TO N
111 READ A(I)
112 NEXT I
112
Explanation: Line 100 reserves memory space for the 4 variables A(0) to A(40). If 30 is input for
N, the FOR/NEXT loop will assign values only to the variables A(1), A(2), …, A(30); the
remaining variables, A(0), A(31), …, A(40), although a variable, are simply not used. On the
other hand, if 40 is input for N, the FOR/NEXT loop will read values from DATA lines for A(1),
…, A(40). If a number 41 or larger is input, the attempt to read a value for A(40) will cause the
fatal error condition.
Note that when coding a program that will read input data into an array, you must ensure
that the DIM statement specifies an array large enough to accommodate all the input values. Also
note that instead of tying up a memory unnecessarily, expressions rather than constants to specify
dimensions for arrays used. For example,
100 INPUT N
110 DIM A(N)
Specifies the dimension of array A only during program execution. This capability is called
dynamic storage allocation. It is useful, if the available memory space is limited.
Example: Write a program to determine how many of each integer are there in a list of integers,
all between 1 and 100, contained in DATA lines. Input 999 to terminate.
Algorithm: 100 counts must be determined for each of the numbers between 1 to 100. C(1), C(2),
…, C(100) can be used to store these counts by reading each value in the DATA lines to
determine which of the 100 integers it is. Now, using X to denote the value being read gives rise
to the following algorithm:
i. Initialize: C(i) = 0 for I = 1 to 100
ii. Read a value for X
iii. If X = 999, print the results and stop
iv. Add 1 to C(X) and go to step(ii).
113
In (iii) the results is to be printed under two columns containing I and C(i) but not output with
C(I) = 0, i.e. if I is not in the given list. From the above algorithm we can derive the following
flowchart:
Print column
PHeadings
For I =1 to 1 00
C(I) > 0
Print I, C(I)
114
The Result: DATUM FREQUENCY
32 1
45 2
50 6
60 2
80 5
Example: Write a program that reads ten names into an array B$ and then search the array for
any names typed at the keyboard. When the word FINI is typed the program terminates.
If the program is executed and “GOMWALK” is typed, the result will be:
TYPE NAMES EXACTLY AS FOLLOWS
FIRST NAME (SINGLE SPACE) LAST NAME
115
TYPE ‘FINI’ WHEN FINISHED
? GOMWALK
GOMWALK IS NOT ON THE LIST
But if NENFORT GOMWALK is typed, it produces
? NENFORT GOMWALK
NENFORT GOMWALK IS IN THE LIST
9.21 SUBROUTINES
A function as defined earlier can be referenced as many times as necessary. Often, the same
sequence of statements are needed in several places in a program. This inclusion in several
places can be avoided by including this sequence of statements just once in a program. The
sequence of statements is called a subroutine.
Examples
1. Write a program to print the average of any two input values and also the average of their
squares.
116
140 PRINT “THE AQUARES ARE” ; A ; “ “ ; B
150 GOSUB 300
160 END
Explanation: The sub routine is from lines 300 to 330. Line 110 transfers control to line 300 then
the average of the two numbers is printed. The RETURN statement then transfers control to line
120, the line following the GOSUB statement just used. The squares of the two numbers are
found in lines 120 and 130. When line 150 is encountered, a second transfer of control to the
subroutine is done again. The statement RETURN then transfers control to the line 160, which
terminates the program.
2. Write a program to print a short report for each employee whose names and annual salary are
included in DATA lines. Use two subroutines, with the first to print the report and the second
simply to print a row of dashes, and it is called by the first subroutine.
117
510 FOR I=1 TO 30
520 PRINT “-“
530 NEXT I
540 PRINT
550 RETURN
Results:
--------------------------------------------------------------
EMPLOYEE NAME : OLUSEGUN OBASANJO
ANNUAL SALARY : 18500
WEEKLY SALARY : 355.77
--------------------------------------------------------------
--------------------------------------------------------------
EMPLOYEE NAME : ATIKU ABUBAKAR
ANNUAL SALARY : 25700
WEEKLY SALARY : 494.23
--------------------------------------------------------------
118