How To Think Like A Programmer Problem Solving For
How To Think Like A Programmer Problem Solving For
READS
474
1 author:
Paul Vickers
Northumbria University
82 PUBLICATIONS 436 CITATIONS
SEE PROFILE
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
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.
1.1
1.2
1.3
1.4
Teaching Approach
1.5
1.6
1.7
Chapter Summary
1.8
Exercises
1.9
Projects
Learning Objectives
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.
You have just started to learn a programming language at a university or college. You are only a little way into the course, but already you are starting to
feel lost and panicky and may even be falling behind.
You have tried to learn programming and have come away feeling that it is
terribly difficult. You have either fallen at the first hurdle or have finished an introductory course, but in either case you are left feeling bewildered with a sense that
you never really understood it. If someone were to ask you which aspects of the
subject you were having particular difficulty with, you would reply all of it.
You have not learned any programming before, but it is a mandatory part of
your university or college degree (which may not even be in Computer
Science or Engineering). You feel anxious about it.
You are taking, or are about to take, an introductory programming course.
You have had a look at the set textbook and even the first few chapters seem
too advanced for you.
You are a secondary/high school student and you need an introductory book
to get you started with the basics.
You are a mature reader. You are not necessarily on a formal course of study
(though you may be) and you would like to find out what computer programming is about. Perhaps you have had a look at some other books and they all
seem too advanced, too technical (even the introductory ones). You do not
think you are a dummy or even an idiot, but you would like to see if you can
get a foothold on what appears to be an interesting subject.
If you have identified yourself in the above list then continue reading. If you
have not, continue reading anyway so that you can recommend this book to people
you know who need to read it (and who can then stop bugging you for help!).
Think Spots
The Think Spot is a point in the text where a question (or a number of questions) 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.
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:
Key terms and important points appear in the margin next to the paragraph or
section in which they are introduced or defined. Together with the index this
feature should make it easier for you to find what you are looking for.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
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?
In the box is a question Brian the bewildered programmer is asking about the
material next to which his picture appeared. Brians 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 question, though sometimes you are required to try to answer Brians FAQ yourself.
The books 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 number), 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 incrementally 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 developed 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.
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 computers 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.
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.
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 particular 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 temperature 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 simple 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.
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 algorithm is a derivation of Al-Khwarizmi (native of Khwarizm), the name given to
the ninth-century mathematician Abu Jafar 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.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
FIGURE 1.2
Abu Jafar 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 individual 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 pocket (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.
Heuristic
This book takes a HEURISTIC approach to solving problems and expressing those
solutions as algorithms. Having solved the problem and produced a corresponding 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 programming 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 abstraction 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.
FIGURE 1.3
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.
11
unashamedly deals with the high-level abstraction and leaves the translation exercise 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.
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 comprehensibility). 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.
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
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 expressing 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 programming 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 someone 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.
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.
6.
1.9 Projects
Below are the four themed projects that will be used to develop your programming 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.
Hazchem sign
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
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 information about the nature of the hazard. Table 1.1 shows how to decode the EAC.
Table 1.1
Coarse spray
Foam
Fine spray
Dry agent
V
LTS(CPC)
R
S
Dilute spillage
V
BA & fire kit
T
W
V
LTS(CPC)
X
Y
Contain spillage
V
BA & fire kit
Z
Public safety hazard
E
Key
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.
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 written as MCMXCIX and the year 2007 as MMVII.
Table 1.2
Decimal Equivalent
10
50
100
500
1000
As you can imagine, arithmetic is not so simple using such numbers. For example, 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 production 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.
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 possible. 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 determining whether a sentence is a pangram. If it is, determine if it is isogrammatic.
The different parts can have different lengths and usually are printed with
hyphens separating the blocks (the hyphens are not part of the number). The
check digit is introduced to ensure that the previous nine digits have been correctly transcribed. It can be a digit (09) or the character X (representing the value
10 it is not necessary yet to understand how the check digit is calculated).
Until January 2007 all ISBNs were 10 digits. A new 13-digit format was introduced in January 2007 (known as ISBN-13 or Bookland EAN). All 10-digit
Copyright 2008 Cengage Learning, Inc. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part.
Hyphenating an ISBN
Raw ISBN
Hyphenated ISBN
Book Title
0140124993
0-14-012499-3
How to Solve It
999361419X
99936-14-19-X
8466605037
84-666-0503-7
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 wont 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.
Chapter 1
End of Chapter Exercises
1. There are some quite formal definitions, but in laymans 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.
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 registration 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.