100% found this document useful (2 votes)
34 views

Pascal Programming A Beginners Guide to Computers and Programming 2nd Edition Chris Hawksley download

The document is a promotional listing for various programming books, including 'Pascal Programming: A Beginner's Guide to Computers and Programming' by Chris Hawksley. It provides links to download these books in different formats and mentions the content structure of the Pascal programming book, which covers foundational programming concepts and practical applications. The second edition of Hawksley's book has been revised to conform to the ISO standard Pascal and includes a set of answers to selected exercises.

Uploaded by

suilahvrieze
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
34 views

Pascal Programming A Beginners Guide to Computers and Programming 2nd Edition Chris Hawksley download

The document is a promotional listing for various programming books, including 'Pascal Programming: A Beginner's Guide to Computers and Programming' by Chris Hawksley. It provides links to download these books in different formats and mentions the content structure of the Pascal programming book, which covers foundational programming concepts and practical applications. The second edition of Hawksley's book has been revised to conform to the ISO standard Pascal and includes a set of answers to selected exercises.

Uploaded by

suilahvrieze
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Pascal Programming A Beginners Guide to

Computers and Programming 2nd Edition Chris


Hawksley pdf download

https://ebookgate.com/product/pascal-programming-a-beginners-
guide-to-computers-and-programming-2nd-edition-chris-hawksley/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Programming WPF 2nd Edition Chris Sells

https://ebookgate.com/product/programming-wpf-2nd-edition-chris-sells/

ebookgate.com

PIC Programming for Beginners Arrl

https://ebookgate.com/product/pic-programming-for-beginners-arrl/

ebookgate.com

CNC Programming Handbook A Comprehensive Guide to


Practical CNC Programming 3rd Edition Edition Smid

https://ebookgate.com/product/cnc-programming-handbook-a-
comprehensive-guide-to-practical-cnc-programming-3rd-edition-edition-
smid/
ebookgate.com

Computers and Programming Ferguson Career Launcher 1st


Edition Lisa Mccoy

https://ebookgate.com/product/computers-and-programming-ferguson-
career-launcher-1st-edition-lisa-mccoy/

ebookgate.com
Programming F A comprehensive guide for writing simple
code to solve complex problems 1st Edition Chris Smith

https://ebookgate.com/product/programming-f-a-comprehensive-guide-for-
writing-simple-code-to-solve-complex-problems-1st-edition-chris-smith/

ebookgate.com

Parallel Programming Techniques and Applications Using


Networked Workstations and Parallel Computers 2nd Edition
Barry Wilkinson
https://ebookgate.com/product/parallel-programming-techniques-and-
applications-using-networked-workstations-and-parallel-computers-2nd-
edition-barry-wilkinson/
ebookgate.com

Absolute Beginner s Guide to Programming 2nd Edition Greg


Perry

https://ebookgate.com/product/absolute-beginner-s-guide-to-
programming-2nd-edition-greg-perry/

ebookgate.com

Programming Windows Presentation Foundation 1st Edition


Chris Sells

https://ebookgate.com/product/programming-windows-presentation-
foundation-1st-edition-chris-sells/

ebookgate.com

How to Make a Noise A Comprehensive Guide to Synthesizer


Programming Simon Cann

https://ebookgate.com/product/how-to-make-a-noise-a-comprehensive-
guide-to-synthesizer-programming-simon-cann/

ebookgate.com
PASCAL
programming:
a beginnens guide
to computers and
programming
SECOND EDITION CHRIS HAWKSLEY
WITHDRAWN
Ho iongtr ttii property Of tilt
PotlwPyblteUhwiy.

to computers and programming

ISO Standard Pascal Edition


VIWAHOHTIW
tv •m'lm'^i ^^^^
(^Pascal programming
)
A BEGINNER'S GUIDE TO COMPUTERS AND
PROGRAMMING

CHRIS HAWKSLEY
Department of Computer Science, University of Keele

SECOND EDITION

The right of the


Cambridge
University of
and sell
to print
all manner of hooks
was granted by
Henry Vlll in 1534.
The University has printed
and published continuously
since 1584.

CAMBRIDGE UNIVERSITY PRESS


Cambridge
London New York New Rochelle
Melbourne Sydney
Published by the Press Syndicate of the University of Cambridge
The Pitt Building, Trumpington Street, Cambridge CB2 IRP
32 East 57th Street, New York, NY 10022, USA
10 Stamford Road, Oakleigh, Melbourne 3166, Australia

© Cambridge University Press 1983, 1986

First published 1983


Reprinted 1985
Second edition 1986

Printed in Great Britain by the University Press, Cambridge

British Library cataloguing in publication data

Hawksley, Chris
Pascal programming: a beginner's guide to computers and
programming. - 2nd ed.

1 . PASCAL (Computer program language)


I. Title
005.13'3 QA76.73.P2

Library of Congress cataloguing-in-publication data

Hawksley, Chris, 1949-


Pascal programming.

Includes index.
1 . PASCAL (Computer program language)
2. Electronic digital computers - Programming.
\rm^ ^ 86-13627

ISBN 0 521 33066 1 hard covers


ISBN 0 521 33714 3 paperback

(First edition ISBN 0 521 25302 0 hard covers


0 521 27292 0 paperback)

UP
To my parents
1

I
Digitized by tine Internet Archive
in 2015

https://archive.org/details/pascalprogramminOOchri
Contents

Preface xi

1 Introduction 1

Part 1 Foundations of programming 3

2 Data and information 5

2. 1 The computer as a tool 5

2.2 Symbols and symbolism 6


2.3 Information representation 7
2.4 The number crunching myth 9
2.5 Data types 10
3 Algorithms 16
3.1 Problem solving 16
3.2 Algorithms and language 19
3.3 Another myth 22
4 Computers and programs 25
4. 1 A computer model 25
4.2 Programming languages 29
4.3 Operating systems 31
5 First steps in Pascal programming 33
5. 1 Pascal program construction 33
5.2 Identifiers and declarations 36
5.3 Statements 38
5.4 Expressions 39
5.5 Standard functions 43
5.6 Boolean expressions 44
5.7 Reading and writing 46
5.8 Semicolons and compound statements 47
5.9 A short program 48
6 Control structures 51
6.1 Conditional statements 51

vii
viii Contents

6.2 Repetition 56
6.3 Choosing loop structures 59
6.4 The case statement 62
7 Procedures and functions 65
7.1 Declaring and caUing procedures 65
7.2 Local variables 67
7.3 Global variables and parameters 69
7.4 Functions 74
8 Input and output 78
8.1 Modes of programming 79
8.2 Read and readln 80
8.3 Write and writeln 83

Part 2 Problem Solving by Computer 87


