Download as pdf or txt
Download as pdf or txt
You are on page 1of 125

Federal University Lokoja -Introduction to Computer Science

CHAPTER ONE: INTRODUCTION AND HISTORY OF COMPUTERS

1.0 INTRODUCTION
Computers are indeed some of the most interesting and complex items of technology in
everyday use, but they are only around in such numbers because they are useful tools. A
computer is a device which accepts data in one form and processes it to produce data in
another form. This definition can be put in a more explicit form as, computer is an
electronic device that can receive a set of instructions, or program, and then carry out
this program by performing calculations on numerical data or by compiling and
correlating other forms of information. Note the three words used in the definition of
computer, data, program, and information. “Data” is the name given to basic facts, e.g.
the number of items sold by a business, the name of a customer, or the numerical values
used in mathematical formulae. A program is a set of instructions which is written in the
language of the computer. It is used to make the computer perform specific task such as
calculating interest to be paid to savings account holders or producing a payroll.
Information refers to a result when data is converted into a more useful or intelligible
form. In this situation data is said to be processed into information.

From the foregoing definition of a computer, it has a simplified representation as in


Fig.1.1.

Input Process Output

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.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
1
Federal University Lokoja -Introduction to Computer Science

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 later 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.
1.2.1 The Development of Calculating Devices
For over two thousand years, some simple calculating devices, notable among them
abacus were already in used. Abacus is still being used today in some parts of Asia for
calculation. This device is a mechanized pebble counter in which beads are strung on
wires or strings held in a frame. The beads are slid along the wires when counting,
adding, etc. Subsequently, significant developments of calculating devices took place
especially in the seventeenth century. Prominent among them include the invention of
logarithms by John Napier, a Scottish mathematician in 1614. Logarithms aid manual
multiplication and division. Later in 1617, Napier’s bones was devised for use as
multiplication aids. Napier’s bones was a set of rods carved from bone and used for
calculation. Three years later, which was in 1620 to be precise, William Oughted, an
English man, invented an analog calculating device otherwise called the slide rule. The
rule has scales divided in fixed and sliding scales respectively. Francis Bacon in 1623
made the first recorded use of binary codes for number representation.

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 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 made use of a shift mechanism while calculating. 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 effort. 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
2
Federal University Lokoja -Introduction to Computer Science

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.

An amateur mathematician and an 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
3
Federal University Lokoja -Introduction to Computer Science

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 holes 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 50 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).

1.2.2 Early Computers with changing Technology


Analog computers began to be built at the start of the 20th century. Early models
calculated by means of rotating shafts and gears. Numerical approximations of equations
too difficult to solve in any other way were evaluated with such machines. During both
world wars, mechanical and, 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
4
Federal University Lokoja -Introduction to Computer Science

arithmetic logic units were designed by semiconductor devices first. Thus the “first
generation” computers were valve based machines based upon Von Neumann design
principles.

1.2.3 Electronic Computers


Development in the electronics industry supported the computer designers to construct
faster computers. When the electronics industry came out with the transistor, the
computer industry manufactured machines with transistors. The transistor was invented
in 1948 by a team of scientists headed by William Shockley at the Bell Laboratories in
the U.S. Transistors are made from materials called semiconductors principally silicon(
the main elements in sand and rock) and germanium. The rapidly advancing field of the
electronics led to the construction of the first general-purpose all-electronic computer in
1946 at the University of Pennsylvania by the American engineer John Presper Eckert,
Jr. and the American physicist John William Mauchly. (Another American physicist,
John Vincent Atanasoff, later successfully claimed that certain 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 spacing,
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 TRANslator) was released in 1957 which makes it the first high level
programming language.

1.2.4 Circuit Integration


In the late 1960s the concept of circuit integration otherwise known as Integrated
Circuits, IC, became a reality in the electronics industry. The introduction of IC made it
possible to build a small one-centimeter chip, with the capability fabricating hundreds of
transistors on one silicon substrate, with inter-connecting wires plated in place. The IC
resulted in a further reduction in price, size, failure rate, and enabled construction of
5
Federal University Lokoja -Introduction to Computer Science

faster computers with more memory capacity. Computers built in this stage are called
“third-generation“ computers. The first IC was presented by Harwick Johnson of RCA
in 1953 although the inventor is said to be Jack Kilby of the USA. The third generation
computers were first released into the market in 1964 e.g. among the first series was
IBM 360 series.

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

To return, then, to the “switch-checking” capabilities of a modern computer: computers


in the
1970s generally were able to check eight switches at a time. That is, they could check
eight binary digits, or bits, of data, at every cycle. A group of eight bits is called a byte
(we shall look at it later in details), each byte containing 256 possible patterns of ONs
and OFFs (or 1’s a 0’s). Each pattern is the equivalent of an instruction, a part of an
instruction, or a particular type of datum, such as a number or a character or a graphics
symbol. The pattern 11010010, for example, might be binary data – in this case, the
decimal number 210 (recall the Number Systems) – or it might tell the computer to
compare data stored in its switches to data stored in a certain memory-chip location.

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
6
Federal University Lokoja -Introduction to Computer Science

computer needed in the future. The second 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 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.

1.3 COMPUTER GENERATIONS


1.3.1 First Generation (1945-1956)
With the onset of the Second World War, governments sought to develop computers to
exploit their potential strategic importance. This increased funding for computer
development projects hastened technical progress. By 1941 German engineer Konrad
Zuse had developed a computer, the Z3, to design airplanes and missiles. The Allied
forces, however, made greater strides in developing powerful computers. In 1943, the
British completed a secret code-breaking computer called Colossus to decode German
messages. The Colossus's impact on the development of the computer industry was
rather limited for two important reasons. First, Colossus was not a general-purpose
computer; it was only designed to decode secret messages. Second, the existence of the
machine was kept secret until decades after the war.

American efforts produced a broader achievement. Howard H. Aiken (1900-1973), a


Harvard engineer working with IBM, succeeded in producing an all-electronic calculator
by 1944. The purpose of the computer was to create ballistic charts for the U.S. Navy. It
was about half as long as a football field and contained about 500 miles of wiring. The
Harvard-IBM Automatic Sequence Controlled Calculator, or Mark I for short, was an
electronic relay computer. It used electromagnetic signals to move mechanical parts.
The machine was slow (taking 3-5 seconds per calculation) and inflexible (in that
sequences of calculations could not change); but it could perform basic arithmetic as
well as more complex equations.

Another computer development spurred by the war was the Electronic Numerical
Integrator and Computer (ENIAC), produced by a partnership between the U.S.
government and the University of Pennsylvania. Consisting of 18,000 vacuum tubes,
70,000 resistors and 5 million soldered joints, the computer was such a massive piece of
machinery that it consumed 160 kilowatts of electrical power. Developed by John
Presper Eckert (1919-1995) and John W. Mauchly (1907-1980), ENIAC, unlike the

7
Federal University Lokoja -Introduction to Computer Science

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.

1.3.2 Second Generation Computers (1956-1963)


By 1948, the invention of the transistor greatly changed the computer's development.
The transistor replaced the large, cumbersome vacuum tube in televisions, radios and
computers. As a result, the size of electronic machinery has been shrinking ever since.
The transistor was at work in the computer by 1956. Coupled with early advances in
magnetic-core memory, transistors led to second generation computers that were
smaller, faster, more reliable and more energy-efficient than their predecessors. The first
large-scale machines to take advantage of this transistor technology were early
supercomputers, Stretch by IBM and LARC by Sperry-Rand. These computers, both
developed for atomic energy laboratories, could handle an enormous amount of data, a
capability much in demand by atomic scientists. The machines were costly, however,
and tended to be too powerful for the business sector's computing needs, thereby
limiting their attractiveness. Only two LARCs were ever installed: one in the Lawrence
Radiation Labs in Livermore, California, for which the computer was named (Livermore
Atomic Research Computer) and the other at the U.S. Navy Research and Development
8
Federal University Lokoja -Introduction to Computer Science

Center in Washington, D.C. Second generation computers replaced machine language


with assembly language, allowing abbreviated programming codes to replace long,
difficult binary codes.

Throughout the early 1960's, there were a number of commercially successful second
generations computers used in business, universities, and government from companies
such as Burroughs,
Control Data, Honeywell, IBM, Sperry-Rand, and others. These second generation
computers were also of solid state design, and contained transistors in place of vacuum
tubes. They also 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.

