Information Technology Reference
In-Depth Information
Figure 1.2.
Adding three single-digit numbers
Procedure PROC1:
You are given three digits as input, a , t , and b .
You will return two digits as output, c and s .
1.
Call PROC0 on t and b , and let u and v be the answers returned.
(The u is the left digit returned by PROC0, and the v is the right one.)
Call PROC0 on a and v , and let u and v be the answers returned.
(The u is the left digit returned, and the v is the right one.)
2.
u =
v .
3.
If u
=
0 , then return with c
=
0 and s
=
u =
v .
If u
=
1 , then return with c
=
2 and s
=
v .
Otherwise, return with c
=
1 and s
=
PROC1
Now, building on this procedure, consider adding three digits. Intuitively, one should
add the first two digits and then take the sum and add the last digit to it. However one
needs to worry about the carry digits to get the answer right. The procedure PROC1
in figure 1.2 does this. It calls PROC0 twice and then decides whether the final carry
digit to return should be 0 , 1 ,or 2 .
Trace the behavior of this procedure in detail to make sure you understand how it
works. Suppose PROC1 is called with inputs 7 , 4 , and 5 .
= 7 , t
= 4 , and b
= 5 . Determine the values of c and s to return.
At the start, a
1.
Call PROC0 on 4 and 5 , which returns 09 .So u
=
0 and v
=
9 .
Call PROC0 on 7 and 9 , which returns 16 .So u =
1 and v =
2.
6 .
u , so return with c
3.
Then u
=
=
1 and s
=
6 .
The output returned by PROC1 in this case is 16 , as desired.
Here are some other examples to make sure you understand how this works:
If PROC1 is called on 3 , 4 , and 1 , it will return 08 : u and v will be 0 and 5 , and
u and v will be 0 and 8 ,so c will be 0 and s will be 8 .
If PROC1 is called on 8 , 9 , and 2 , it will return 19 : u and v will be 1 and 1 , and
u and v will be 0 and 9 ,so c will be 1 and s will be 9 .
 
Search WWH ::




Custom Search