9 Program design 89
9.1 'Good' programs 90
9.2 Structured programs 90
9.3 Comments 93
9.4 Data structure 93
9.5 Top-down program design 94
10 Problems involving small quantities of data 99
10.1 A simple program 99
10.2 Conditionals in use 101
10.3 Loopring the loop 105
10.4 Alternative strategies 106
10.5 Using procedures 109
10.6 Sets and in 111
11 Using more data 116
11.1 Arrays 116
11.2 Using arrays 117
11.3 Sorting 123
1 1 .4 Tables of data 126
1 1.5 array and type 133
12 Text processing and files 137
12.1 Files 137
12.2 String manipulation 141
12.3 Word processing 143
12.4 Grammatical analysis 152
13 Analysing data and presenting results 160
13.1 Packages 161
13.2 Files, records and fields 162
13.3 Pascal records 164
Contents ix

1 3.4 Entr> and venfication of data 166


13.5 Presenting results 168
14 Further Pascal 173
14.1 Additional data t>pes 173
14.2 Records and pointers 174
14.3 Recursion 174
14.4 Non-text files 174
14.5 File pointers 175
Appendices 176
1 Pascal synta.x diagrams 176
2 Reserved words 184
3 Standard functions 185
Answers to selected e.xercises from Part 1 186

Index 191
^1

i
o Preface

I was surprised to find that although there are shelves of programming texts
on the market, many of which use the excellent language Pascal, none of
these books was proving to be a great success with the hundreds of students
taking subsidiary level computer programming courses I have taught over
the last eight years. I began to ponder why this should be. Was it the
standard of the text books themselves? Certainly not; several are of
first-class quality with authors of recognised programming and teaching
ability. Perhaps the students were not up to scratch? An easy get-out, this,

but not good enough since their eventual results were on the whole normal
and satisfactory. Could it be that my teaching style or ability was not good
enough to support and encourage reading of a back-up text? Well,
possibly, though my students tend to be a vocal lot yet they hurl no more
than a fair share of verbal abuse in my direction. On the other hand, I have
never found it easy to follow any of the text books closely in these courses
and this gives a clue to part of the problem.
I believe that the level of background knowledge assumed in most texts
is unrealistically high for a lot of students. There are two related problems.
Firstly, the bias tends to be towards the numerate scientist both in the

general approach and, too often, in the choice of examples. Also, the
starting point of many texts is too advanced for many newcomers to
computing, relying on additional course or book material to introduce
some of the fundamentals of computing.
I have tried to write this book for students who are learning computer
programming, probably for the first time, and probably as a subsidiary
subject. It is possible that their main subject or subjects may lie in

disciplines apparently far removed from computing though this is not


necessarily the case. I have not assumed previous exposure to computers

xi
xii Preface

nor any parallel courses in computer science. The examples require only
'common-sense' mathematical ability and have been chosen from a wide
range of disciplines. In addition, I hope the book will be of value to the
individual reader learning to program for the first time and as a 'starter
new computer science students, who should progress fairly rapidly
kit' for

onto the more advanced texts covering algorithms, data and programs.
I have not tried to cover absolutely all of Pascal's features in detail in

order to concentrate on using the more common ones and to keep the book
short. New programming facilities are introduced usually by typical
examples, with passing reference to the theoretical alternatives, though I

have given diagrams covering all of Pascal in an appendix. Most of the


language is covered. Left out are bits of Pascal that will appeal to the
programmer growing in experience who will eventually wish to peruse
more advanced texts on programming and problem solving in any case.
These are dealt with in chapter 14.

The text starts with a fairly gentle introduction to computers and


programming leading into the basic foundations of programming in the
Pascal language. The emphasis in part 2 is on practical applications of
computer programming and I have tried to select examples from disciplines
that may be familiar to the non-specialist student of computing some text :

processing, social science applications, and analysis of collected data, for


example. i

It should be a source of encouragement to many readers to know that


in my experience there is little, if any, correlation between the ability to
become a competent programmer and the academic background of a
student. A number of first class mathematics students have passed through
the Computer Science Subsidiary Course at Keele. A proportional number
of students from the departments of Physics, Chemistry, Biology, Geology,
Psychology, Economics, Education, Geography, Sociology, Social Policy,
Music, English, French, German, Russian, Latin, History, American
Studies, Philosophy, (my apologies for any omissions)
Law, and Politics

have succeeded equally well. Yet, every year I hear 'Do you think I can
make it? I am not very good at maths., you know.' Quite honestly, a
positive attitude is a far more important prerequisite than an 'A' level in
mathematics. Enjoy your programming.
I am indebted to many people for help and ideas in writing this book,
amongst whom I must include the generations of students who have helped
me to appreciate some of the common difficulties experienced by beginners.
In particular, I would like to thank Professor Colin Reeves for his
encouragement to write the book in the first place, Dr Neil White whose
Preface xiii

meticulous knowledge of Pascal was invaluable and Lorraine Jarvis for


grappling with some of my handwriting and drawings. Any mistakes or
shortcomings that remain are entirely my own responsibility.

C. Hawksley
June 1982

Preface to the second edition

In this second edition the text has been revised to conform to the definition
of standard Pascal specified in the international standard ISO 7185. The
main changes relate to details in the diagrams used to show the structure
of Pascal but a few alterations to descriptions in the text have also been
made. ISO standard Pascal has gained wide acceptance among the
expanding number of Pascal systems now on the market. It is encouraging
to note that Pascal itself continues to increase in popularity both in
education and in real applications and that it is now available on a wide
range of low-cost microcomputers.
By popular request, a set of answers to some of the exercises in Part 1

has been inserted at the end of the book.

Chris Hawksley
Keele, February 1986
© Introduction

The last thing one knows in constructing a work is what to put first.

Pensees, Blaise Pascal (1623-62)

There are certain similarities between learning to program a computer and


learning to play a musical instrument. In case the music profession or the
reader are alarmed by this let it be added quickly that the similarities lie

in aspects of the learning process and not in the activities themselves. In

common with many other learning processes, such as learning to cook or


to drive a car, both require an assimilation of three basic components:
background knowledge, technical skill and creative art.
In learning to play a piano, for example, it is not essential to know
precisely how the piano is constructed; how the hammer mechanism is
made or how to tune the instrument, but a basic level of appreciation of
the mechanics is most necessary. The fact that a note is struck and then
decays, that the loud and soft pedals affect the note quahty in particular
ways are examples of this simple, but important, background knowledge.
In computer programming it is not essential to know how a computer
works from an electronic viewpoint, for instance, nor even in the case of
larger remote-access computers is it necessary to know where the computer
is located physically. On the other hand, it is important to appreciate some
of the general principles on which a digital computer operates in order to
gain a Teer for the tasks to be performed. For this reason, the first few
chapters of thisbook aim to introduce the kind of background information
that is relevant to the programming of a computer. Terms such as data,
data processing and algorithm are explained and a model is used to
describe the fundamental workings of the computer itself.

