|
Table of Contents
Learning C++:
An Index of Entry Points
2. The A reference document on the basic elements of C++.
3. The Patterns
|
Back a few paragraphs we said that there were three
parts to developing a correct algorithm. The first two were Now we discuss the third part. It turns out that computer-based
solutions to certain problems don't always take the same form as human
oriented solutions. And, even when they do, there are often ways of
phrasing the solution in algorithmic form that are easier to translate
into code. A simplistic example: Suppose we had written the 'if' part of
the algorithm above as: To an English speaker, this means the same thing as the above algorithm
but it may not be clear to a novice programmer that "when....otherwise" is
translated as 'if...else'. More important there are times when a computer algorithm must include
details that would never be included in a set of instructions meant for a
human. Consider the program from chapter 2 to calculate the sum of 10
numbers (ch2prg4.cpp) . Instructions
given to a human for this problem would be something like:
However, this is not at all how a computer solves this problem - as you
can see from looking at the code in ch2prg4.cpp Therefore, translating
these instructions into C++ code would be a difficult task. The challenge
is to find an algorithm that is correct AND easy to translate. Consider
the following more 'computer friendly' algorithm for this problem:
You will learn how to write easily translatable algorithms as you learn
how to code but in the meantime you need an aid in writing good
algorithms. It turns out that there are a number of general patterns
or templates that underlie many common coding problems. Expert
programmers simply 'know' these and use them in developing their
algorithms. These patterns represent the general form your algorithms
should take when faced with certain classes of problems. The rest of this
chapter discusses a number of these patterns and provides coding examples
based on these. You are strongly advised to study these carefully and use
them when you begin a new programming problem. They are meant to guide you
in the design process and to help you avoid having to 're-invent the
wheel' every time you start a new program. (For those simply wanting a summary of the patterns themselves, a separate
document is provided.) |