Reputation: 3
Please help, I need the sum of the squares of the first 5 numbers using DEBUG - Assembly programming in DOSBOX. This an example of a 2^2:
-a 100 </i>
15BC:0100 mov ax,1
15BC:0103 mov bx,2 ; Base Number
15BC:0106 mov cx,2 ; Exponent
15BC:0109 ;bucle 109:
15BC:0109 mov dx,0
15BC:010C mul bx
15BC:010E loop 109
15BC:0110 int 20
15BC:0112
-g 110
Upvotes: 0
Views: 613
Reputation: 2493
The instruction mul bx
multiplies the content of ax
(always) with the content of the bx
register (the parameter). Cause that are 16 bit registers, the result can have up to 32 bits. The lower 16 bits of this result are placed in ax
and the higher 16 bits in dx
. So you don't have to clear dx
before mul
. That's only necessary for div
.
The code to calculate ax = 3²
(in general ax = bx
cx
) would then be:
mov ax, 1
mov bx, 3 ; Base Number (that is multiplied by itself cx plus one times)
mov cx, 2 ; Exponent (how often the multiplication should be repeated)
expLoop:
mul bx
loop expLoop
If only the square is to be calculated, the loop is no longer necessary and the code could be simplified:
mov ax, 3 ; Base Number (that is multiplied by itself one time)
mul ax
This will calculate 3²
(in general ax²
). Note that bx
and cx
are not used here anymore.
As Michael already mentioned, you have to sum up your results after this if you want to get a sum of squares. Cause cx
is not used anymore, it could be used with loop
to iterate over all the numbers to be squared. bx
could be used to store the sum of the squares:
xor bx, bx ; Sum is initialised to zero
mov cx, 5 ; Iterate from 5 down to 1
iterate:
mov ax, cx
mul cx ; Calculate the square of the acutal number
add bx, ax ; Sum up the squares in bx
loop iterate
Upvotes: 2