1.3.3 Third Generation Computers (1964-1971)


Though transistors were clearly an improvement over the vacuum tube, they still
generated a great deal of heat, which damaged the computer's sensitive internal parts.
The quartz rock eliminated this problem. Jack Kilby, an engineer with Texas
Instruments, developed the integrated circuit (IC) in 1958. The IC combined three
electronic components onto a small silicon disc, which was made from quartz. Scientists
later managed to fit even more components on a single chip, called a semiconductor. As
a result, computers became ever smaller as more components were squeezed onto the
chip. Another third-generation development included the use of an operating system that
allowed machines to run many different programs at once with a central program that
monitored and coordinated the computer's memory.

9
Federal University Lokoja -Introduction to Computer Science

1.3.4 Fourth Generation (1971-Present)


After the integrated circuits, the only place to go was down - in size, that is - Large scale
integration (LSI) could fit hundreds of components onto one chip. By the 1980's, very
large scale integration (VLSI) squeezed hundreds of thousands of components onto a
chip. Ultra-large scale integration (ULSI) increased that number into the millions. The
ability to fit so much onto an area about half the size of a U.S. dime helped diminish the
size and price of computers. It also increased their power, efficiency and reliability. The
Intel 4004 chip, developed in 1971, took the integrated circuit one step further by
locating all the components of a computer (central processing unit, memory, and input
and output controls) on a minuscule chip. Whereas previously the integrated circuit had
had to be manufactured to fit a special purpose, now one microprocessor could be
manufactured and then programmed to meet any number of demands. Soon everyday
household items such as microwave ovens, television sets and automobiles with
electronic fuel injection incorporated microprocessors.
Such condensed power allowed everyday people to harness a computer's power. They
were no longer developed exclusively for large business or government contracts. By the
mid-1970's, 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
10
Federal University Lokoja -Introduction to Computer Science

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

11
Federal University Lokoja -Introduction to Computer Science

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 2ND 5TH


GENERATION GENERATION 3RD G ENERATION 4TH GENERATION GENERATION
(1951-1958) (1959-1963) (1964-1978) (1979-PRESENT) (PRESENT AND
SIZE(Typical Room size Closet size Desk-size BEYOND)
Credit card-size
Desktop and Laptop
Computers) Mainframe mainframe Minicomputer Micro?
Very-Large-Scale
Large-Scale(LSI)
Integrated semi- Integrated(VLSI)
CIRCUITRY Vacuum tubes Transistors Semi-Conductor
conductor circuit superconductor
circuits
circuits?
DENSITY(Circuits Hundreds of
One Hundreds Thousands 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(Capacity Hundreds of
Thousands Tens of Thousands Millions Billions?
in characters) Thousands
COST(Per million
$10(N1440) $1.00(1440) $0.10 $0.001 $0.0001?
instructions)

12
Federal University Lokoja -Introduction to Computer Science

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.

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
13
Federal University Lokoja -Introduction to Computer Science

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.

Magnetic Ink Character Recognition (MICR)


In this method, human readable characters are printed on documents such as cheque
using special magnetic ink. The cheque can be read using a special input unit, which can
recognize magnetic 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.

14
Federal University Lokoja -Introduction to Computer Science

Optical Mark Reading and Recognition (OMR)


In this method, special pre-printed forms are designed with boxes which can be marked
with a dark pencil or ink. Such a document is read by a document reader, which
transcribes the marks into electrical pulses which are transmitted to the computer. These
documents are applicable in the areas where responses are one out of a small number of
alternatives and the volume of data to be processed is large. For example:

• Objective type answer papers in examinations in which large number of


candidates appear. For example JAMB answers sheets.
• Market surveys, population survey etc.,
• Order forms containing a small choice of items.
• Time sheets of factory employees in which start and stop times may be marked.

The advantage of this method is that information is entered at its source and no further
transcription is required.

Optical Character Recognition (OCR)


An optical scanner is a device used to read an image, convert it into a set of 0's and 1's
and store it in the computer's memory. The image may be hand-written document, a
typed or a printed document or a picture.

15
Federal University Lokoja -Introduction to Computer Science

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.

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.

16
Federal University Lokoja -Introduction to Computer Science

2.1.2 Memory Unit


It is used to store the Programs and data. One of the important elements of a computer is
the main storage or main memory. It is like a human memory as it can retain or store
information which may later be recalled or accessed. Data must be transferred to main
storage before it can be processed by the processor. Its operation is wholly electronic,
and consequently very fast and reliable. Data is almost instantly accessible from main
memory because of its electronic operation and close proximity to the processor. For
example, an item of data may be retrieved from main storage in much less than one
millionth of one second. For this reason main storage is called immediate access storage.

Uses of Main Storage


Main storage ideally, would be used to store all data requiring processing, in order to
achieve maximum processing speeds. It stores Instructions awaiting execution or to be
obeyed, Instructions currently being obeyed, Data awaiting processing, Data currently
being processed, and data awaiting output. An area of main storage being used for data
currently being processed is called a Working Storage area and an area being used for
data awaiting processing or output is called a buffer area

The operational Characteristics of Main Storage


The main storage is divided into locations, each location with its own address. Data is
placed into a location. This can be imagined as if the locations are arranged like a set of
boxes. The boxes are numbered from zero upwards so that each box can be identified
and located. The “location in main storage” corresponds to one of the boxes, and the
“location address” corresponds to the number of the box.
e.g.

0 1 2 3 etc

17
Federal University Lokoja -Introduction to Computer Science

Once data is placed in a location in main storage it remains there until it is replaced by
other data. Data placed into the same location will destroy what was there previously.
Accessing and fetching data from main storage is really a copying action which does not
result in the data being deleted from main storage. A data can be fetched from the
locations in main memory in any order, and the time taken does not depend on the
position of the locations. This order of accessing data is called Random Access. On the
other hand if data access is by reading through from the first location to the last, then the
mode of access is called Serial or Sequential Access.

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. A bit 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 manufacture. A set of instructions stored in
this way is said to be “hard-wired”, and is often called firmware.

There are other types of ROM such as

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.

18
Federal University Lokoja -Introduction to Computer Science

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 than 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 supposed to be stored in main storage so that all internal operations can be
carried out at maximum speed, but because main 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 be 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).

1 Kilobyte (KB) 1024 Bytes


1MegaByte (MB) 1KB x 1KB
1GigaByte (GB) 1KB x 1KB x 1KB
1 Terabyte (TB) 1KB x 1KB x 1KB x 1KB

2.1.3 CENTRAL PROCESSING UNIT


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.
19
Federal University Lokoja -Introduction to Computer Science

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

The functions of the CPU are


1. to control the use of main storage to store data and instructions
2. to control sequence of operations
3. to give commands to all parts of the computer system
4. to carry out processing

The processor controls the input of data and its transfer into main storage, processes the
data, and then sends the result to output units of various types. At all stages data
transmission is electronic.

2.1.4 Output Devices


When a data is processed the results are taken from main storage and fed to an output
device. The output device could be a printer or a video display screen. If it is a printer,
the information is automatically converted to a printed form (hard copy). Alternatively,
data may be displayed on a screen similar to that used in a television set(soft copy).
Some typical output devices are hereby presented.

Visual Display Unit (VDU)


The VDU is the output device that produces temporary output called soft copy, on its
screen.
There are two common kinds of VDU:
20
Federal University Lokoja -Introduction to Computer Science

- Cathode Ray Tube (CRT) monitor


- Liquid Crystal Display (LCD) Panel

Cathode Ray Tube (CRT) monitor


A CRT monitor looks like a television and consists of a screen and a case to house the
electrical components. The large picture tube inside the monitor is actually the CRT.
The front pant of the tube where output is displayed is the screen. There are two types of
CRT monitors:
- The monochrome monitor (usually black and white)
- Colour monitor
Most desktop computers use a CRT monitor.

A CRT monitor Figure 5.7 (a)

Liquid Crystal Display (LCD) Panel


A LCD Display panel is a thin display screen that does not use the cathode ray tube
technology.
As the name implies, it is a flat panel containing a liquid crystal such as mercury. LCD
panels are mostly used in portable computers.

An LCD Panel Figure 5.7 (b)

Printer
21
Federal University Lokoja -Introduction to Computer Science

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

Dot Matrix Printer


