Professional Documents
Culture Documents
CS101 Reviewed Material (Completed) - FUL
CS101 Reviewed Material (Completed) - FUL
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
9
Federal University Lokoja -Introduction to Computer Science
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.
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.
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.
consists of one or more input device. The keyboard and mouse of a computer are the
most commonly used input devices. However there are other input devices such as
Scanner, Optical Mark Reading and Recognition (OMR), digitizers, Magnetic Ink
Character Recognition (MICR), Light Pen etc.
Key Board
The most common input device is the Keyboard. It is used to input letters, numbers, and
commands from the user.
Mouse
Mouse is a small device held in hand and pushed along a flat surface. It can move the
cursor in any direction. In a mouse a small ball is kept inside and the ball touches the
pad through a hole at the bottom of the mouse. When the mouse is moved, the ball rolls.
This movement of the ball is converted into electronic signals and sent to the computer.
Mouse is very popular in the modern computers that use Windows and other Graphical
User Interface (GUI) applications.
14
Federal University Lokoja -Introduction to Computer Science
The advantage of this method is that information is entered at its source and no further
transcription is required.
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.
16
Federal University Lokoja -Introduction to Computer Science
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.
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).
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 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.
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.
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.
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.
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
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”.
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
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
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.
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
28
Federal University Lokoja -Introduction to Computer Science
CHAPTER THREE
TYPES OF COMPUTERS
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.
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
Digital computer speed and calculating power are further enhanced by the amount of
data handled during each cycle. If a computer checks only one switch at a time, that
switch can represent only two commands or numbers; thus ON would symbolize one
operation or number, and OFF would symbolize another. By checking groups of
switches linked as a unit, however, the computer increases the number of operations it
can recognize at each cycle. For example, a computer that checks two switches at one
time can represent four numbers( 0 to 3) or can execute one of four instructions at each
cycle, one for each of the following switch patterns: OFF-OFF(0); OFF-ON(1); ON-
OFF(2); or ON-ON(3).
Counting on ones fingers is probably the simplest digital operation we all know. Digital
watches have special tiny digital computers within them.
3.2.2 Mainframes
Large general purpose computers with extensive processing, storage and input/output
capabilities. It is expensive with the capability of serving the needs of major business
enterprises, governments, scientific research establishments, or the like. They are usually
multi-user systems accommodating hundreds of users at a time with each having his
terminal(monitor and keyboard).
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:
31
Federal University Lokoja -Introduction to Computer Science
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.
Boolean (Logical) Data Types: These data types take only one or two possible values at
any one time. The two values are “True” and “False”. The name “Boolean” comes from
the name of a logician called George Boole who did much pioneering work in the
algebra of logic.
2. Pure Binary: in which the whole number is converted to binary e.g. 39 decimal is
represented as 10011.
33
Federal University Lokoja -Introduction to Computer Science
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.
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.
words, symbols; expressions and statements may be formed and combined. The
semantics is defined in terms of what happens when the program is executed.
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.
Constants
Pi = 3.141592654
Variables
i, quantity_required, product: integer
area, rate, unit_cost: real
rate_code: character
rate_code_valid: boolean
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
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
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
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:
45
Federal University Lokoja -Introduction to Computer Science
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.
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
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.
48
Federal University Lokoja -Introduction to Computer Science
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.
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.
50
Federal University Lokoja -Introduction to Computer Science
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
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
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
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
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:
begin
candidate.candidate_name := “Samson”
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
end
The facilities for creating records are only in some high level languages such as Pascal, Cobol,
Modula, etc.
This data could be stored in an array of records declared in the following way:
Variables
Candidate: array[1..6] of record
Number: integer
Name: string
Average : real
Endrecord
The following pseudocode could be used to output the data suppose the data had already been
assigned to records in the array. “ i” is an integer.
Begin
For I: 1 to 6
With candidate(i)
Output(number, name, av-mark)
Endwith
Endfor
end
7.1.6 Lists
Lists provide a flexible way of handling data items in order. Changes to the order can be
achieved with minimal data movement and little loss of storage space. E.g. The sentence “Alex
does not like Mango” is written as a list.
We regard each word in the sentence as a data- item or datum which is linked to the next datum
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
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
56
2 3
42
89
5 4
-1 42 -1 89
We notice that
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.
Is
Yes No
Transaction
Decision Symbol e.g. a Credit?
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.
Or
(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
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).
66
Federal University Lokoja -Introduction to Computer Science
5. Endeavor to run as Administrator each time you want to use the application.
67
Federal University Lokoja -Introduction to Computer Science
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.
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:
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
Type Examples
(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).
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
- 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.
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
E.g. , LET A = 2 + 5 has line 100 and contains the BASIC command LET A= 2 + 5. This
line will cause the computer to evaluate the sum 2 + 5 and then assign this value to the
variable A.
The general form of the first BASIC statement, the LET statement, is ln LET a = e or
more simply, ln a = e (LET is optional) where ln stands for line number, a denotes a
variable name, and e denotes a BASIC expression that may simply be a constant. This
statement directs the computer to evaluate the expression e and then assign this value to
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.
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
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.
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$.
77
Federal University Lokoja -Introduction to Computer Science
The use of the semicolon means that the value will be printed on the same line with the
statement being separated by the semicolon
and the second form displays the included string. In either case, you must respond by
typing a value for each variable in the input list and separate them by commas.
80
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
------------ -------------
.
.
.
5.5 11440
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
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
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
In BASIC, more than one command can follow the keyword THEN in an IF statement.
For example:
70 IF X > 0 THEN PRINT X : GOTO 30
50 IF A = 0 THEN PRINT “ DONE “ : END
65 IF X > 60 THEN S = S+ X : N = N + 1
These examples illustrate here different forms of the IF statement:
IF condition THEN ln
IF condition GOTO ln
IF condition THEN command { : command}
Expressions such as these are called relational expressions and they are used in IF
statements.
Example. Write a program to input two numbers A and B and print the message BOTH
if both are negative and the message NOT BOTH otherwise.
Here’s an algorithm for doing this:
a. Input values for A and B.
b. If A is not negative, print NOT BOTH and stop.
c. If B is not negative, print NOT BOTH and stop.
85
Federal University Lokoja -Introduction to Computer Science
The program:
10 INPUT A, B
20 IF A >= 0 THEN 60
30 IF B>= 0 THEN 60
40 PRINT “BOTH “
50 GOTO 70
60 PRINT “ NOT BOTH “
70 END
Example
a. The logical expression ( A < B) AND (B < C ) is true if both expressions A < B and B
< C are true; otherwise it is false.
b. (A<B) OR (A< C) is true if either or both of the expressions are true. This expression
is false only if the expression (A >= B) AND (A>= C) IS TRUE.
c. The logical expression NOT (A < B) is true if the A < B is not true, otherwise it is
false. The expression NOT(A<B) is equivalent to the relational expression A >= B.
Example.
a. The statement IF (A>0) AND (B> 0) THEN 200 will transfer control to line 200 if
both A and B are positive. Otherwise ,control passes to the line following the IF
statement.
b. The statement IF (G.= 80) AND ( G <= 89) THEN PRINT “B” will cause the letter B
to be printed only if G is between 80 and 89, inclusive.
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
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
89
Federal University Lokoja -Introduction to Computer Science
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
Exercises
Prepare a flowchart and then a program to accomplish each task specified in each of the
following. Try to avoid GOTO statement in your program.
1. Input one number. If it is b/w 3 and 21, print BETWEEN. Otherwise, print NOT
BETWEEN.
2.Input two numbers. If either one is positive, print EITHER. Otherwise, print NEITHER.
3. In put three distinct numbers. If the second is the largest, print LARGEST. If it is the
smallest, print SMALLEST. Otherwise, print neither.
4. For any input list, determine how many times a number is strictly larger than the one
just before it. For example, if the list is 17, 3, 19, 27, 23, 25, the answer will be three,
because 19>3, 27>19, and 25>23.
5. Several pairs(X,Y) of numbers are to be input. Any pair with X = Y serves as the end
of data (EOD) tag. Determine and print counts of how many pairs satisfy X<Y and how
,any pairs satisfy X>Y.
Example. Construct a flowchart and write a program to evaluate the following sum
where N is to be specified by the user. If the input value N is less than 1, the sum is zero.
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
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.
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
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
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
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
102
Federal University Lokoja -Introduction to Computer Science
103
Federal University Lokoja -Introduction to Computer Science
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
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
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
In a flowchart, the READ statements such as READ Q and READ M, N, P would appear
in a flowchart as follows:
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
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
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
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
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
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.
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.
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.
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
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.
This is a 4 X 3 array Q.
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
Results:
Example.
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.
Example: Write a program segment that reads values for N variables A(1), A(2), …,
A(N).
The Program:
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.
119
Federal University Lokoja -Introduction to Computer Science
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
121
Federal University Lokoja -Introduction to Computer Science
32 1
45 2
50 6
60 2
80 5
Example: Write a program that reads ten names into an array B$ and then search
the array for any names typed at the keyboard. When the word FINI is typed the
program terminates.
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.
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
Results:
--------------------------------------------------------------
EMPLOYEE NAME : OLUSEGUN OBASANJO
ANNUAL SALARY : 18500
WEEKLY SALARY : 355.77
--------------------------------------------------------------
EMPLOYEE NAME : ATIKU ABUBAKAR
ANNUAL SALARY : 25700
WEEKLY SALARY : 494.23
--------------------------------------------------------------
125