Task

Write a program to find the sum of squares of a numeric vector.

The program should work on a zero-length vector (with an answer of   0).



Related task

   Mean


		;;; Sum of squares
		cpu	8086
		bits	16
section		.text
		org	100h
		jmp	demo
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;;; Calculate the sum of the squares of the array in SI.
		;;; The array should contain 16-bit unsigned integers.
		;;; The output will be 32-bit.
		;;; Input: (DS:)SI = array, CX = array length
		;;; Output: DX:AX = sum of squares
		;;; Registers used: AX,BX,CX,DX,SI,DI
sumsqr:		xor	bx,bx	; Keep accumulator in BX:DI.
		xor	di,di	; (So zero it out first)
		and	cx,cx	; Counter register 0? "Program should work
		jz	.done	; on a zero-length vector"
.loop:		mov	ax,[si]	; Grab value from array
		mul	ax	; Calculate square of value (into DX:AX)
		add	di,ax	; Add low 16 bits to accumulator
		adc	bx,dx	; Add high 16 bits, plus carry
		inc	si	; Point to next value
		inc	si
		loop	.loop	; Next value in array
.done:		mov	ax,di	; Return the value in DX:AX as is tradition
		mov	dx,bx
		ret
		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
		;;; Demo: use the subroutine to calculate the sum of squares
		;;; in the included array, and show the result
demo:		mov	si,array
		mov	cx,arrlen
		call	sumsqr
		;;; Print the return value in DX:AX as a decimal number
		;;; (Note: max supported value 655359 - this is a limitation
		;;; of this rudimentary output code, not of the sum of squares
		;;; routine.)
		mov	di,outstr_end
		mov	cx,10
.decloop:	div	cx
		dec	di
		add	dl,'0'
		mov	[di],dl
		xor	dx,dx
		and	ax,ax
		jnz	.decloop
		mov	dx,di
		mov	ah,9
		int	21h
		ret
section		.data
outstr:		db	'######'	; Placeholder for decimal output 
outstr_end:	db	'$'
array:		dw	1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
arrlen:		equ	($-array)/2	; length is in words