The Dot Matrix Printer can print both text and graphics. The printer head consists of a
number of small pins arranged in form of a matrix. The control circuit makes the pins
strike the ribbon and produce tiny dots on the paper as the print head moves across the
paper. The matrix of dots can form any text and graphics.

A Dot-Matrix Printer Figure 5.10

Ink Jet Printer


The ink jet printer works in a way similar to that of the dot matrix printer. However,
nozzles are used instead of pins. Tiny ink droplets are projected from the nozzles into
the paper to form any text or graphics.

An Ink Jet Printer Figure 5.11

22
Federal University Lokoja -Introduction to Computer Science

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.

A Laser Printer Figure 5.12

2.1.5 Secondary (Auxiliary) Storage Devices


For a computer to function, programs and data need to be stored in the main memory.
There the can computer functions without secondary storage devices. However, a
computer is more useful and works better with secondary storage devices. This is
because the computer does not work with all programs and data at the same time.

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
23
Federal University Lokoja -Introduction to Computer Science

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.

DID YOU KNOW?


That auxiliary storage device permanently holds 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 devices that hold the disk
and carries out read/Write operations are called a disk drive. There two types of
magnetic disk:
- The Floppy Disk
- The Hard Disk

Floppy Disk (or Diskette)


The floppy disk also called diskette is made from a plastic material coated with a
magnetic material. It is usually enclosed in a square jacket to protect it from dust and
finger prints, and cannot be removed from the jacket. Diskettes are available in several
sizes but the most widely used are the 5 1/4 inch type, which has a plastic jacket, and the
3 1/2inch type with a rigid vinyl jacket. The later has a higher storage capacity (1.44Mb)
and (2MB) than the former and is more convenient to use. As a result the 5 1/4 inch type
is rarely seen and is fast disappearing.

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
24
Federal University Lokoja -Introduction to Computer Science

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

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.

25
Federal University Lokoja -Introduction to Computer Science

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.

26
Federal University Lokoja -Introduction to Computer Science

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.

A Cassette Figure 5.18

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.

27
Federal University Lokoja -Introduction to Computer Science

Figure 20. A CD-ROM Drive and CD-RW

28
Federal University Lokoja -Introduction to Computer Science

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, and
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.

3.1.1 Analog Computers


The analog computer is an electronic or hydraulic device that is designed to handle input
in terms of, e.g., voltage levels or hydraulic pressure, rather than numerical data. The
simplest analog calculating device is the slide rule, which employs lengths of specially
calibrated scales to facilitate multiplication, division, and other functions. In a typical
electronic analog computer, the inputs are converted into voltages that may be added or
multiplied using specially designed circuit elements. The answers are continuously
generated for display or for conversion to another desired form. Analog computers are
likened to measuring instruments such as thermometers and voltmeters. The output from
analog computers is often in the form of smooth graphs from which information can be
read. For example, Car Speedometer, thermometer, fuel pumps, etc.

3.1.2 Digital Computers


Everything that a digital computer does is based on one operation: the ability to
determine if a switch, or “gate”, is open or closed. That is, the computer can recognise
only two states in any of its microscopic circuits: on or off, high voltage or low voltage,
or- in the case of numbers 0 or 1.

The speed at which the computer performs this simple act, however, is what makes it a
marvel of modern technology. Computer speeds are measured in megahertz, or millions
of cycles per second. A computer with a “clock speed” of 33 MHz is capable of
29
Federal University Lokoja -Introduction to Computer Science

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 COMPUTER CLASSIFICATION BY SIZE AND POWER

3.2.1 Super computers


A broad term for one of the fastest computers currently available. Such computers are
typically
used for number crunching including scientific simulations, (animated) graphics,
analysis of geological data (e.g. in petrochemical prospecting), structural analysis,
computational fluid dynamics, physics, chemistry, electronic design, nuclear energy
research and meteorology. Perhaps the best known supercomputer manufacturer is Cray
Research

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

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.
30
Federal University Lokoja -Introduction to Computer Science

3.2.4 Microcomputers.
It is a further step in miniaturization in which the various integrated circuits and
elements of a computer are replaced by a single integrated circuit called a “chip”.
PURPOSE: There are computers designed for a particular job only: to solve problems of
restricted nature e.g. computers designed for use in weapons guidance systems. A word
processor used in the production of office documents, letters, contracts, etc. These type
of computers are called special purpose computers. Computers designed to solve a wide
variety of problems are called general purpose machines. They can be temporarily
become special purpose through adaptation.
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.
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.1 System Software


These are programs with associated documentation which control the way the computer
operates or provide facilities which extend the general capabilities of the system. An
example of system software is a suite of programs called the operating system. The
operating system controls the performance of the computer by doing a variety of jobs to
ensure the proper, orderly and efficient use of hardware by applications programs.
Applications programs can only work when used in conjunction with the operating
system.

Systems software is classified into the following categories:


• Systems management programs such as: operating system (MS-DOS, OS/2 WARP;
Windows
• 9x/ NT/2000/XP; Linux, Xenix Unix, etc);
• Operating environment e.g. Graphical User Interface;
• Database management systems (DBMS); \
• Telecommunications monitors e.g. front end processors, network servers.
• System support programs such as: system utilities; performance monitors; security
monitors.
• System Development programs such as: programming language translators
(compiler,
• Interpreter, assembler); programming environments; CASE packages

31
Federal University Lokoja -Introduction to Computer Science

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)
c) Spreadsheets (Microsoft Excel, Lotus 1-2-3, etc),
d) Desktop publishing software (Microsoft PageMaker)
e) Presentation software ( e.g. PowerPoint),
f) Payroll packages

4.2 OPERATIONS ON DATA


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.

4.1.2 Data Types


A data type consists of
1. a set of data values
2. a set of operations which may be used singly whilst others may be combined together
and arranged to form other data items. The former are classified as simple data types
whereas the latter are classified as data structures or data aggregates.

The simple data types are


1. Numeric Integer
2. Numeric Real
3. Character
4. Boolean( Logical)

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

32
Federal University Lokoja -Introduction to Computer Science

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

Within the computer numerical data types are represented as


1. Binary Coded Decimal (BCD) - i.e. representation in which each decimal digit in the
number is coded separately e.g. 39 decimal is represented as 0011, 1001. BCD is a 4 bit
code used for coding numeric values only, as follows:

2. Pure Binary: in which the whole number is converted to binary e.g. 39 decimal is
represented as 10011.
33
Federal University Lokoja -Introduction to Computer Science

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.3 Arithmetic Operations


In computer programming languages symbols are commonly used instead of arithmetic
operators such as +, -, x, and . The corresponding symbols here are +, -,* and / or div.
For exponentiation e.g 32, 3 ^ 2 or 3**2 is used.

Operations on Integers - Div and Mod


These two operations apply to integers and produce integer results. Div produces and
integer quotient and Mod produces an integer remainder. e.g. 11 div 4 = 2; 11 mod 4 =
3.
Note that dividing zero by zero leads to undefined result while division by zero leads to
infinite result. Concatenation is an operation which adds one string onto the end of
another string. The operator symbols commonly used for concatenation are either ‘+’ or
‘&’ E.g. “ALEX” & “JAMES” is “ALEXJAMES”.

4.2.4 Logic Relation Operators -


These give Boolean values when applied to data types such as integers, reals and
characters. These operators are

There are 3 basic Boolean operations; NOT, OR, and AND.


A proposition is a statement that can either be true or false.

34
Federal University Lokoja -Introduction to Computer Science

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.

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
35
Federal University Lokoja -Introduction to Computer Science

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

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
36
Federal University Lokoja -Introduction to Computer Science

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

Some programming languages declare data types in very different ways.


A variable name does not have an associated value until it has been assigned one. This
process or assigning values to variables before using them is called “initialization”. E.g.
pi = 3.142

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.

37
Federal University Lokoja -Introduction to Computer Science

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

38
Federal University Lokoja -Introduction to Computer Science

Fig. 21 The semantics of the selection if_then_else

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.

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.

39
Federal University Lokoja -Introduction to Computer Science

ii) Semantics of a case statement.

40
Federal University Lokoja -Introduction to Computer Science

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.

41
Federal University Lokoja -Introduction to Computer Science

42
Federal University Lokoja -Introduction to Computer Science

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

When a subprogram is well constructed, it should be self-contained, performed well


defined operations on well defined data and have an internal structure which is
independent of the program in which it is contained. A subprogram with all these
features is called a program module

