SOLUTION TO HOMEWORK #4:
------------------------

7.1
	Answer depends on the index numbering. if the first element of array
	is numberred 0, then element 6 is the 7th element of the array, and
	the answer is:
		(a) 46	(b) 64	(c) 64	(d) 82

	If the first element of array is numbered 1, then element 6 is the 6th
	element, and the answer is:
		(a) 45	(b) 60	(c) 60	(d) 75

7.4
	m[8,10] = m[1000 + 4(8 - 0)(10 - 0 + 1) + 4(10 - 0)]
		= m[1000 + 32(11) + 40]
		= m[1392]

7.7
(a)			.data
		row:	.word	?
		col:	.word	?
		size:	.word	?
		addr:	.word
		offset:	.word
	
			.text
		mul	offset, col, j
		add	offset, offset, i
		mul	offset, offset, size
		la	addr, array
		add	addr, addr, offset

(b) The code changes for column-major order by replacing col with row,
and interchanging i with j.

			.data
		row:	.word	?
		col:	.word	?
		size:	.word	?
		addr:	.word
		offset:	.word
	
			.text
		mul	offset, row, i
		add	offset, offset, j
		mul	offset, offset, size
		la	addr, array
		add	addr, addr, offset


7.14 SAL code that reads single line of input and prints it in reverse order.

			.data
		stack:	.word	0:80
		sp:	.word	stack
		char:	.byte
		prompt:	.asciiz	"Input a line, and hit return"
		newline: .byte '\n'
		no:	.word	0		# no. of chars pushed


			.text
     __start:	puts	prompt
		put	newline
	input:	get	char			# get next char
		move	M[sp], char		# push char
		add	sp, sp, 4
		add	no, no, 1
		bne	char, newline, input	# branch if not end of line

	output:	sub	sp, sp, 4		# pop char
		move	char, M[sp]
		put	char			# print char
		sub	no, no, 1
		bnez	no, output		# loop if stack not empty

	end:	done

	

8.2 The value in register $12 would be 0, the third word of the array bb.

8.4

SAL code:
---------
			.data
		a:	.word
		bb:	.word
		c:	.word
		i:	.word 0

			.text
	for:	add	i, i, 1
		bgt	i, 20, next		# exit loop if i > 20
		add	a, a, bb
		bge	a, 5, for
	if:	move	c, a
		b	for
	next:

MAL code:
---------

			.data
		a:	.word
		bb:	.word
		c:	.word
		i:	.word 0

			.text
      __start:	lw	$7, i
		lw	$2, a
		lw	#3, bb
		lw	$4, c
		li	$5, 5
		li	$6, 20
	for:	add	$7, $7, 1
		bgt	$7, $6, next		# if i>20, exit loop
		add	$2, $2, $3		# a := a + b
		bge	$2, $5, for
		add	$4, $2, $0		# if a<5, then c <- a
		b	for`			# continue for loop
	next:
	

8.7 MAL code for reading one line of characters and printing in reverse order

	# $2 contains char read
	# $3 holds newline char
	# $4 and $5 are used for address calculation

			.data
		stack:	.byte	0:256
		str:	.asciiz	"Enter a line of characters.\n"

			.text
		# read in lin eof input into stack
     __start:	puts	str
		la	$4, stack
		move	#3, '\n'
		getc	$2
		beq	$2, $3, endwhile1
      while1:	sb	$2, ($4)		# push char
		add	$4, $4, 1
		getc	$2
		bne	$2, $3, while1
   endwhile1:	la	$5, stack
		sub	$4, $4, 1		# pop char
		bgt	$5, $4, endwhile2
       while2:	lbu	$2, ($4)
		putc	$2
		sub	$4, $4, 1
		bge	$4, $5, while2
   endwhile2:	done