How To Think Like A Programmer: Problem Solving For The Bewildered
How To Think Like A Programmer: Problem Solving For The Bewildered
How To Think Like A Programmer: Problem Solving For The Bewildered
net/publication/236270907
CITATION READS
1 19,897
1 author:
Paul Vickers
Northumbria University
123 PUBLICATIONS 786 CITATIONS
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
Context Informed Intelligent Information Infrastructures for Better Situational Awareness View project
All content following this page was uploaded by Paul Vickers on 08 January 2014.
ISBN: 978-1-84480-900-4
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
1 Introduction: Starting to
Think Like a Programmer
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Learning Objectives
■ Understand how to use the book and its special features
■ Understand how programs are structured recipes (algorithms) to calculate/
compute the answer to a given problem
■ See how using abstraction is necessary for solving problems
■ Understand the difference between solving problems and writing computer pro-
gramming language code
This chapter serves two purposes. First, it describes for whom the book is intended,
how the book is structured, and how to use it. Secondly, you will learn what a computer
program is, why programmers write programs, and what they use to write those
programs. You will discover the difference between writing program code and solving
problems and you will learn why good programmers are, primarily, good problem
solvers.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Think Spots
The Think Spot is a point in the text where a question (or a number of ques-
tions) is raised for you to think about. To get the most benefit you should take
1
If this book is being used at pre college/university level then it might be used over an entire
term or semester.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
a little time to think about the questions rather than just reading them and
moving straight on. The famous Kodak Picture Spot signs at Disney World are
sited at places where a great photograph can be taken; similarly, the Think Spot
is located at points where you will really benefit from some reflective thinking
and so develop the bigger picture.
In-text Exercises
Throughout the book you will see a picture of a pencil in the margins alongside
some text in a shaded box denoting a short exercise:
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Throughout the book you will see pictures of Brian looking bewildered in the
margin. He appears at points where beginning programmers often have trouble
understanding the point being made. Further down the page (or possibly on the
next page) after seeing Brian you will find a box like this:
Huh?
I don’t understand why you said . . .
In the box is a question Brian the bewildered programmer is asking about the
material next to which his picture appeared. Brian’s queries are the kinds of
frequently-asked questions (FAQ) I have been asked over the years by beginning
programmers. The answer to the FAQ usually appears in the box below the ques-
tion, though sometimes you are required to try to answer Brian’s FAQ yourself.
The book’s accompanying website (at www.cengage.co.uk/vickers) contains a
section where readers can submit their own FAQs seeking answers to issues that
still cause puzzlement. I would like to encourage readers to submit their own
FAQs and I will then provide answers to these on the website as appropriate.
End-of-chapter Exercises
Each chapter has exercises at the end. The exercises are designed to help you
reflect on what has been covered in that chapter. Any time you cannot complete
an exercise suggests that you would benefit from going over the material again.
Some exercises may be based on a single section (identified by the heading num-
ber), others may require ideas from several sections, and a few bring together the
whole chapter. Solutions to selected exercises are given in Appendix C.
Projects
After the normal end-of-chapter exercises you will find some longer project-style
exercises. These longer exercises are themed and will give you practice in incre-
mentally building larger and larger solutions to more complex problems. The initial
themes are introduced in the exercises at the end of this chapter and are then devel-
oped with each subsequent chapter. In these projects, you will be working toward
developing complete programs that make use of most of the programming
techniques discussed in this book. The projects cover a range of different problem
scenarios, such as constructing a vending machine algorithm, decoding hazchem
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
signs, working with Roman numerals and dates, playing with sentences that use all
the letters of the alphabet, and working with ISBNs for an online bookstore.
Layout
All programming language code, pseudo-code (Chapter 3), examples of text that
would appear on a computer screen or in a file on the computer’s hard disc (or
removable diskette), and examples of text that would be entered into a computer
via the keyboard will appear in this monospaced typewriter-style font.
Reflections
Sometimes you will see a word or phrase set in SMALL CAPITAL LETTERS. Such
words and phrases are the titles of short reflective opinion pieces that appear in
the Reflections chapter (immediately following Chapter 8). These Reflections are
designed to introduce some more complicated ideas that the interested reader
can use to deepen their understanding of some of the problems and issues faced
by programmers today.
2
It has been estimated that some of today’s very large computer systems are the most com-
plex artefacts ever built.
3
Actually, the program may itself be considered a machine, only one built from logic rather
than metal and plastic. For a clear and concise discussion of the program as machine, see
Software Requirements and Specifications (Jackson, 1995).
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
withdrawal request. When I select a hot wash to get my cotton shirts really clean
I am telling my washing machine to use the program (set of instructions) that will
draw and heat enough water, release the detergent at the right time, rinse with
cool water, and so on.
If you think about it, a computer program is in many ways just like a recipe.
If you have ever cooked a meal then you will recall having to carry out particu-
lar tasks in a certain order. Even something as simple as making buttered toast or
muffins requires that you spread the butter after the bread/muffin has come out
of the toaster. You successfully make buttered toast or muffins (and keep your
toaster in good working order) when you carry out the steps in the right order.
If you have never done so, find a cookery book and look at some of the recipes. You will see
all the things you have to do in order to prepare various meals.
A good recipe is one that clearly sets out all that you have to do and when,
that gives precise quantities for the ingredients, and that tells you what temper-
ature to use in the oven and for how long to cook the dish. If the instructions are
well set out then it should be possible for anyone to follow them and produce the
desired result.
A musical score is a bit like a program too. Over hundreds of years musicians
and composers have developed formalized languages of notation that allow
musical instructions to be communicated on paper. A music score indicates all
the notes to be played including their durations and volumes. Sections of the
score can be marked for repetition including alternate endings to repeated
phrases. Other marks tell the musician to speed up, slow down, pause, play
louder, play more softly, etc. As long as a musician knows how to read and
interpret a score then he or she can play music written by somebody else. The
score in Figure 1.1 is presented in Western musical notation and shows a sim-
ple piece of piano music. It has a repeated section and alternative endings for
the repeated section.
FIGURE 1.1 A simple musical score: In this piece of music the first two bars are played through
three times. The first two times they are followed by the music in Bar 3, and by the fourth bar after
the third play through. The dots before the third bar line indicate that the previous section is to be
repeated. The brackets with numbers indicate what should be played and how many times.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Algorithms
Algorithm is a common word in programming circles. An algorithm is a rule, or
a finite set of steps, for solving a mathematical problem. In computing it means
a set of procedures for solving a problem or computing a result. The word algo-
rithm is a derivation of Al-Khwarizmi (native of Khwarizm), the name given to
the ninth-century mathematician Abu Ja’far Mohammed ben Musa who came
from Khwarizm (modern day Khiva in the south of Uzbekistan). Thus, this book
is about learning how to understand problems and design algorithms that are
solutions to those problems.
4
For example, imagine if the problem were to calculate the monthly payments on a loan.
Your solution should work for all the possible values of loan amount, loan duration, interest
rate, and so on, and not just for the example numbers given in the problem specification.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
FIGURE 1.2 Abu Ja’far Mohammed, aka Al-Khwarizmi after whom the algorithm is named.
terms without focusing on its concrete details. For example, if you talk about
driving in your car, the word car is really an abstraction for the specific individ-
ual car you drive. Your car will be different from my car. Even two cars of the
same make, model, year, and specification are still different from each other
inasmuch as they are both individuals. Person is an abstraction, as are man,
woman, child, boy, girl, and so on. We all use abstraction in our everyday lives;
indeed, without it we would not be able to function for it enables us to ignore
all the fine details that would otherwise overwhelm us. The money in my pock-
et (how much, what currency, how many coins, what year were they minted,
how many notes, their serial numbers), the people in the shop (how many
men, women, boys, girls, what are their names, nationalities, ethnic groups,
ages, heights, educational qualifications, first languages, etc.), and the stars in
the sky are all abstract ways of managing an otherwise unmanageable amount
of information.
Programmers use abstraction as a way of simplifying and managing detail.
However, unlike most of our everyday abstractions, programmers do not actually
ignore the detail, instead they defer its consideration. At some point the detail will
need to be considered. Part of being a programmer is learning how to juggle
abstractions, ignoring the fine detail when it is appropriate to do so.
This book follows the practice of dealing with control abstraction and
data abstraction separately. The algorithms you will learn to build in this
book control and manipulate data in order to produce desired results.
When you withdraw money from your bank you are performing control
(the sequence of actions necessary to withdraw the money) to manipulate
data (the amount of money in your account, the date it was withdrawn, and
so forth). Regarding data, this book takes a highly abstract view treating all the
data in the problems it presents simply as values. Our control abstractions take
a fairly general form in the beginning but as the book progresses the level of
abstraction is lowered as we consider more specialized ways of performing
actions.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Heuristic
This book takes a HEURISTIC approach to solving problems and expressing those
solutions as algorithms. Having solved the problem and produced a correspon-
ding algorithm, the programmer would then translate the algorithm into
programming language code (a lower level of abstraction). When presented with
an algorithm in a computer programming language such as Java or BASIC, the
computer can carry out the instructions in the algorithm many millions of times
faster (and reliably and accurately) than any person could.
Most books jump right away into the specific requirements of a given program-
ming language and the learner will, through no fault of his or her own, associate
the art of programming with writing instructions in a programming language. But
using a programming language is one of the final steps in the process of writing a
program. This book focuses on teaching you to concentrate on the most important
stages: understanding the problem at hand and solving it algorithmically.
Too many beginning programmers blend problem solving with coding and
treat them as one activity and then (reasonably) see programming as hard.
Problem solving requires thinking about the problem at a high level of abstrac-
tion while writing programming language code requires a very low level of
abstraction. Inevitably, the learner starts trying to apply the very low level of
abstractions in their thinking about the problem. In fact, if problem solving
and coding are separated we discover that the coding aspects are reasonably
straightforward while it is really problem solving where the difficulty lies.
One skill you will develop as a programmer is being able to think in terms of
high-level abstractions (understanding and thinking about the problem at hand)
and in terms of low level abstractions (individual data items, their format, and
their status) simultaneously. However, having witnessed the confusion that can
arise when a beginner is asked to do this from the very beginning, I decided in this
book to make a clear separation between the high-level problem-solving skills and
the low-level language-coding skills. Once you have become comfortable in
approaching problems and producing algorithmic solutions, it is then time to think
about translating the algorithms into a programming language. This book
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
unashamedly deals with the high-level abstraction and leaves the translation exer-
cise to other books that deal with specific programming languages. Eventually,
after learning how to solve problems and then how to translate algorithms into
programming language code you will find yourself able to mix the low-level
abstractions with the high-level ones and the boundary between problem solving
and writing in the chosen programming language will become more fluid.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
is clumsy, or both (though this is a general rule that does not always apply –
sometimes speed of execution is more important than elegance or comprehensi-
bility). Therefore, in Chapter 8 we will look at some of the techniques available
to you for designing good programs that are, after all, just solutions to problems.
5
Take the following anonymous book dedication: “to my parents, George Pólya and God.”
What does that mean? Surely the author is not claiming that God is one of his parents? The
sentence is syntactically (grammatically) correct though its meaning can be misunderstood.
The addition of an extra comma makes things much clearer: “to my parents, George Pólya,
and God.” Most people are taught not to put a comma after the element that precedes the
‘and’ in a list, yet in this case adding the serial comma really helps to make the author’s mean-
ing crystal clear. You may be interested to know that the serial comma is also known as the
Oxford comma as it is a stylistic practice of the Oxford University Press (OUP). The OUP uses
it precisely because it removes ambiguity from lists. Most people do not use it, but I do. If you
look closely you will see that it is used throughout this book. You hadn’t noticed? Shame on
you, programmers need to have an eye for detail you know.
6
Certain problems in mathematics and engineering excepted.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
1.8 Exercises 13
the problem. That is, it calculates the correct tax or it correctly stores the text
entered by the user of the word processor. The solution to the problem is provided
by you, the programmer. It is you who solves the problem by deciding the correct
series of instructions that, when followed, result in the desired outcome. The
process of solving the problem is really the essence of computer programming.
Many people are fooled into thinking that writing programming language code is
what defines programming. Not so. Writing the code is merely the stage of express-
ing the solution to the problem in a way that it can be communicated to the
computer. Once we have the solution, correctly expressing it in the chosen pro-
gramming language does take skill and experience, but to be able to write the
program code we must first solve the problem. Moreover, before we can solve
the problem we must first understand it. It is one thing to try to write the program
code for a problem we understand but have not completely solved yet (though
this is still bad practice); it is quite another thing to try to write the code for a
problem we do not even understand. Explaining tasks to a person and to a
computer is essentially the same; the difference is the required level of precision, or
un-ambiguity (abstraction), in the language used.
1.8 Exercises
1. What is an algorithm?
2. What is a program? Try giving an answer in no more than thirty words. Do you know some-
one who is very poor at understanding technology (usually they cannot program their video
recorder or set the stations on their car radio)? If so, how would you explain to him or her
what a computer program is?
3. Describe your wallet using three different levels of abstraction: low (as many details as you
can think of), medium (the main points), and high (identifying characteristics only).
4. Put on my shoes is a highly abstract description of a common task. To describe the task
at a lower level of abstraction requires some details to be known. Jot down some of the
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
main pieces of information that are needed to be able to describe step-by-step the process
of putting on a pair of shoes.
5. Learning to write Java/C/Visual Basic/programming language of your choice is not the
same thing as learning to program. Why not?
6. What were the causes of the First World War?
1.9 Projects
Below are the four themed projects that will be used to develop your program-
ming skills throughout the rest of the book. After each set of end-of-chapter
exercises you will find additional exercises related to one or more of these
projects. As you progress through the book you will find yourself extending
your solutions until you have outline algorithms for complete programs.
Your task for this chapter is to read through the project descriptions and
familiarize yourself with their contents. Try to identify what problems might
exist.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
1.9 Projects 15
The first character of the EAC is a number identifying the method to be used
for fighting any fire. The second character is a letter identifying the safety
precautions to be taken by firefighters, whether a violent or explosive reaction is
possible, and whether to dilute or contain any spill. The third character is either
blank or an E indicating the existence of a public safety hazard. The four-digit code
is the United Nations substance identification number that is used to find out the
exact name of the chemical. The hazard warning diamond gives specific informa-
tion about the nature of the hazard. Table 1.1 shows how to decode the EAC.
Table 1.1 Emergency Action Code: required firefighting methods and precautions
P V
LTS(CPC)
R
Dilute spillage
S V
BA & fire kit
T
W V
LTS(CPC)
X
Contain spillage
Y V
BA & fire kit
Z
Key
V = Can be violently or explosively reactive
BA = Breathing apparatus
LTS = Liquid tight Suit/Chemical Protection Suit and BA required
DILUTE = Spillage may be washed away when greatly diluted with
large quantities of water.
CONTAIN = Spillage must not enter water courses or drains.
DRY AGENT = Water must not be allowed to contact substance.
What patterns can you see in Table 1.1? How might these patterns help in
solving problems related to the decoding of an Emergency Action Code?
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Empire that had an altogether different numbering system. In the Roman system,
numbers are represented by combinations of the primitives given in Table 1.2
below. The number 51 is written as LI, the number 1,500 is written as MD, and
so on. Further, the numbers 4, 9, 40, 90, 400, and 900 are written as IV, IX, XL,
XC, CD, and CM respectively. Thus, 14 is XIV, 99 is XCIX, etc. (What is common
to the numbers 9, 40, 90, and 900?). In this system, the year 1999 would be writ-
ten as MCMXCIX and the year 2007 as MMVII.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
As you can imagine, arithmetic is not so simple using such numbers. For exam-
ple, consider the simple sum 1,999 ⫹ 2,007 using Roman numerals:
MCMCXIX ⫹ MMVII ⫽ ?
The answer is MMMMVI. Why do we need to know about Roman numerals
today? The media industry still uses them. TV shows have the year of produc-
tion expressed in Roman numerals, as do some movies, books, and so on. The
pages in the front matter of books (before the first chapter) are numbered using
Roman numerals with Arabic digits being reserved for the main body (look at
the page numbers for the preface in this book).
Imagine you are writing software for a media production company that needs
a reliable way of dealing with translation of dates into Roman numerals. What
sorts of problems might you face in converting between decimal numbers and
Roman numerals?
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
1.9 Projects 17
It is not terribly meaningful even if they are all real words. Most pangrams are not
isogrammatic, so the next goal is to make them as close to being isogrammatic as pos-
sible. Here are some more pangrams with their letter count shown in parentheses.
Pack my box with five dozen liquor jugs (32, e, i, and o repeated).
Waltz, bad nymph, for quick jigs vex (28, only a and i repeated – not as meaningful
though).
Six plump boys guzzled cheap raw vodka quite joyfully (46).
Sympathizing would fix Quaker objectives (36).
Quick waxy bugs jump the frozen veldt (31).
Brick quiz whangs jumpy veldt fox (27).
Think about what problems exist in constructing a pangram and in determin-
ing whether a sentence is a pangram. If it is, determine if it is isogrammatic.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
7
The book in question is Karma Ura and Karma Galay (eds), Gross National Happiness and
Development: Proceedings of the First International Seminar on Operationalization of Gross National
Happiness, The Centre for Bhutan Studies, Thimphu, Bhutan, 2004. However, you won’t find
it on Amazon. The group code is 99936 which is used for books published in the Kingdom of
Bhutan.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Licensed to: iChapters User
Chapter 1
End of Chapter Exercises
1. There are some quite formal definitions, but in layman’s terms an algorithm
is a set of clear instructions to carry out a defined task.
2. A computer program is an algorithm expressed in a programming language to
be carried out by a computer.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
A P P E N D I X C Solutions to Selected Exercises 231
3. High: black leather. Medium: A black leather billfold with a single fastening.
Two main currency pockets plus slots for cards. Low: A black leather billfold
with a single fastening about 5 years old, contains £25 in cash: a £20 note (the
old design with Edward Elgar on the back) and a £5 note; 4 debit card receipts,
1 ATM receipt, 1 debit card, 1 credit card, and my Engineering Council regis-
tration card ...
6. Well, you might be a history student taking programming as a compulsory
course! The answer “the assassination in Sarajevo of Archduke Ferdinand by
Gavrilo Princip” is too simplistic and will not receive credit.
Chapter 1 Projects
StockSnackz Vending Machine
No solutions for this chapter.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
View publication stats