4.2 Programming as a Step-Wise Strategy
89
In this chapter, we will use an example to present a typical code writing process
in detail. Our focus will be on a step-wise approach that is so often required, unless
the programmer is experienced and the programming task is “small”.
Often, such a step-wise approach starts out with a very simple version of the
final program you have in mind. You test and modify that simple version until it
runs like you want. Then you include some more code, test and modify that version
until it works fine. Then you include more code, test and modify, and so on. Each of
these steps then brings you closer to your final target program. In some cases, all the
steps are clear in advance, but often, new insight develops along the way, making it
necessary to modify the plan. The step-wise approach is good also in that it allows
you to get started with a step or two (that you see are needed), even if you do not
know how to proceed from there, at least yet.
How to break up a programming task into a series of steps is not unique. It
will also depend on the problem, as well as on the programmer. More experienced
programmers can save time by writing the final version of some program in one go
(or at least with few steps). Beginners, however, may greatly benefit from a stepwise procedure with the sufficient number of steps. The following example should
illustrate the idea.
4.2.1 Making a Times Tables Test
The Programming Task Write a program that tests the user’s knowledge of the
times tables from 1 to 10.
Breaking up the Task There are many possible ways to do such a times tables
testing, but our reasoning goes as follows. In this test, there will be 10 different
questions for the 1 times table, 10 different questions for the 2 times table, and so
on, giving a 100 different questions in total. We decide to ask each of those questions
one time only. There are quite many questions, so we also allow the user to quit with
Ctrl-c (i.e., hold the Ctrl key down while typing c) before reaching the end.
To code this, the first idea that possibly comes to mind, is to use a double for
loop on a form like:
for a in [1, 2, ..., 10]:
for b in [1, 2, ..., 10]:
< ask user: a*b = ? >
< check answer, give points >
With a construction like this, we see that for each value of a, the second factor b
will run over all values 1 to 10. The questions will then appear in a predictable and
systematic way. First we get the 1 times table (1*1, 1*2, . . . , 1*10), then the 2
times table (2*1, 2*2, . . . , 2*10), and so on. Clearly, this would be an acceptable
approach. However, some would still argue that it might be better if the 100
questions were randomized, depriving the user any benefit from just remembering a
sequence of answers.
Précédent

- 110/350

Suivant