In the case of the student musician, technical ability must be acquired

1
2 Introduction

through the learning of scales, finger positioning and chords, for example.
The repertoire of basic skills is gained partly from instruction by tutor or
text and, perhaps largely, by a 'practice makes perfect' process. The parallel
skills in programming entail the learning of a programming language and
the way in which its constructions may be put to practical use. Again, the
educational process should include a substantial element of practical
involvement: the writing of small programs to reinforce the theory. With
this in mind, the later chapters of part 1 introduce fundamental constructions
of the Pascal programming language together with short examples to
illustrate their use. It is important for the reader to supplement this by
attempting short exercises of the kind found at the ends of these chapters.
The introductory material is covered fairly quickly in part 1and more
advanced details are omitted at this stage. The objective is to move on to
the creative side of programming as soon as possible, since the writing of
complete programs to solve actual problems is our ultimate aim. Armed
with the basic techniques, part 2 begins to explore the art of problem
solving: taking a loosely defined problem, creating a precise program
design and writing a complete Pascal program. In musical terms we begin
to play pieces of music using our own style and interpretation.
The examples in part 2 are chosen to demonstrate reasons for selecting
particular kinds of programming constructions and ways of putting them
together. Thus, much of the material introduced in part 1 is revisited in

the case studies of part 2 with an emphasis on practical applications. If you

experience difficulty in understanding a new Pascal feature introduced in


the earher chapters, bear in mind that there is likely to be a further reference
or references in the index to later case studies which may be of assistance.
Also in new Pascal facilities are introduced which
later chapters, several

can be added to the repertoire of programming skills once the fundamentals


have been firmly established.
There is no substitute for practical programming experience as a way
of boosting the confidence and of improving one's abihty to cope with new
problems. Yet problem solving is a fascinating and rewarding art which
will more than repay the initial effort to master the use of the building
blocks of programming. Note, finally, that one must always beware of
taking analogies too far. The fact that some musical instruments and some
computers possess keyboards is perhaps the only real similarity between
the two after all!
Parti

Foundations of programming
Data and information

2.1 The computer as a tool

It is easy to forget that the computer is a tool constructed by man.


Perhaps due to ignorance or fear of a rapidly expanding technology many
people have overlooked this fact. It is currently fashionable to attribute
man-like features to the computer; even to call it a superhuman brain
capable of enormous mental feats performed with tireless efficiency. Indeed,
this machine has become so humanised that we read regularly of computers

making mistakes. Bills issued for £0.00 form a source of amusing material
for the newspaper columnist. Complaints ranging from the delivery of
wrong goods to the erroneous disconnection of electricity meters are put
down to the apparently unavoidable occurrence of a computer error. The
consequences are not always amusing. An inanimate collection of circuits
has taken over from the anonymous clerk as the perfect scapegoat for
administrative irresponsibility.
Yet, in the same way that we would not entertain a claim that a
carpenter's chisel made a mistake or that a writer's pen spelled a word
wrongly we should recognise this twentieth century example for what it

is: a bad workman blaming his tools. For a computer is as much a tool
as a chisel or a pen. Furthermore, it is a deterministic device. It can and
will do precisely what it is told todo and only that, in common with chisels
and pens. Like all artifacts the computer is prone to malfunction, but this
is not at all the same as making a mistake. How often do we encounter
pens which misspell as a result of the nib breaking?
Thinking of the computer as a tool in this sense provides a convenient
starting point for this text. We are faced with a device which is not human,
not intelhgent and which we must learn to use. The appropriate term is

to program a computer. More than with many longer established trades


the technical terms associated with this tool are numerous and apt to

5
6 Data and information

bewilder the new computer user. Where it is necessary to use these terms
we shall define them at the time they are first encountered.
Having introduced the computer in this way we should not be discouraged
by the fact that it is a mere tool. It is an immensely powerful and general
one as we shall see. More immediately, let us examine the raw materials
on which our tool is to work.

2.2 Symbols and symbolism


In computing we are concerned not with the fashioning of some
physical medium as in the case of a chisel but with the manipulation of
intangible symbols. Symbols have been in use considerably longer than
computers. From hieroglyphics to Morse code, the Greek alphabet to
shorthand the use of symbols was one of man's first steps on the road to
civilisation. A few examples of symbols are shown in figure 2.1.

Interestingly, we have become so accustomed to using symbols that we


take them for granted. More precisely, we do not distinguish clearly
between a symbol and our interpretation of that symbol. Symbols are
marks on paper, shapes carved on stone, holes in punched
literally signs;

cards or a character typed on a keyboard are all examples of signs. Thus,


one may describe the symbol 'O' as a circle drawn on paper, no more and
no less.
However, to make, use of a symbol we must impose some kind of
interpretation on it. Hence we may interpret the symbol 'O' as the 15th
letter of the English alphabet. In this sense the symbol 'O' is an example
of an item of data and the interpretation placed on the symbol is an example
of information conveyed by the data. This is more than a trivial distinction.

Figure 2.1. Symbols.

CLAVDIVSIV OL^y 1234567890

Roman characters Greek letters Arabic numerals

Hieroglyphics Chinese

001 101 1 10

Binary
Information representation 7

In particular, note that whereas the data are invariable - they are so many
marks on paper, for example - the information conveyed is subject to
personal interpretation and may differ widely. Thus, taken out of context
the symbol 'O' may be interpreted as an Arabic numeral, the chemical
symbol for oxygen, even a nought in noughts and crosses. The very
personal nature of information is even more clearly illustrated in figure 2.2.

The item of data 'SALLY' conveys information that is most unlikely to


be exactly the same to two individuals. We may see it as a girl's name but
we are just as likely to imagine someone or something we know called
'SALLY' and our reaction is coloured by this knowledge.
In the same way, if we ask a London commuter what he understands
by the symbols 'PADDINGTON' we are likely to get a very different
interpretation to that given by a 5-year-old child!

2.3 Information representation


Why should this distinction between data and information be of
interest to us? The answer becomes apparent if we attempt to define a
computer. Rather than make use of a technical definition in terms of
electronics or mathematics, which would be of Httle use to us here, we shall

use an operational definition:

A computer is a machine that is capable of processing data.

It is data which are processed, not information. Information processing


is strictly for human beings. The computer can impose no interpretation
of its own on data but is restricted to accepting one set of symbols at one
end, to processing them in a precisely defined manner and to generating
a second set of symbols at the other end. Whether or not these symbols
convey information to the user is a separate issue into which the machine
has no insight.
Inextricably tied up in this relationship between data and information
is the matter of convention. In the case of 'SALLY' we each place our own
interpretation on the data based on our real-world experience of people