43
Federal University Lokoja -Introduction to Computer Science

4.6 FUNCTIONS
Many high level programming languages have inbuilt functions such as, square root
function
“sqrt”. When a required function is not inbuilt it is sometimes possible for the
programmer to define it for him or herself.

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

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.

44
Federal University Lokoja -Introduction to Computer Science

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)

Now a form of the procedure follows from the preceding example.

45
Federal University Lokoja -Introduction to Computer Science

CHAPTER FIVE: APPLICATION AREAS


5.1 REASONS FOR USING COMPUTER

Virtually computers are employed to solve problems in almost every areas of human endeavour.
Now-a-days computer is playing a main role in everyday life it has become the need of people just
like television, telephone or other electronic devices at home. It solves the human problems very
quickly as well as accurately. The important characteristics of a computer are described below:

Storage
A computer has internal storage (memory) as well as external or secondary storage. In secondary
storage, a large amount of data and programs (set of instructions) can be stored for future use. The
stored data and programs are available any time for processing. Similarly information downloaded
from the internet can be saved on the storage media.

Accuracy
In addition to being very fast, computer is also very accurate device. it gives accurate output result
provided that the correct input data and set of instructions are given to the computer. It means that
output is totally depended on the given instructions and input data. If input data is in-correct then the
resulting output will be in-correct. In computer terminology it is known as garbage-in garbage-out.

Speed
The computer is a very high speed electronic device. The operations on the data inside the computer
are performed through electronic circuits according to the given instructions. The data and
instructions flow along these circuits with high speed that is close to the speed of light. Computer
can perform million of billion of operations on the data in one second. The speed of computer is
usually measure in Mega Hertz (MHz) or Giga Hertz (GHz). It means million cycles units of
frequency is hertz per second. Different computers have different speeds.

Arithmetical and Logical Operations


A computer can perform arithmetical and logical operations. In arithmetic operations, it performs the
addition, subtraction, multiplication and division on the numeric data. In logical operation it compares
the numerical data as well as alphabetical data.

Reliability
The electronic components in modern computer have very low failure rate. The modern computer can
perform very complicated calculations without creating any problem and produces consistent
(reliable) results. In general, computers are very reliable. Many personal computers have never needed
a service call.

46
Federal University Lokoja -Introduction to Computer Science

Retrieving data and programs


The data and program stored on the storage media can be retrieved very quickly for
further processing. It is also very important feature of a computer.

Automation
A computer can automatically perform operations without needing the user during the
operations. It controls automatically different devices attached with the computer. It
executes automatically the program instructions one by one.

Versatility
Versatile means flexible. Modern computer can perform different kind of tasks one by
one of simultaneously. At one moment you are playing game on computer, the next
moment listening music & you are composing and sending emails etc.

Communications
Today computer is mostly used to exchange messages or data through computer
networks all over the world. For example the information can be received or send
through the internet with the help of computer.

Diligence
A computer can continually work for hours without creating any error. It does not get
tired while working after hours of work it performs the operations with the same
accuracy as well as speed as the first one.

No Feelings
Computer is an electronic machine. It has no feelings. It detects objects on the basis of
instructions given to it based on our feelings, taste, knowledge and experience: we can
make certain decisions and judgments in our daily life. On the other hand, computer
cannot make such judgments own. Their judgments are totally based on instructions
given to them.

Common data
One item of input data can affect several different procedures. For example a customer
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.
5.2 MAIN AREAS OF APPLICATION
5.2.1 Commercial Applications
i) Routine administrative, or clerical e.g. payroll and order processing
ii) Management: A company needs information on which to base decisions concerning the
current
operations and future plans. It requires this information to be timely and accurate. These
47
Federal University Lokoja -Introduction to Computer Science

examples
are:
(a) Stock Control
(b) Production Controls
c) Labour Control
d) Network Analysis
e) Linear Programming
f) Financial Modeling.

5.2.2 Scientific, Engineering and Research Applications


This covers the use of Computers for complex calculations, the design, analysis and control
of physical systems, and the analysis of experimental data or results, i.e. scientific
processing and Industrial Computing. Some of these applications exploiting the full
computational power of computers are:
a. Weather forecasting systems
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.

5.2.3 Computers in the Government


Computers are used to keep records of the people that the government serves. Several
government agencies use computers to facilitate the task they are required to give to the
people.

48
Federal University Lokoja -Introduction to Computer Science

CHAPTER SIX: NUMBER SYSTEMS AND COMPUTER ARITHMETICAL PROCEDURE


6.1 NUMBER SYSTEM
The number systems used 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 shorthand for binary. This
numbering system can be summarized as follows.

Number system
Binary
Octal
Decimal
Hexadecimal

Symbol used
0,1
0,1,2,3,4,5,6,7.
0,1,2,3,4,5,6,7,8,9.
0,1,2,3,4,5,6,7,8,9,A,B,C,D,

E.g.
a) Conversion from
6 5 4 3 2 1 0
i) 1101101 → Decimal = 1x2 + 1 x 2 +0 x 2 +1x2 +1x2 +0x2 +1x2 = 109
2
ii) 109 → Binary

49
Federal University Lokoja -Introduction to Computer Science

Similarly conversion from octal to decimal and back to octal takes the same format. Likewise conversion
from Hexadecimal to decimal and back to Hexadecimal.

(b) Conversion b/w Octal and Binary.

The conversion from binary to octal is easily executed by grouping the binary number digits into three
from right to left, adding extra zeros at the left end if necessary.

E.g. Convert 1110111000010 → Octal


2
Grouping into threes from right to left results in Binary digits

50
Federal University Lokoja -Introduction to Computer Science

c) Conversion b/w Hexadecimal and Binary.


As it is in octal and Binary, the groupings of the binary digits to Hexadecimal equivalent is in Fours from
right to left adding extra zeros when necessary. The conversion takes viz.

It is easier when converting from Hexadecimal to octal to first of all convert to Binary then to Octal. As in
this example let’s convert to Binary

51
Federal University Lokoja -Introduction to Computer Science

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.
52
Federal University Lokoja -Introduction to Computer Science

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 10110
2
(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

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.

53
Federal University Lokoja -Introduction to Computer Science
6.1.3 Binary Representations of negative Numbers
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 0
+1 0 0 1
+0 0 0 0
(Redun
dant)-0 1 0 0
-1 1 0 1
-2 1 1 0
-3 1 1 1

b) One’s Complement method


Sign
+3 0 1 1
+2 0 1 0
+1 0 0 1
+0 0 0 0
(Redun
dant) -0 1 0 0
-1 1 1 0
-2 1 0 1
-3 1 0 0

c) Two’s complement method


Sign
+3 0 1 1
+2 0 1 0
+1 0 0 1
0 0 0 0
-1 1 1 1
-2 1 1 0
-3 1 0 1
-4 1 0 0
54
Federal University Lokoja -Introduction to Computer Science

Range: +3 to -4
Notice that there is no redundant representation of zero using two’s 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 two’s complement by adding 1.
Note that Two’s complement arithmetic is more straight forward than one’s complement arithmetic
E.g. when adding two negative numbers:
Two’s complement one’s complement
1 1 12 1 1 02
1 1 12 1 1 02
1 1 1 02 1 1 0 02
Ignore 1 Add carry

1 0 12

55
Federal University Lokoja -Introduction to Computer Science
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
.0 x 2
the required result is 101
3. Convert –1/3 to binary using 5 bits for your representation and two’s 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.1011 – 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
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.

56
Federal University Lokoja -Introduction to Computer Science
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 as 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
Set 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 CS101 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 “( )”. 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. An array can be two-
57
Federal University Lokoja -Introduction to Computer Science

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

This table can be represented in an array called


56 44
42 36
89 73
A= 65 86
48 51

7.13. 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”.

58
Federal University Lokoja -Introduction to Computer Science

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
Character 2 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
position
characters
Contents long.
J A E S * K A T Y * A N N * A L E X *
ND RD TH
comment 2 STRING 3 STRING 4 STRING

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
ND RD TH
Comment 1ST 2 STRING 3 STRING 4 STRING
STRING

7.1.4 Records

Records are like one dimensional array 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:

59
Federal University Lokoja -Introduction to Computer Science

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.

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
60
Federal University Lokoja -Introduction to Computer Science

end
The facilities for creating records are only in some high level languages such as Pascal, Cobol,
Modula, etc.

