Assignment 8 Solution

MAL program

.data

array:		.byte	0:80	# stack to store characters of
				# string
print_stack:	.byte	0:4	# stack to store digits of
				# integer

enter_str:	.asciiz "\n Enter string   : "
cont_str:	.asciiz "\n\n Do you want to continue(y/n):"
reverse_str:	.asciiz "\n Reversed string: "
length_str:     .asciiz "\n String length  = "

#	$8  - Base address of array
#	$9  - Array pointer
#	$11 - String length
#	$13 - Print stack base address
#	$14 - Print stack pointer

.text

__start:
	la $8,array		# Initializing the array pointer
	move $9,$8

	jal get_input		# Get the string input

	la $13,reverse_str
	puts $13
	jal string_reverse	# Reverse the string

	la $13,length_str
	puts $13
	la $13,print_stack	# Print out the string length
	move $14,$13
	jal put_integer

	la $9,cont_str		# Loop for repeated input
	puts $9
	getc $10
	li $15,'y'
	beq $10,$15,__start
	done

# Procedure get_input gets the input from the user as a
# sequence of characters, stores them in a byte array
# and ignores characters when the string length exceeds
# 80 characters. However the condition for termination
# is newline character

get_input:
	li $11,0		# Initalizing string length
				# to 0
	la $12,enter_str
	puts $12
loop:
	getc $12
	beq $12,'\n',end_input	# Check if end of line
	bge $11,80,loop		# Check if string length > 80
	sb $12,($9)
	add $9,$9,1		# Store the character in the
	add $11,$11,1		# byte array
	b loop
end_input:
	jr $31

# Procedure string_reverse reverses the string by loading
# the bytes in the byte array. This is done until the
# array pointer becomes less than the base address of the
# array when it means that all the characters in the
# string have been output

string_reverse:
	sub $9,$9,1
	blt $9,$8,ret
	lb $12,($9)
	putc $12
	b string_reverse	 
ret:
	jr $31

# Procedure put_integer prints an integer by storing it
# in a stack and reversing the digits and displaying
# them as ascii characters

put_integer:
	li $15,10
	bgez $11,pos
	li $12,'-'		# If the number if negative
	putc $12		# print the negative sign
	sub $11,$0,$11		# and negate the number
pos:
	blt $11,$15,last
	rem $12,$11,10		# loop for storing the remainder
	add $12,$12,48		# of number by 10 into the stack
	sb $12,($14)
	add $14,$14,1
	div $11,$11,10
	b pos
last:
	add $11,$11,48		# if the number becomes < 0
	putc $11		# print that digit
ar_loop:
	beq $14,$13,ret
	sub $14,$14,1		# read the contents of the
	lb $15,($14)		# stack and print it out
	putc $15
	b ar_loop
ret:
	jr $31