Figure 2.2. SALLY'.


8 Data and information

and objects. On the other hand, no reader of this text can dispute that
'SALLY' is an item of data made up of five letters of the EngHsh alphabet.
That we are all agreed on this is an essential part of the process of
communication which is (hopefully) going on between us. This too is

information, but it is information that is made accessible to all of us by


conventions that govern, in this case, the relationship between symbols and
letters of the English alphabet. Similarly, though less rigidly, we use
conventions to convey the meaning of words in a language. By popular
consent the sky is 'blue' and we refrain from redefining this colour to mean
'yellow' or 'palpitating'.
In natural (human) language the conventions are rarely hard-and-fast.
Indeed it is a common ploy in literature to bend or to break the conventions
as shown in the quotation below.

Run till you're dithery,


Hithery
Thithery
Pfitts! pfitts!

How she spits!


Spitch! Spatch!
Can't she scratch!
Scotching the bark
Of the sycamore-tree,

(from Cat! by Eleanor Farjeon)

Remarkably, we can follow such verse. Perhaps we may differ slightly


in our interpretations - I am not too certain what 'scritch' means - but the
overall impressions are surely communicated. Such immense facility
is the
with which we process language daily. But this is moving off the present
point and we shall return to take a more detailed look at language in
chapter 3. At the moment we should appreciate that conventions play an
equally important role in computing and that we need to be made explicitly
aware of these conventions.
For example, a convention which we have all taken for granted since
our early schooldays informs us that the symbols

3850

when written side by side in this manner are data that may be interpreted
as a number: more precisely as the integer three thousand eight hundred
and fifty. Since the computer, as just defined, is a blind processor of
The number crunching myth 9

symbols it must be 'made aware', in some sense, of the conventions


governing thousands, hundreds, tens and units. How this is achieved and
whether the computer user need involve himself in implementing such
conventions depends on the computer system in question but in this
particular case (integer numbers) a convention will almost certainly exist.
We shall examine some of the more common conventions shortly.
The above example illustrates a potential source of frustration for new
programmers. We often embellish numbers with commas or spaces to
improve readability. Thus the two variants

3,850 and 3 850

are not uncommon. More often than not in computing, however, spaces
and commas are used to separate numbers. Hence, 3,850 is likely to be
interpreted as the two distinct 3 and 850 separated by a comma.
numbers
An awareness of the fact that the computer lacks our perception in these
matters is a better philosophy than that seemingly believed by the student
who complained that he had put the data in ten times and the computer
had still not recognised his numbers!

2.4 The number crunching myth


It may come as a shock to pocket calculator fans that the
representation of information in a computer is by no means limited to
numbers. Indeed, it is a common misconception that the computer is a
'number crunching' device. That this arose is due mostly to historical
accident, since early computers were seen as a panacea for mathematicians
and scientists who needed a way of performing calculations impossible
previously by hand.
For a long time the facilities available to the programmer reflected this
preoccupation with numbers. Even today there are programming languages
still in common usage whose philosophy of representing alphabetic
characters, for example, goes something like

let 'A' be represented by 1

let 'B' be represented by 2


let 'C be represented by 3
etc.

which makes the analysis of text look remarkably like cryptography.


Fortunately, this attitude is changing and non-numerical data handling
facilities have improved dramatically in some more recent languages. This
is good news indeed for the non-scientific programmer. The task of
10 Data and information

formulating the solution to a problem is sufficiently demanding in itself,

without having to contort that solution into a numeric code.


Looked at another way, the most primitive level of operation of the
computer will most probably include instructions such as 'add' and
'subtract'. But these numerical instructions will be greatly outnumbered
by instructions for reading and printing characters, for comparing
characters, for moving data from place to place and so on. The computer
is primarily a symbol processing machine, not a super calculator.

2.5 Data types


In an abstract sense we can imagine any number of data 'objects'
representing objects in the real world. These data objects may be classified
into specific categories or types where the data are related to their type by
the relevant data convention. For example, we saw earlier how the data
object '3850' is related to an actual number by means of a convention. We
provide a formal framework for these ideas by considering '3850' to be an
object of data type 'integer'. Thus, a data type identifies a set of values that
are interrelated in some way, in this case by being a member of the set of
positive and negative whole numbers (or zero). In a wider sense we could
imagine data types such as those in figure 2.3. For each type, the values
are interrelated in a specific way as suggested by the name of the type.

This notion of data values associated with a specific data type is

fundamental to the writing of computer programs. In particular, it is the


data type to which an object belongs that determines the outcome of
operations performed on the data. For example, in adding two integer
objects such as

3850 + 2165

we anticipate a result that is also an integer, that we expect


is, the '
+ '

operator to deliver the integer that is the numerical sum of the two. In
another context, however, such as

'PIECE'
+ 'MEAL'

Figure 2.3. Data types.

('red', 'yellow', 'blue')

Data type: 'primary'

('mon', 'tues', 'wed', 'thurs', 'fri', 'sat', 'sun')

Data type: 'day of week'

(..., 1968, 1972, 1976, 1980, ...)


Data type: 'leapyear'
Data types 11

where, instead of integers the two values are of a data type called, say,
'string', we may wish the ' -f ' operator to mean 'concatenate the two strings
of characters within primes', delivering the result 'PIECEMEAL', rather
than to imply a meaningless numerical addition. In each case it is the data
types of the operands (the objects on either side of the operator) which
determine the meaning of the operator in that context.
In practice, there are a small number of data types which are used so
widely that they are predefined within a programming language (the
medium in which the user writes his program). This means that the user
may define and manipulate objects of these basic types assuming the
relevant conventions to exist. A brief description of the most commonly
available data types and their constituent values is given below. Note that
this is a collection of useful, common types. An actual programming
language may provide more, or less, predefined data types. Also, the names
given to the data types below are subject to considerable notational
variation. Commonly, for example, 'int' is used for integer and 'char' for
'character', but such vagaries need not concern us here.

Characters
The data type 'character' (often abbreviated to 'char') may be
defined explicitly as a set of characters such as that in figure 2.4. In practice
the set of characters making up this data type will differ from computer
to computer since it is dictated by the characters that may be read into
or printed out of the computer. This in turn is determined by the computer
manufacturers, who have not always found it possible, or in their interests,
to standardise it. Usually the differences are minor, but they can be
annoying if one is transferring a program from one computer to another.
Looking at the character set in figure 2.4 we must be careful to
distinguish between the characters 0-9 and any numerical notions they may
conjure up. '3' may be considered every bit as much a character as 'A' or
';' or '
+ '. It is useful to imagine a character as corresponding to a key
depression on a typewriter keyboard. '3' and ';' are keys that result in a