7.1.5 Arrays of Records (Tables)


If in the event we want to store the following table of data for a set of Students’ examinations
Candidate Number Candidate Name Average Mark
1505 Samson 60.5
1510 James 88.4
1515 Bill 90.2
1520 Joseph 66.0
1525 Henry 59.8
1530 Blessing 77.4

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.

ALEX DOES NOT LIKE MANGO

We regard each word in the sentence as a data- item or datum which is linked to the next datum
61
Federal University Lokoja -Introduction to Computer Science

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:
LEFT POINTER DATUM RIGHT POINTER

1) 56 is the first datum called the parent or root node


2) 42 is added to the tree using the rule “lower numbers to the left, higher numbers to the right,”

56 -1
A right pointer which is a terminator

-1 42
-1 Here both pointers are terminators. Thus 42 is a
terminator node. It is a left descendant of the parent node.

62
Federal University Lokoja -Introduction to Computer Science

3) Next 89 is added.

56

2 3

-1 89 -1
-1 42 -1

4) 65 is added next, then


5) 48 next.

56

2 3

42
89

5 4

-1 42 -1 89

We notice that

i) The leftmost node contains the smallest number

ii) The rightmost ode contains the highest number.


63
Federal University Lokoja -Introduction to Computer Science

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

The Terminator Symbol e.g.

Add Number to Calculate


Subtotal Profit
Process Symbol e.g.

Sort Used to represent symbol that


transactions has been set out in detail
elsewhere

A pre-defined process symbol e.g.

Is
Yes No
Transaction
Decision Symbol e.g. a Credit?

There is only one entry point


and at least two exits

64
Federal University Lokoja -Introduction to Computer Science

Input
name

Input /Output Symbol e.g. Used where data input or output is to be performed

Used to shown the flow/path of a sequence of symbols. Vertical lines without arrow heads are
assumed to flow top to bottom. Horizontal lines without arrow heads are assumed to flow left to
right.

used to add explanatory notes or descriptions.

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.

65
Federal University Lokoja -Introduction to Computer Science
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. It is a high-level
programming language invented in 1964 at Dartmouth College. Beginner Computer
Programmers use BASIC because it is easy to learn. BASIC is used in numerous
educational and commercial applications (eg. Visual Basic for Applications, VBA).

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

Installing the BASIC Software (Compiler)


1. Download a copy of Basic Compiler free application from a website online (eg.
www.justbasic.com)
2. Save the downloaded executable file (eg. jbwin101.exe) to a known location on the
computer
3. Run the executable by double-clicking on jbwin101.exe and follow the on-screen
instructions to install the program (ignore warning messages)
4. Read the welcome screen and get acquainted with the program features. Read the
help section and complete tutorial.

66
Federal University Lokoja -Introduction to Computer Science

5. Endeavor to run as Administrator each time you want to use the application.

KEY FEATURES OF A PROGRAMMING LANGUAGE


A Computer programming language (eg. BASIC) has the following basic features;
• Commands – This refer(s) to words that carry out specific operation. They act on
strings or variables.
• Variables - Refer to values that can be changed or altered by user input or a function
• Strings – Refer to a series of characters that may be provided by the user or
manipulated by commands or functions.
• Functions – These refer to operations that transform a string or variables to specific
results. Eg. Mathematical functions
• Routines and(or) Subroutines – These are sets of self-contained parts of a program
that execute commands and functions.
• Loops - Refers to a repeated operation initiated with a command
• Conditionals - Refer to commands that are executed only if certain (specified)
condition

Features of a Computer Program


All computer programs share common features, which include;
• Architecture – This defines the overall structure of a program
• Syntax – This defines the specific order of commands, functions and statements
• Statements – these are the lines of codes that comprise the program

9.2 PROBLEM SOLVING


A computer program consists of a sequence of instructions to the computer. These
instructions describe a step-by-step process for carrying out a specified task. Such a
process is called an algorithm. Since a computer program describes an logarithm, the
process. Algorithms. An algorithm is a prescribed set of well-defined rules and processes
for solving a problem in a finite number of steps

67
Federal University Lokoja -Introduction to Computer Science

E.g. Here is an algorithm to determine the largest number in a list of numbers.


Let’s use two symbols:
L to denote the largest of the numbers already read
N to denote the number currently being read
Now the algorithm
1. Read the first number and denote it by L
2. Read the next number and denote it by N
3. if L is at least as large as N, skip the next step
4. Assign the number N to L
5. If all numbers have not been read, go to step (2)
6. print the value of L and stop.

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.

Thus the last values of L is 8.


68
Federal University Lokoja -Introduction to Computer Science

9.3 A First Look at BASIC

The medium of communication with a computer before it will performed any service for
us is the computer program. BASIC is one among many computer programming
languages that exist today. It has rules of grammar called syntax and meanings to words
called semantics. E.g. here is a BASIC program whose purpose is described in the first
line:

100 REM PROGRAM TO AVERAGE 3 NUMBERS


110 REM X, Y, AND Z DENOTE THE NUMBERS
120 REM A DENOTES THE AVERAGE
130 LET X = 43
140 LET Y = 27
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 cannot 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


69
Federal University Lokoja -Introduction to Computer Science
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

m
nEm = n x 10 . Here n may be any integer or decimal, but m must be an integer, E stands for “
4 -2 3
exponent”. E.g. 1E4 = 1 X 10 ; -13.6E-2 = -13.6 X 10 ; .12345E03 = .12345 X 10 .

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.

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

9.3.2 String Constants and Variables


A string constant is a sequence, or string, of BASIC characters enclosed in quotation
marks e.g. “ INCOME”; “X=”; “ ***** “; “567”; “ 19 APRIL 1776”. Thus the value of
the string constant “ NANCY JONES” is the string NANCY JONES. A string may
contain up to 255 characters.
Variables whose values are strings are called string variables. Their names differ from
numerical variable names such that their last character must be a dollar sign($). Thus the
B$, NAMES$, A45$ AND SSN$ are admissible names of string variables but WORD$ is
not - it contains the reserved word OR. Also, NAME1$ and NAME2$ mean the same
70
Federal University Lokoja -Introduction to Computer Science

variable since variable names are distinguished only by their first two characters.
9.3.3 Arithmetic Operations and expressions
BASIC uses the following symbols to denote arithmetic operations

Symbol Meaning Priority

- Negation 1

^ Exponentiation 2

* Multiplication 3

/ Division 4

+ Addition 4

- Subtraction 4

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
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
(2) –5 ^ 2. Since negation (-) has highest priority, it is performed first. Thus –5 ^ 2 = (-5)
= 25. Parentheses are used in BASIC expressions just as in ordinary algebra. E.g. 5 * 2/3
can be written as (5 * 2 ) / 3.

(3) Evaluate 3 7 + MN when M = 4 and N = 5 . This is (7 + M * N) ^ (1/3) =3.


Note that BASIC systems are not designed to take roots of negative numbers, E.g. (-8) ^
(1/3) will not give value or A ^ B will result in an error if A is negative and B is not an
integer.
Problems
1. Evaluate the following
(a) –2 * 3 / 2* 3 (b) 75E-5 (c) 1.23E7 (d) (2 + (3 * 4 – 5 )) ^ 0.5

71
Federal University Lokoja -Introduction to Computer Science

2. For A=2, B=3, and X=2, evaluate each of the following (a) B/(A*X) (b) B/A/X
3. Some of the following are admissible BASIC expressions. Explain why.
(a) SUM * SUM (b) A * ( 2.1 – 7B) (c) SCORE * 7 (d) –9 ^ 0.5 (e)
X2 ^ 2

4. Write BASIC expressions for these arithmetic expressions.


2
(a) 0.06P (b) a/b + c/d (c) ( x + 4xy)(x + 2y)
5. Write equivalent BASIC expressions without using parentheses.
(a) P^ (Q * R) (b) ((X + 1) + y) (c) x * (x * (x * ( x + D) + C) + B ) + A

9.3.4 THE LET STATEMENT: Assigning values to Variables.


This is a way on how to instruct computer to evaluate expressions. A BASIC
programming line consists of a command to the computer preceded by unsigned integer
called the line number.
line number BASIC command

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.

A BASIC program is a collection of BASIC programming lines. The BASIC commands


contained in these lines are executed by the computer in the order determined by
increasing line numbers, unless one of the commands override this order.

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

