Information Technology Reference
In-Depth Information
Figure 1.4.
Adding any list of numbers
Procedure PROC3:
You are given a list of numbers
n
1
,
n
2
, ....
You will return a single number
sum
as output.
1.
Let
sum
start off being the single digit
0
.
2.
Start with the first number
n
1
and
sum
. Make sure they both have the same
number of digits by inserting
0
symbols on the left as needed. Then call PROC2
on these two numbers, and let the new value of
sum
be the number it returns.
3.
Do the same thing with
n
2
and the current value of
sum
, to produce the next
value for
sum
.
4.
Continue in this way with the rest of the numbers,
n
3
,
n
4
, ....
5.
Return as output the final value of
sum
.
2.
Call PROC1 with
a
=
0
(the
c
from the previous step),
t
=
4
, and
b
=
8
.
It will return
c
=
1
and
s
=
2
.So
z
2
will be
2
.
=
1
(the
c
from the previous step),
t
=
7
, and
b
=
2
.
3.
Call PROC1 with
a
=
1
and
s
=
0
.So
z
1
will be
0
.
It will return
c
4. Finally,
z
0
will be
1
(the last
c
returned).
So the answer returned by PROC2 on
747
and
281
will be the four digits
1028
. And
sure enough, 1028 is the sum of 747 and 281. Again observe that the procedure does
not explain itself. Nowhere does it say that each digit stands for a power of ten (units,
tens, hundreds, thousands, and so on) with the unit digits on the right. However,
even if you do not know what the symbols are supposed to mean or why you are
doing the operations, if you follow the directions in PROC2 exactly, keeping track of
where you are at each step, you will add the two numbers correctly.
PROC3
Now consider a general addition procedure that will add any list of numbers, each
with any number of digits. The procedure for this is in figure 1.4. It is easy to see that
it does the right thing, repeatedly adding two numbers using PROC2 and keeping a
running total. (PROC3 is not explicit about how to pad the shorter numbers with
0
symbols on the left. Imagine there is a PROC4 that does that.)