Pascal Programming A Beginners Guide to Computers and Programming 2nd Edition Chris Hawksley download
Pascal Programming A Beginners Guide to Computers and Programming 2nd Edition Chris Hawksley download
https://ebookgate.com/product/pascal-programming-a-beginners-
guide-to-computers-and-programming-2nd-edition-chris-hawksley/
https://ebookgate.com/product/programming-wpf-2nd-edition-chris-sells/
ebookgate.com
https://ebookgate.com/product/pic-programming-for-beginners-arrl/
ebookgate.com
https://ebookgate.com/product/cnc-programming-handbook-a-
comprehensive-guide-to-practical-cnc-programming-3rd-edition-edition-
smid/
ebookgate.com
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
https://ebookgate.com/product/absolute-beginner-s-guide-to-
programming-2nd-edition-greg-perry/
ebookgate.com
https://ebookgate.com/product/programming-windows-presentation-
foundation-1st-edition-chris-sells/
ebookgate.com
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.
CHRIS HAWKSLEY
Department of Computer Science, University of Keele
SECOND EDITION
Hawksley, Chris
Pascal programming: a beginner's guide to computers and
programming. - 2nd ed.
Includes index.
1 . PASCAL (Computer program language)
2. Electronic digital computers - Programming.
\rm^ ^ 86-13627
UP
To my parents
1
I
Digitized by tine Internet Archive
in 2015
https://archive.org/details/pascalprogramminOOchri
Contents
Preface xi
1 Introduction 1
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
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
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 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
C. Hawksley
June 1982
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
Chris Hawksley
Keele, February 1986
© Introduction
The last thing one knows in constructing a work is what to put first.
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
Foundations of programming
Data and information
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
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.
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.
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
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
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!
3850 + 2165
operator to deliver the integer that is the numerical sum of the two. In
another context, however, such as
'PIECE'
+ 'MEAL'
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
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
'
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
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
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
0.66666666667
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
:
I I-
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'.
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;
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.
® Algorithms
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
Given the maze in figure 3.1, describe how the mouse should set
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.
Solution II
1. Start at the entrance.
2. Move forward until
The path traced through the maze by this solution is shown in figure
3.2. ^
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
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.
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
— computer
problem algorithm
program
20 Algorithms
3. Approach house.
4. If there is no note
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
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.
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:
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.
changed.
In this chapter we some of these computer programming
shall study
operation of, and relationships between, the basic components. For this
central
processing
unit (CPU)
control unit
arithmetic unit
input output
store
device device
A computer model 27
read number
1st
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
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.
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.
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.
is 'low-level' or 'machine-oriented'.
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.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.
• 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 comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
ebookgate.com