72
Federal University Lokoja -Introduction to Computer Science

the variable a. Only numerical values may be assigned numerical variables and only
strings to string variable.

Example. Assignment of numerical values


The Program After execution of each statement
Value of P value of Q
100 LET P = 12 12 0
110 LET Q = P/2+1 12 7
120 LET P = Q/2+ 1 4.5 7
130 LET Q = P/2+1 4.5 3.25
140 END 4.5 3.25

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.

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 “ ”.
73
Federal University Lokoja -Introduction to Computer Science

9.4 THE BASIC STATEMENT


40 LET N = N + 1 does not mean that N is equal to N + 1. It means that the expression N
+ 1 is evaluated and this value is assigned to the variable N. For example, the effect of
the two programming lines
30 LET N = 5
40 LET N = N + 1
is that the value 6 is assigned to N.

9.5 THE PRINT STATEMENT


Every computer language must be designed so that the results can be made available in a
usable form. In BASIC, the PRINT statement meets this requirement. The simplest form
of this statement is ln PRINT a where ln denotes a line number and a denotes any string
or numerical expression. E.g., the statements
100 PRINT “ THIS IS A MESSAGE.”
110 PRINT 7 * 8 + 3
120 PRINT X
130 PRINT A$
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.

Example. Printing labels for output values:


100 REM ** AUTOMOBILE SALES TAX
74
Federal University Lokoja -Introduction to Computer Science

110 REM COMPUTATION PROGRAM **


120 REM
130 PRINT “TAXATION DEPARTMENT”
140 LET PRICE = 1000
150 PRINT “PRICE:”, PRICE
160 PRINT “ SALES TAX: ‘ , .05 * PRICE
170 END

When this program is executed, it will produce the output:


Taxation department
Price: 1000
Sales tax: 50

Both line 150 And line 160 print a numerical value preceded by label identifying what
the value represents. The two lines are delimited(separated)by comma. This comma
instructs the computer to space the two output values shown. The two labels in the
program are PRICE: and SALES TAX: identifying the numerical output values. String
variables can be used for this purpose also e.g., if the line
90 LET P$ = “PRICE” is added to the program and line 150 is changed to
150 PRINT P$, PRICE
the program will produce exactly the same output.

9.6 THE REM STATEMENT: remarks as part of a program


The BASIC statement that allows the insertion of comments is the REM(REMARK)
statement. The general form is ln REM comment where comment denotes any comment
or remark you may wish to include.
Example
100 REM **DETERMINE THE RATE OF RETURN
110 REM GIVEN THE CURRENT RICE
120 REM AND EARNINGS OF A SECURITY**
75
Federal University Lokoja -Introduction to Computer Science

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
Explanation 1. Comments in REM statements need not be enclosed in quotation marks.

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.

9.7 MULTIPLE COMMANDS IN A PROGRAMMING LINE

76
Federal University Lokoja -Introduction to Computer Science

BASIC allows the inclusion of many commands in a single programming line – the
commands are simply separated with colons. E.g. 10 LET A = 8: LET B = 12 : PRINT A
+ B is admissible. The general form of a multiple – command programming line is
Ln command { : command }

The commands are executed from left to right unless one of them overrides this order.
The following two lines are admissible but not equivalent:
10 REM PRINT THE RESULTS : PRINT X
10 PRINT X ; REM PRINT THE RESULT.
The first is simply a remark and will cause no action during program execution. The
second will print the value of X . Note that overusing of multiple – command lines tends
to clutter a program and obscure its meaning.

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

2. Which of these are incorrect LET statement? Explain.


a. 10 LET A+ B = S
b. 20 LET Z = 4E2.5
c. 30 LET “DEPT#7” = D$

3. Which of these are incorrect PRINT statement? Explain.


5 PRINT COST$ , COST
10 PRINT SEVEN$ , 7
15 PRINT “ FINAL RESULT” , AVERAGE

77
Federal University Lokoja -Introduction to Computer Science

4. Show the output if this program is run.


10 LET L = 10 : REM LENGTH
20 LET W = 5 : REM WIDTH
30 LET H = 4 : REM HEIGHT
40 LET V= L*W*H : REM VOLUME
50 PRINT V
60 LET L = W : H = W
70 PRINT V
80 END

9.8 THE COMMANDS LIST AND RUN


LIST is used to display some or all of the programming lines entered:
Command Effect
LIST Entire program is listed
LIST ln Only line ln is listed
LIST ln1, ln2 Lines ln through ln2 are listed.
A program can be executed(run) by typing RUN. This causes the program statements to
be executed according to the sequence of their line numbers.

9.9 THE INPUT COMMAND


The INPUT command, allows values for variables to be typed during program execution
and thus interact with the computer while your program is running.
E.g. 10 PRINT “ TYPE A NUMBER.”
20 INPUT T
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.
78
Federal University Lokoja -Introduction to Computer Science

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

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(?)
79
Federal University Lokoja -Introduction to Computer Science

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.

9.10 THE GOTO COMMAND: A first look at the loops.


The GOTO command allows overriding the normal sequential order in which
programming lines are executed. This means that you can direct the computer to execute
sections of a program repeatedly and thus to perform hundreds of calculations with only a
few programming lines. The general form of the GOTO command is :
GOTO ln
Example: Here is a program containing a loop:
100 LET I= 0
110 PRINT I
120 LET I = I + 1
130 GOTO 110
This program will cause the numbers 0, 1,2, 3,…, to be printed one number per line. Each
time 130 is executed; control is transferred to line 110. This is what is meant by a loop.
The loop consists of the three statements 110, 120, and 130.

Example: A program to do multiplication:


100 PRINT “ AFTER EACH ? ENTER TWO NUMBERS.”
110 INPUT A, B
120 LET P = A * B
130 PRINT PRODUCT IS “, P
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.

80
Federal University Lokoja -Introduction to Computer Science

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
180 PRINT H, A
190 LET H= H + 0.10
200 GOTO 160

Results: HOURLY ANNUAL


RATE SALARY
81
Federal University Lokoja -Introduction to Computer Science

------------ -------------
.
.
.
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
160 LET A =B
170 LET B = C
180 GO TO 140
2. CORRECT THE FOLLOWING PROGRAM
10 REM PROGRAM TO PRINT AN

82
Federal University Lokoja -Introduction to Computer Science

20 REM 8 PERCENT TAX TABLE


30 LET X = 100
40 LET T = 8 * X
50 PRINT “ PRICE “, “ TAX”
60 PRINT X, T
70 LET X = X + 1
80 GO TO 40
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
3 2
y = √1.09x - √3 8.51x + (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.

4. Write a program to perform the following task.


A list of numbers is to be typed at the keyboard. After each number is typed, the program
should cause two values to be printed: a count of how many numbers have been typed
and the average of all numbers entered to that time.

9.11 DECISION MAKING


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.

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
83
Federal University Lokoja -Introduction to Computer Science

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

3. In this program the loop is from line 110 to 150.


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.
84
Federal University Lokoja -Introduction to Computer Science

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}

9.11.2 Relation expressions


Any two BASIC expressions can be compared by using the relational symbols below.
BASIC Symbol Arithmetic Symbol Meaning
= = Equal to
< < Less than
> > greater than
<> ≠ Not equal to
<= ≤ Less than or equal to
>= ≥ Greater than or equal to

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.
c. If B is not negative, print NOT BOTH and stop.
85
Federal University Lokoja -Introduction to Computer Science

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

9.11.2 Compound Logical expressions


A logical expression is an expression that is either true or false. BASIC allows you to
write compound logical expression by using logical operators AND, OR, and NOT.

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.

86
Federal University Lokoja -Introduction to Computer Science

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.

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
87
Federal University Lokoja -Introduction to Computer Science

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

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
Federal University Lokoja -Introduction to Computer Science

9.12 Flowcharts and Flowcharting


A pictorial representation of the sequence of steps in an algorithm or a program is called
a programming flowchart or simply a flowchart. Flowcharts are useful for program
documentation . But it is often easier to prepare a pictorial description of a process than
to attempt a detailed description in words. The flowchart is therefore an excellent way to
do this
E.g. 7. Here is a flowchart displaying the process of adding the integers from 1 to 10.

89
Federal University Lokoja -Introduction to Computer Science

flowchart to another can be displayed and also to avoid long lines.

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 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
n
A = P(1+R) 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:

90
Federal University Lokoja -Introduction to Computer Science

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.

91
Federal University Lokoja -Introduction to Computer Science

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
140 IF P * (1 + R ) ^ N < 2 * P THEN 130
92
Federal University Lokoja -Introduction to Computer Science

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.

9.13 Summing with the IF statement


Since summing is a repetitive process, it can be accomplished efficiently with a loop. It is
therefore important that an exit be made from the loop only after the required sum has
bee obtained.

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.
2 2 2 2
S=1 +2 +3 +…N
Problem analysis: Here’s a simple algorithm for this task:
a. Input N.
2 2 2 2
b. Calculate the sum S = 1 + 2 + 3 + … N .

93
Federal University Lokoja -Introduction to Computer Science

c. Print S and stop.

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.

The Program: 10 INPUT N


20 LET S = 0
30 LET J = 1
40 IF J > N THEN 80
50 LET S = S + J ^ 2
60 LET J = J + 1
70 GOTO 40
80 PRINT “ SUM IS”, S
90 END
94
Federal University Lokoja -Introduction to Computer Science

Example. For any set of input values , find two averages: the average of those in the
range 60 to 80 and the average of all the others.
Analysis of the problem: Input: A list of numbers typed at the keyboard.( let 999
terminates this list.)
Output: A1 = average of numbers from 60 to 80
A2 = average of all other numbers.
Let X = current input value
S1 = sum of numbers from 60 to 80
S2 = sum of all other numbers (but not 999)
N1 = count of numbers whose sum is S1
N2 = count of numbers whose sum is S2.

95
Federal University Lokoja -Introduction to Computer Science

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

96
Federal University Lokoja -Introduction to Computer Science

9.14.1 FOR /NEXT loops


Example. Here is a program to print the integers from 1 to 5 with FOR/NEXT LOOPS.

100 FOR N = 1 TO 5

110 PRINT N; “ “ ;

120 NEXT N

130 END

RUN

The Results
12345

This program simply instruct the computer to execute line 110 five times, once for each
integer n from 1 to 5.
Example . Here is a program to calculate and print the price of one, two, …, and six
items selling at seven for N1.00.
100 REM U DENOTES THE
105 REM UNIT PRICE
110 LET U = 1.00/7
115 FOR K = 1 TO 6
120 LET P = U * K
125 PRINT K , P
130 NEXT K
135 END
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.
97
Federal University Lokoja -Introduction to Computer Science

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

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.

98
Federal University Lokoja -Introduction to Computer Science

FLOWCHARTing FOR/NEXT loops

Note that if the value is more than or less than 1, the “STEP” is used.

Example.
FOR M = 2 TO 9 STEP 3

99
Federal University Lokoja -Introduction to Computer Science

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

100
Federal University Lokoja -Introduction to Computer Science

(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
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

101
Federal University Lokoja -Introduction to Computer Science

9.14.2 Nested loops


It is permissible. and often desirable, to have one FOR/NEXT loop contained in another.
There is one rule that must be observed when loops occur in this way.
If the body of one FOR/NEXT loop contains either
FOR or the NEXT statement of another loop, it must contain both of them(see below)

102
Federal University Lokoja -Introduction to Computer Science

Example: The following program is to illustrate the nested FOR/NEXT loops.


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

103
Federal University Lokoja -Introduction to Computer Science

When the program is run the output is as follows:


1111111111
2222222222
3333333333

Exercises
Show the output of each program

i 10 FOR I = 1 TO 3
15 FOR J = 2 TO 3
20 PRINT J
25 NEXT J
30 NEXT
35 END

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

104
Federal University Lokoja -Introduction to Computer Science

70 END

ii. 10 REM PRINT SUMS


20 FOR A = 3 TO 1
30 FOR B = 4 TO 1
40 PRINT A; “PLUS”; B; “=”; A+B
50 NEXT B
60 NEXT A
70 END

iii. 10 REM PRINT PRODUCTS


20 FOR I = 1 TO 3
30 FOR J = 2 TO 4
40 PRINT I; “ TIMES”; J; “=”; I*J
50 NEXT I
60 NEXT J
70 END

9.15 THE READ AND DATA statements


In addition to LET and INPUT commands used to assign values to variables, there are
other commands such as READ command that is used to assign data to variables; DATA
command that allows the inclusion of data as part of the programs; and the RESTORE
command that allows the reading of the data more than once during a single program run.
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

2. This is a program to “read” and print a list of numbers:


10 READ X
20 PRINT X
30 GO TO 10
40 DATA 7, -123, 40
105
Federal University Lokoja -Introduction to Computer Science

50 END
The result: 7
-123
40
3. A program to read and print two strings:
10 READ A$, B$
20 PRINT B$; “ “; A$
30 DATA FLIES, TIME
40 END

The Result: TIME FLIES

In a flowchart, the READ statements such as READ Q and READ M, N, P would appear
in a flowchart as follows:

9.16 THE RESTORE statement

Examples : 1. Here is a program segment.


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.

106
Federal University Lokoja -Introduction to Computer Science

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

2. Show the output of each program


a. 10 READ A1, A2, A3 b. 10 READ A, B$, M$
20 PRINT A1, A2, A3 20 LET M$ = B$
30 RESTORE 30 PRINT M$
40 READ A3, A2, A1 40 READ A, B$, M$
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
107
Federal University Lokoja -Introduction to Computer Science

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

9.17 STRING AND NUMERICAL FUNCTIONS


BASIC is designed to assist in manipulating both numerical and string data. For this
reason, it includes several functions, called built-in functions, to carry out automatically
certain common calculations with numbers and operations on strings. There are also
functions called user-defined functions that are not part of the language but are defined
by individual users depending on the need.

9.17.1 String Functions


a) The string Function LEN: If S denotes the string, then LEN(S) reads length of S, which
is the number of characters in S. E.g LEN(“JOHN AND MARY”) GIVES THE VALUE
13. And if Z$=”JOHN AND MARY” then LEN(Z$) also give a value 13. note that
blanks are counted as characters. The S is called the argument of the function.

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$
108
Federal University Lokoja -Introduction to Computer Science

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:
1. MID$(S,M,N) is the string of N characters from S beginning with the Mth
character of S.
2. MID$(S,N) is the string consisting of all characters in S from the Nth character
onwards.
Example:
MID$(“JOHN AND MARY”,6,3) has the value AND
MID$(“JOHN AND MARY”,10) has the value MARY

Example: A program to count the number of A’s in a string A$ of any length.


10 LET C=0
20 INPUT A$
109
Federal University Lokoja -Introduction to Computer Science

30 FOR I=1 TO LEN(A$)


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
9.17.2 Built-in numerical function

Note 1 degree = π/180

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)

110
Federal University Lokoja -Introduction to Computer Science

60 NEXT I
70 PRINT C$
80 END

c) 10 LET B$=”A TO Z”
20 PRINT RIGHT$(B$,1) ; TO ; LEFT$(B$,1)
30 END

2. Evaluate the following BASIC expressions:


a) ABS(3*(2-5)) b) INT(26.1+0.5)
c) 100*INT(1235.7/100+0.5) d) ABS(INT(-3.2))
e) INT(ABS(-3.2))
3. Show the output for each program
a) 100 FOR N=0 TO 4
110 LET X=N*(N-1)
120 LET Y=ABS(X-8)
130 PRINT N , Y
140 NEXT N
150 END

b) 100 LET S=13.99


110 IF S>14 THEN 160
120 LET R=INT(100*S+0.5)/100
130 PRINT S , R
140 LET S=S+0.003
150 GOTO 110
160 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.

o,
Example, if X=45 then we must convert it to radians by multiplying by π/180
o
i.e 45 x π/180.

9.17.3 User-defined functions (The DEF statement)


111
Federal University Lokoja -Introduction to Computer Science

Basic allows the user to define and name his own numeric functions in addition to the
built-in functions. They can be referenced in any part of a program the same way as the
built-in functions are referenced.

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
3
function. Now if the expression FN Q(2) is used in the program its value will be 2+2
=10. In a similar manner if Y is assigned the value 2, then FN Q(Y) will also be 10.

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.

2. The ASCII function ASC


This function converts the first character in a string to its numeric code. E.g.
ASC(“JOHN”)=74, the numeric code for J. with a one-character string , ASC converts
the character to its numeric code. For example ASC(“A”)=65.

3. The STRING function