Figure 2.4. A character set.

space !''#$%&'()* ,_./ +


0
@
123456789
ABCDEFGHI :;< >?
JKLMNO_ =

P QRSTUVWXYZ
abcdefghijklmno [ \ ]

£
p qrstuvwxyz{ \
12 Data and information

character being printed in just the same way as 'A'. By the same analogy,
'space' is seen to be a character corresponding to a depression of the space
bar on the typewriter. The fact that the character printed is 'invisible'

should not deter us from considering 'space' as a character in the same way
as any other. Finally, note that this analogy can be pushed too far. Many
typewriters do not have keys for '0' (zero) and '1' (one). The typist is

expected to use a capital ('upper case' in computing terminology) 'O' (oh)


and a small ('lower case') T (el) respectively. These are four distinct

characters in computing, and keyboards on computer terminals possess


separate keys for these characters.
Interestingly, it would be possible to manage with no other data type
than 'character' since we normally communicate with the computer by
typing in characters from a keyboard and receiving results as printed
characters. Groups of characters such as '123' may be given special
significance and arithmetic performed by character manipulation. Indeed,
this notion is reflected in the fundamental design of computers, where data
entering and leaving a computer are normally viewed as streams of
characters. However, to permit only characters would be particularly
unwieldy and it is usual to provide a number of the other basic types
described below.

'
Integers
The data type 'integer' embraces all positive and negative integral
numbers including zero. In practice, since computers cannot cope with the
infinity of numbers implied in this definition a restriction on the maximum

size of an integer will be imposed. Typically, this may be of the order of


plus or minus several million, but on mini- or micro-computers a much
smaller range may be imposed.
Examples of integers with and without signs are

45
-23
+ 36
Further characteristics of integers will be discussed in conjunction with the
next data type.

Reals
All numbers on the continuum from minus infinity to plus infinity,
known to mathematicians as real numbers and including all fractions, are
Data types 13

elements of a data type commonly referred to as real (figure 2.5). Again,


in practice, a restriction will be placed on the maximum size of a real,

although this may be very large, perhaps greater than 10 to the power
76 (an unimaginably large number unlikely to be put into perspective by
calculating that there have been less than 10 to the power 17 seconds since
the world was created).
Note, however, that despite this restriction there is still an infinite

number of reals within these limits. This is because in theory there is an


infinitely small difference between two adjacent real numbers. Inherent in

the representation of a real number in a computer is the concept of


precision, for it is impossible to represent many real numbers exactly. The
rational number |, for example, which may be written as 0.66 recurring,
has no exact representation (we cannot go on writing 6s indefinitely!).
Indeed, we are obliged to use an approximation such as

0.66666666667

which may then be considered as a real expressed to a precision of 1

decimal places. Thus, in general, all real arithmetic is approximate and this

may or may not be apparent to the user. The number of places of precision
seems more than generous for most applications but small errors in long
chains of arithmetic calculations can accumulate and become significant.
However, this is not a book on numerical analysis and the user who plans
to do extensive real arithmetic will need to make a much wider study of
error considerations elsewhere. The above example serves to illustrate a
point which is more relevant to us here. It is not always immediately
recognised that there is a fundamental difference between the data types
'rear and 'integer'. The latter is definitely not a subset of the former and,
significantly, the usage of integers and reals is very different. Integers are
used for enumeration for counting, for identifying events and elements of
:

sets of objects where the idea of a real number is nonsense.


We may take a simple example to demonstrate this difference. The length
of a football pitch can vary anywhere between 100 and 120 yards. It is a
real quantity, for example 1 10.75 yards. Even if the length is measured out

Figure 2.5. Real numbers.


Smallest difference
between two 'real's'
\

I I-

Largest -ve Largest +ve


'
real 'real'
14 Data and information

to an exact number of yards it is still a real quantity subject to a certain


precision in measurement and we may care to distinguish it from an integer
by including a decimal point, as in 1 10.0 yards. The number on the back
of a player on the other hand is an integer quantity used to identify the
player. We should think it very odd to see a player wearing the number
3.142 on his back.
In computers, real numbers are represented in a different way to integers
and this affects the way a programmer must think of numbers. For
example, it is often necessary to determine whether two values are equal.
Whereas it can be guaranteed that the comparison of two values will

proceed as expected if both are integers (if both have the value 2 they will

be identified as equal, for example), the same is not necessarily true if they
are reals. Because of the possibility of small errors in arithmetic, previous
arithmetic manipulation may result in very small but important differences
between the values. Hence, a value that is expected to be 2.0 may in fact
be 1.9999999999, which is very close, but far enough away to deliver an
unexpected result if compared with 2.0! As a general rule, it is unsafe to
test for the equality of reals.

Booleans
The data type 'Boolean', often called 'Bool' or 'logical' is the
simplest type of all, consisting of the two possible values 'true' and 'false'.

The name is derived from Boolean algebra (originally from the


mathematician George Boole) and, indeed, algebraic Boolean expressions
may be constructed using this type. Apart from their role in this branch
of mathematics, however, values of type 'Boolean' are useful as markers
or 'flags' to denote that a specific event has, or has not, occurred in our
program.
As an aside we can note that objects of type 'Boolean' are particularly
easy to represent in a computer since the digital electronic components
making up the computer usually work on a binary principle.

Exercises

2. 1 Choose suitable names for data types to embrace the values below
and add one extra element to each type.
{a) lion, tiger, leopard, cheetah;
{b) 2,3,5,7,11,13;

(c) 0011, 0110, 0101, 1001, 1100.


Exercises 15

2.2 What data types would be appropriate for the following values
arising in the context of a mortgage repayment calculation?
{a) The amount of money borrowed;
{b) The number of repayments;
{c) The mortgage interest rate;
(d) An indication of whether repayments are to be calculated on
a monthly or annual basis;
(e) The initials of the borrower's name.

2.3 Study the documentation of Pascal on your computer system and


find:

{a) The largest permitted integer (called 'maxint');


{b) The range and precision of real numbers;

(c) Whether the corresponding section of the character set is the

same as that shown in figure 2.4 (part of the common American


Standard Code for Information Interchange (ASCII) set).
^1

® Algorithms

Man is only a reed, the weakest thing in nature; but he is a thinking


reed.
Pensees, Blaise Pascal.

The purpose of our tool, the computer, is to solve problems, but in order
to do so a proposed solution to a problem needs to be expressed in terms
that are understandable to the computer programmer and that at the same
time are suitable for interpretation by the computer. A formalism for doing
this is called a pr'ogramming language and the problem solution written in

that language is called a computer program.


Before tackling the detailed form of a programming language we need
to ask what kind of problem the computer can be reasonably expected to
solve and in what general terms we must present our solution. In this
chapter we shall attempt to answer these key questions and to introduce
the notion of a formal representation for our problem solutions. It is then
a relatively small step to the constructs used in the programming language
Pascal which are developed in subsequent chapters.

3.1 Problem solving


Consider the following problem

Given the maze in figure 3.1, describe how the mouse should set

about finding the cheese.

Here is a possible solution:

Solution I
1. Start at the entrance.

16
Problem solving 17

2. Turn left, up, right, right, down, left, forward, right, left, left, up,
right, left, left, forward, left, down, right, right, up.

3. Eat cheese.

This solution takes advantage of our superior position and intellect


(compared to mice). We can see over walls which, we must assume, the
mouse cannot. Nevertheless, a reasonably literate mouse would have little

difficulty in following the path described in solution I.

On the other hand, solution I is completely ad hoc. Most importantly,


it does not solve the set problem since it says nothing about how to solve
the maze nor about how the mouse may set about finding a path. What
is written down is a description of a known path through the maze, and
that is very different.
Let us try again.

Solution II
1. Start at the entrance.
2. Move forward until

either a choice of routes is open


or the way is blocked
or the cheese is found.
3. If a choice of routes is open, try the right branch.
4. If the way is blocked, return to the last unexplored branch and
take it.

5. If the cheese is found, eat it, otherwise repeat from step 2.

Figure 3.1. Maze.


18 Algorithms
-^1

The path traced through the maze by this solution is shown in figure

3.2. ^

Eventually, solution II provides the mouse with a route to the cheese


but it is clear that the two approaches are radically different. In contrast
to solution I, which attempts to solve the problem explicitly by describing
a specific path, this second technique provides a general set of rules which
may be used to find a path through the maze. This is a systematic solution
to the maze problem. For all relevant conditions that may arise in the
traversal of the maze there is a system of rules specifying the actions to
be taken. The decision-making process is never left to intuition, nor does
it depend on previously determined knowledge of the correct path.

It is this systematic approach that is all-important in problem solving.


making up solution II represents an abstract
Significantly, the set of rules
solution to the maze problem. The rules are not coloured by details of a
specific maze and they are equally applicable to any maze. Indeed, it is

possible that we may encounter a maze that is too difficult to solve by the
first approach, perhaps by virtue of sheer size. If, however, we are endowed

with an extremely fast programmable mouse or, better still, if we could


simulate the mouse's activities using a computer, we may well find a
solution using the second approach.
To the computer programmer, the generality of application offered by
solutions of the type II above is extremely attractive. In a wider sense, the
'best' solutions to problems often embody a system of rules that solve a

whole set of related problems. In complete contrast, solution I is

computationally useless by the time we have written down the instructions


:

Figure 3.2. Solution II to the maze problem.

114'
i
i :
Algorithms and language 19

we have necessarily solved the problem manually and there is then not
much point in using a computer.

3.2 Algorithms and language


A sequence of steps to solve a problem, of the form illustrated in
solution II above, is called an algorithm. It is a way of expressing a strategy
for solving the problem in a systematic manner. Thus, the creation of an
algorithm may be imagined as an intermediate step in writing computer
programs and we may represent this as in figure 3.3.

Introducing this intermediate step raises a most important question.


How is the algorithm created, as if by magic, from the chaos of a problem?
The algorithm for the maze problem is a good example of this. It is not
difficult to see, in retrospect, why this algorithm works and how it appears
to solve the problem satisfactorily - it is not nearly so easy to explain how
that algorithm was developed in the first place! In fact, problem solving
remains an area of human activity that is not well understood and we shall
return to this argument later in this chapter. The wavy line connecting the
two boxes in figure 3.3 is intended to remind us that this is not a simple
transformation. In general, there no explicit way of deriving an algorithm
is

for a given problem and this aspect of computing is most aptly described
as the 'art' of computer programming; an art that is developed by
experience in solving progressively more difficult problems.
Fortunately, this 'rabbit from the magician's hat' appearance does not
mean that we can say nothing objectively about writing algorithms. Not
only are there techniques that are common to many problems, and we shall
investigate some of these in part 2, but there is much to be gained from

a disciplined approach to the design of algorithms. We may note, for


example, that the maze algorithm employs several distinct kinds of steps.
Whereas, normally, the rules are obeyed one after another, from top to
bottom, there is a particular construction at step 2 that obliges a
conditional choice of just one alternative, and another at step 5 that implies
a possible repetition of other steps. In fact, this threesome, which we may

Figure 3.3. From problem to program.

— computer
problem algorithm
program
20 Algorithms

term respectively sequence, condition and repetition, forms the backbone


of computer program design as we shall see later.

Developing algorithms for everyday activities can be an interesting


game. Here is an algorithm for delivering milk to a house.

Milk delivery algorithm


1 . Consult milk round book (or memory) for usual order from house.
2. Pick up order from milk float.

3. Approach house.
4. If there is no note

then leave the order


else read the note and
if the order is the same as or less than usual
then leave this order
else leave part of order (if possible),

return to milk float,


pick up the rest and take it to the house.
5. If there are empties, pick them up.
6. Return to milk float and store any empties.
7. Mark any changes to the order in the milk round book.

Clearly, this is not a very good algorithm - it is doubtful whether many


people would get their milk in time for breakfast if milkmen did not
anticipate changes in orders and, in practice, they will deal with a group
of houses together. However, to attempt to incorporate rules such as 'if

the sun is shining then Mr Jones is likely to want an extra pint today' would
only invite further suggestions for inclusion. We are not seriously trying
to describe the activity in any sense of completeness and, in common with
many everyday activities requiring intuition, an exhaustive algorithm
probably does not exist. Here, the algorithm is extremely informal.
In fact, the difference between an algorithm and a computer program
is precisely this matter of the formality of language. Both of the algorithms
we have met have been written in an abbreviated form of EngHsh, a natural
language. Although they may look quite explicit in their meanings this is

only because we have at our fingertips a remarkable wealth of knowledge


about the use of our language and about the environment of the problem
itself. In the milk delivery algorithm, for example, we make no attempt to
definewhat a 'milk float' or 'empties' are, nor what to 'consult' a milk
round book means. We take in our stride the reference to 'the last
Algorithms and language - 21

unexplored branch' and the interpretation of way is blocked' in the 'the

maze algorithm. It is only when we stop for a moment to think more closely
about this 'reading between the lines' that we begin to appreciate the
complexity of the underlying processing performed by humans with great
facility.

The deterministic computer does not share this ingrained experience of


the real world. The set of instructions obeyed by a computer makes up an
artificial language that does not leave room for the subtleties of natural
language. Each instruction to be obeyed has an unambiguous well-defined
interpretation in the context in which it occurs and the computer
programmer must learn to express algorithms within these constraints.
Having introduced the notion of language there are two linguistic terms
that are carried over into computing from natural language study. That
part of the grammar of a language that concerns the structure of words
and phrases is called syntax. Matters relating to the meaning of these words
and phrases are covered by the term semantics. Hence, for example, the
phrase 'The girl what is pretty' is syntactically incorrect according to the
grammatical rules of English. On the other hand, the sentence (proposed
by the linguist Noam Chomsky) 'Colourless green ideas sleep furiously'
is semantic nonsense (although it could be argued that it is syntactically
correct!). We shall see that this distinction between syntax and semantics
plays an important role in computer programming.
Note that the difference between an artificial language in which we write
programs and a natural language such as English is more than syntactic
complexity. Certainly, English has a very complex syntax but, in addition,
there are countless examples of where a sentence cannot be unambiguously
analysed by syntax alone: an unacceptable condition in a programming
language. Sometimes this is due to word sense ambiguity, as in the two
interpretations of 'foot' in the command 'move one foot forward'. As an
aside, it is worth noting that it was a misunderstanding of the importance
of the role played by semantic and extra-linguistic knowledge that
frustrated massive efforts during the 1 950s and early 1 960s to translate from
one natural language into another by computer. It is not difficult to see,

in retrospect, that it was quite reasonable for a translation program based


largely on syntax to translate the English source text 'out of sight, out of
mind' into the Russian language equivalent of 'invisible imbecile'. Some
more grammatical examples are mentioned in chapter 12.
The above examples illustrate that English is not a good medium for
communicating with computers. Existing programming languages avoid
22 Algorithms

the problems referred to by adhering to a relatively limited syntax which


may be parsed automatically and unambiguously. Parsing is the activity
concerned with analysing a statement in a language into its constituent
syntactic components and this term is also carried over into programming
languages. However, the fact that a programming language does not allow
us the syntactic freedom of English is not in itself a disadvantage. Whilst
it is convenient in the early stages to use an abbreviated form of English
to describe a proposed solution to a problem, the more formal constraints
of a programming language play a positive role in crystalHsing that
description. Looked at another way, if we are unable to express the
solution to a problem in a relatively simple formal language this probably
means we do not fully understand that problem. We should not expect the
computer to offer greater insight.

3.3 Another myth


Is there a limit to the problems computers can solve?
To conclude this chapter on algorithms it is worth devoting brief
attention to some limitations of computers and their problem solving
capabilities. This is not a matter of purely academic interest since it has
a bearing on a number of popular conceptions of the future potential of
computers. We hear fears expressed that it is only a matter of time before
computers 'take over' the world', with implications that we mere mortals
will be reduced to slaves of some new, greater intelligence. While this is

an extreme viewpoint, in general the limitations of computer applications


are not well-understood by the general public. Can we draw any conclusions
about such potential applications in the light of our discussion on problem
solving?
It was mentioned earlier that there are no general rules to formulate an
algorithm for a given problem. There is a close parallel here with that
important aspect of scientific inquiry the derivation of scientific theories
:

from empirical data. It has been suggested that, in general, we are quite
unable to derive scientific theories automatically from observed evidence.
This notion is bluntly expressed in the following quotation:

There are, then, no generally applicable 'rules of induction' by


which hypotheses or theories can be mechanically derived or
inferred from empirical data. The transition from data to theory
requires creative imagination. Scientific hypotheses and theories
are not derived from observed facts, but invented in order to
account for them. They constitute guesses at the connections that
Exercises 23

might obtain between the phenomena under study, at uniformities

and patterns that might undedie their occurrence. 'Happy guesses'


of this kind require great ingenuity, . .

Philosophy of Natural Science, Carl G. Hempel (Prentice Hall,


Englewood Cliffs, 1966, p. 15).

In a similar way,we seem unable to generate algorithms inductively from


the observed data and expected results of a general problem. Perhaps more
poignantly, in general the computer itself cannot devise algorithms. The
computer can do only what it is told to do and if we cannot tell ourselves
how we solve problems we cannot tell the computer either!
By implication, the role that cannot be usurped by our deterministic
computer is that of making the ingenious 'happy guesses' on the way to
devising an algorithm. Indeed, our own 'happy guesses' are often not yet
good enough to provide the computer with satisfactory algorithms and this

explains the inadequacy of our current 'natural-language-understanding'


programs, or the impossibiHty of instructing the computer to find a cure
for the common cold. Moreover, it can be proved that no algorithms can
be written to solve certain problems.
At a more down to earth level it is interesting to note that computer
programming is not a skill that is acquired primarily by the study of
advanced mathematics or science as is often suggested. Certainly, problem
solving requires a disciplined approach and the exposure to systematic
techniques experienced by the scientist is valuable. Yet equally valuable
experience is to be encountered in many other disciplines; for example, in
musical transposition, in the grammatical analysis of natural language and
in social science experimentation.

As a final comment, it is more fruitful to consider that the roles of man


and machine in the problem solving process are complementary rather than
competitive. Whereas the computer has been engineered superbly for
executing algorithms, the human brain was engineered (with unimpeachable
quality of design) for quite different processes.

Exercises

3.1 Modify the algorithm for the maze solution in figure 3.2 so that
the first action on encountering a choice of routes is to take the
left branch and then trace the route through the maze.

3.2 Mark likely syntactic and semantic errors in the following


statements
Algorithms

(a) The data is in the computer.


^ (b) The computer ate the banana.

How many potential (if odd !) interpretations of the sentence Time


flies hke an arrow' can you identify?

3.3 Write an informal algorithm for one of the following:

(^7) Making a cup of coffee.


(b) Getting dressed.
(c) Taking a car out of a garage.
Computers and programs

The technology behind the computer has advanced quite dramatically


over the last thirty years. Early valve computers gave way to transistors,
transistors to integrated circuits and, more recently, the microprocessor, the
'computer on a chip' has appeared. The age of the personal computer is
upon us before many of the big sixties mainframe computers have reached
the scrap heap.
Amid this technological revolution it is perhaps surprising to realise that
the fundamental computer programming principles defined by Dr Von
Neuman over thirty years ago remain substantially unaltered. Computers
have become faster, smaller in physical size and larger in capacity but the
way in which they operate from a programmer's point of view is little

changed.
In this chapter we some of these computer programming
shall study

characteristics in more concrete terms how our tool,


and hence discover
the computer, may be put to work. Two different aspects of a computer
system become apparent here. The hardware consists of the tangible pieces
of the computer - the electronic circuits, the magnetic tapes, keyboards
and displays etc. The intangible programs which enable the computer to
perform useful work are referred to by the term software and it is on the
software that we shall be concentrating later. Firstly, however, a brief
overview of the component parts of a computer system will assist us in

appreciating the vehicle on which software may be developed.

4.1 A computer model


There are many angles from which to view a computer system. One
could start from a hardware viewpoint and introduce elements of digital
electronics into the description. Another approach might begin by
25
26 Computers and programs

describing items of equipment used in computing such as a card reader


or a line printer. However, we are less interested for the moment in the

mechanisms used to construct computing devices than we are in the logical

operation of, and relationships between, the basic components. For this

latter point of view we consider a 'black-box' model shown in figure 4.


and in the discussion that follows it is largely irrelevant what physical
mechanisms the boxes contain. Thus, they may well contain electronic
circuits but the same external effect may be achieved, perhaps, using a
steam engine with pistons and valves or even by a person equipped with
pencil and paper.
At the heart of the computer lies the central processing unit (CPU for
short). This is made up of a control unit, whose task is to direct the
execution of a program, and an arithmetic unit to perform basic operations
such as adding, subtracting or comparing items of data. There is also a
store, in which a program and its data are retained and from which data
are communicated to the CPU. Again under the control of the CPU, data
may be moved into, and out of, the store via input and output devices
respectively.
The store consists of a series of storage locations, each identified by an
address, in which we may keep program instructions and items of data.
We may compare the store to a rack of pigeon holes used to hold mail
the store contents correspond to the mail in the rack whilst the address
of the location is analogous to the name above the pigeon hole. In the same
way that mail may be removed or replaced in the pigeon holes so the
contents of a store location may be changed. A typical computer will

Figure 4.1. A 'black-box' computer.

central
processing
unit (CPU)
control unit

arithmetic unit

input output
store
device device
A computer model 27

contain thousands, perhaps hundreds of thousands of such storage


locations.
One of the characteristics of a computer, separating it from a simple
calculator, for example, is the notion of a stored program. In its most basic
form, a calculator is operated by keying in a number, depressing an
operator key (-f, for example), keying in a second number and pressing
the equals button to obtain the result. Thus, the instructions to perform
chains of operations are not stored within the device but are executed
immediately they are entered by the user. In a computer, all instructions
(the program) are entered into the store before they are obeyed. On a
command to begin, instructions are taken from the store in sequence and
executed one by one by the control unit.
Careful distinction must be drawn here between the program instructions,
which specify the action to be taken, and the program data on which those
instructions operate. We may illustrate this by an example. Suppose the
task of the computer is to read in three integers, to add them together and
print out the result. We may express this task algorithmically:

read number
1st

read 2nd number


read 3rd number
add numbers
print the sum.

As discussed earlier, the informal nature of the language in which this


problem is formulated does not lend itself to being easily interpreted by
a computer. The same task is written below in the programming language
Pascal.

read (a);
read(b);
read(c);
sum:=a + b + c;
write(sum)

In this program, the ambiguity associated with the terms '1st number',
'2nd number' etc. referred to in the former description is eliminated by use
of the symbolic entities 'a', 'b', etc. However, putting aside detailed
examination of the statements in this program to later chapters, let us
examine the way in which a computer would obey such a program in the
terms of our black-box model.
With any program the first step is to convert the statements into a basic
28 Computers and programs

machine representation and to store the set of instructions making up this

representation in the computer store. Conceptually,' we shall divide the

store into two, one side to hold the program and the other the data, in

order to emphasise the difference, as shown in figure 4.2. (In practice, the

same physical store may be used for either purpose.) In figure 4.2 the
program is shown in its original form rather than in a basic machine
representation which would be too obscure and difficult to follow. The
explanation that follows, however, is unchanged by this simplification.

Before the program can be executed we need four storage locations in


which to hold the data for this program. These are reserved for the
quantities 'a', 'h\ 'o! and 'sum' and we shall assume that each is just the
right size and shape to hold an integer. Since such a location is capable
of holding any integer we refer to 'a', 'b', 'o! etc. as variables. (More
technically, we shall call the computer analogue of the name over the
pigeon-hole the identifier of that location.)
The program is now stored in the computer ready to be obeyed,
instruction by instruction from top to bottom. Note that up to this point
there has been no mention of any actual numbers to be added together,
merely a detailed formal description of how to do the addition. Not until
the program is obeyed do we provide the numbers and this is fundamental
to programming - we write the program in abstract terms and provide the
specific input data at execution or run-time, that is, when the program is