This function converts a numeric value to a string. Fir example:
The line 10 LET B$=STR$(342.5) assigns the string “342.5” to B$

4. The VALUE function VAL


It converts a string up to its first non-numeric character into its numerical value. For
example :
LET B=VAL(“30.52”) means B=30.52
LET B=VAL(“TWO”) means B=0

112
Federal University Lokoja -Introduction to Computer Science

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.

9.18.1 One – dimensional arrays

A one-dimensional array(or list) is an ordered collection of items in the sense that is a


first item, second item, etc. Consider the marks obtained in an examinations by a student
in six courses as follows; 60, 55, 98, 80, 75, and 93. Now the first grade is 60, second
grade is 55, and so forth. These grades can be marked with subscripts such as:
g = 60
1
g = 55
2
g = 98
3
g = 80
4
g = 75
5
g = 93
6
This subscripts can further be changed to: G(1)=60, G(2)=55, G(3)=98, G(4)=80,G(5)
=75, G(6)=93. In this case G is the name of the arrays, G(1), …, and G(6) are subscripted
variables, while 1, 2,…, and 6 are the subscripts of G. The array G can be visualized as
follows:

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)

113
Federal University Lokoja -Introduction to Computer Science

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

The analyses of the sample programs:


The index I in example 1 is the subscript in the loop. The first time through the loop, I
has the value 1 and the value 60 is assigned to G(1). The same process occur for the
remaining five passes through the loop.
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).

114
Federal University Lokoja -Introduction to Computer Science

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

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:

115
Federal University Lokoja -Introduction to Computer Science

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.

9.18.2 Higher- dimensional arrays


An item in an array is specified simply by giving its row number and column number.
Data to be processed by the computer are often presented in tabular form. For example,
consider a four by three array representing the votes obtained by four candidates from
three different polling boots.

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
116
Federal University Lokoja -Introduction to Computer Science

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”
117
Federal University Lokoja -Introduction to Computer Science

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

118
Federal University Lokoja -Introduction to Computer Science

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.

9.19 THE DIM statement


Whenever subscripts larger than 10 are needed, more space must be reserved in memory.
This can be achieved with the DIM statement. For example, if a subscripted variable say
P(11) is used in a program, memory space is automatically reserved for the eleven(11)
variables P(0), P91), …, P(10).

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

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 segment to read a list of numbers into array Q.


100 DIM Q(120)
110 LET J =0

119
Federal University Lokoja -Introduction to Computer Science

120 REM READ NEXT VALUE INTO ARRAY Q.


130 LET J = J + 1
140 READ Q(J)
150 IF Q(J) <> 999 THEN 130
160 REM N DENOTES ACTUAL LENGTH OF LIST
170 N = J – 1

Explanation: I is used to keep track of subscript. Each time a value is read for Q(j) it is
compared with the End Of Data(EOD) tag 999. If Q(J) is not 999, J is increased by 1 and
another value is read. If Q(J) = 999, then control passes to line 170, so that N specifies
the number of values, exclusive of the EOD tag read into the array.

Note that more than one DIM statement may appear in a program and each DIM
statement may be used to dimension more than one array . For example line
10 DIM B(20), P(40), Q(6) is admissible and will reserve memory space for the arrays
B, P, and Q.

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

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:

120
Federal University Lokoja -Introduction to Computer Science

Now the program:


100 REM INITIALIZE COUNTERS
101 DIM C(100)
102 FOR I = 1 TO 100
103 LET C(I) = 0
104 NEXT I
105 REM READ X AND ADD 1 TO C(X) UNTIL
106 REM THE EOD TAG 9999 IS ENCOUNTERED
107 READ X
108 IF X =999 THEN 210
109 LET C(X) = C(X) + 1
110 GOTO 170
111 REM PRINT THE FREQUENCY TABLE
112 PRINT “DATUM”, “FREQUENCY”
113 PRINT “------“, “------“
114 FOR I = 1 TO 100

121
Federal University Lokoja -Introduction to Computer Science

115 IF C(I) > 0 THEN PRINT I, C(I)


116 NEXT I
117 DATA 80, 80, 80, 80, 80,, 60, 60, 50
118 DATA 50, 50, 45,45, 50, 50, 50, 32
119 DATA 9999
999 END

The Result: DATUM FREQUENCY

32 1
45 2
50 6
60 2
80 5

9.20 SUBSCRIPTED STRING VARIABLES


Arrays can also be used to process lists of strings, such as names. A string
variable can be used as the name of an array whose entries are strings. The entries
in string arrays are referenced just as entries in numerical arrays are referenced.
For example, if I=6 then B4 denotes the sixth entry in B$.

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.

10 REM READ NAMES INTO ARRAY B$


20 FOR J=1 TO 10
30 READ B$(J)
40 NEXT J
50 REM SEARCH B$ FOR ANY NAME TYPED AT THE KEYBOARD
60 PRINT “TYPE THE NAMES EXACTLY AS FOLLOWS”
70 PRINT “FIRST NAME (SINGLE SPACE) LAST NAME”
80 PRINT “TYPE ‘DONE’ WHEN FINISHED”
90 PRINT
100 INPUT N$
110 IF N$=”DONE” THEN 250
120 LET FOUND$=”FALSE”
130 FOR J=1 TO 10
140 IF N$=B$(J) THEN FOUND$=”TRUE”; GOTO 160
122
Federal University Lokoja -Introduction to Computer Science

150 NEXT J
160 PRINT N$ ; “IS”;
170 IF FOUND$=”FALSE” THEN PRINT “NOT”;
180 PRINT “IN THE LIST”
190 GOTO 90
200 DATA “ABRAHAM LINCOLN” , “BILL CLINTON”
210 DATA “OLUSEGUN OBASANJO” , “ATIKU ABUBAKAR”
220 DATA “SOLOMON LAR” , “CHRISTOPHER DAMEN”
230 DATA “TONY BLAIR” , “ JOHN PAUL”
240 DATA “MONDAY MWANGVWAT” , “NENFORT GOMWALK”
250 END

If the program is executed and “GOMWALK” is typed, the result will be:
TYPE NAMES EXACTLY AS FOLLOWS
FIRST NAME (SINGLE SPACE) LAST NAME
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.

9.21.1 The GOSUB and RETURN Statements


These statements allow the writing and the use of subroutines in BASIC. The GOSUB
statement is used to transfer control to a subroutine while the RETURN statement is used
to transfer control back from the subroutine. A subroutine is any sequence of BASIC
programming lines to carry out a specific task. It must contain at least one return
statement.

Note that subroutine may be called from within another subroutine. The following is a
schematic representation of a program that does this. The action of the program is
indicated by the arrows labeled a, b, c ,and d.

123
Federal University Lokoja -Introduction to Computer Science

Examples
1. Write a program to print the average of any two input values and also the average of
their squares.
100 INPUT “TYPE TWO NUMBERS : ; A , B
110 GOSUB 300
120 LET A=A*A
130 LET B=B*B
140 PRINT “THE AQUARES ARE” ; A ; “ “ ; B
150 GOSUB 300
160 END
300 REM SUBROUTINE TO PRINT THE AVERAGE OF TWO NUMBERS
310 LET M=(A+B)/2
320 PRINT “THEIR AVERAGE IS “ ; M
330 RETURN

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.
100 REM SALARY PROGRAM

124
Federal University Lokoja -Introduction to Computer Science

110 REM N$ = EMPLOYEE’S NAME


120 REM A = ANNUAL SALARY OF EMPLOYEE
130 READ N$ , A
140 IF N$ = “END-OF-DATA” THEN 290
150 REM PRINT ANNUAL AND WEEKLY SALARIES
160 PRINT
170 GOSUB 300
180 GOTO 130
200 DATA “OLUSEGUN OBASANJO” , 18500
210 DATA “ATIKU ABUBAKAR” , 25700
220 DATA “END-OF-DATA”
290 END
300 REM PRINT SHORT SALARY REPORT
310 REM W=WEEKLY SALARY
320 GOSUB 500
330 LET W=A/52
340 LET W=INT(W*100+0.5)/100
350 PRINT “EMPLOYEE NAME : “ ; N$
360 PRINT “ANNUAL SALARY : “ ; A
370 PRINT “WEEKLY SALARY : “ ; W
380 GOSUB 500
390 RETURN
500 REM SUBROUTINE
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
--------------------------------------------------------------
125

You might also like