obeyed. The action of obeying the first three statements is to fetch numbers
presented to the input device and to copy their values into the data
locations specified ('a', 'b' and 'c') as shown in figure 4.3.
Obeying the instruction 'sum: = a-fb+c' involves use of the arithmetic
unit to perform the addition, with the result being placed in the location
by 'sum'. A copy of the sum is transferred to an output
identified device,
and hence to the outside world, by the 'write' statement.

Figure 4.2. A stored program.

a b

read(a);

read(b);

read(c);
c sum

sum:= a + b + c;

write(sum)

STORE
PROGRAM DATA
Programming languages _~ 29
m

Note finally in this example that the same program may be re-run as
many times as desired to find the sums of any three integers.

4.2 Programming languages


It was assumed in working through !he last example that the
black-box computer obeyed directly such instructions as 'read' and 'write'.

In practice, it is most unlikely that the hardware of the computer system


will be capable of accepting directly such complex instructions as these
(though this is not inconceivable in the future). The primitive level of
operation of the computer consists of very basic instructions written in the
machine code of that particular machine, with different machines using
different codes. Programs in machine code may be made up of strings of
binary digits - Os and Is - which are decoded by the computer hardware.

By careful study of a computer manufacturer's documentation it is

possible to write programs directly in machine code. However, the


investment in time and effort to do so is substantial and the size of problem
that could be tackled is severely limited. Historically, the first developments
in the area of a language more suitable for programming resulted in the
arrival of Assembly languages. In essence, these are usually little more
advanced than machine code but they enable programs to be written in
a symbolic representation in place of the binary code. The generic term
for all languages of this nature, which reflect the basic machine architecture,

is 'low-level' or 'machine-oriented'.

Programming in a low-level language suffers from some serious draw-


backs. Such languages are often quite difficult to learn and to use; it is easy
to make mistakes and often difficult to find them and programs cannot be
transferred to a computer with a different machine code. Perhaps more
importantly, the task of programming in a low-level language is demanding

Figure 4.3. Data values for a, b and c.

a b

read(a); 23 17
read(b);
c sum
read(c);
-*6-*17-^23
sum:=a + b + c;
6
From input device
write(sum)
Other documents randomly have
different content
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like