1 Replies - 3287 Views - Last Post: 03 October 2011 - 09:33 AM

#1 dorknexus   User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1272
  • View blog
  • Posts: 4,625
  • Joined: 02-May 04

Factorial by Recursive Procedure Calls

Posted 27 August 2008 - 11:00 AM

Description: Conveys the general idea of how to make recursive calls in MIPS assembly. This particular procedure calculates n!
# The same function in C would look something like this
# int fact(int n)
# {
#      if (n < 1)
#           return (1);
#      else
#           return (n * fact(n - 1));
# }



.data

input_request: .asciiz "Input the first operand: "
output1: .asciiz "The result is "
newline: .asciiz "n"

.align 2

.globl main

.text

main: 
	# request input from user
	la $a0, input_request
	li $v0, 4
	syscall
	
	# retrieve input from user
	li $v0, 5
	syscall
	
	# store user input as first operand
	move $a0, $v0
	
	# calculate factorial
	jal fact
	
	# store result
	move $t0, $v0
	
	# display result
	la $a0, output1
	li $v0, 4
	syscall
	
	move $a0, $t0
	li $v0, 1
	syscall
	
	la $a0, newline
	li $v0, 4
	syscall
	
	# exit program
	li $v0, 10
	syscall	
	
fact:
        # make room on stack for $ra and $a0
	move $fp, $sp
	addi $sp, $sp, -8
	
        # store both those registers on the stack
	sw $a0, 0($fp)
	sw $ra, -4($fp)
	
        # recursive condition
	bgtz $a0, fact_L1
	li $v0, 1
	j fact_return
	
        # recursive calls
	fact_L1:
		addi $a0, $a0, -1
		jal fact
		addi $fp, $sp, 8
		lw $a0, 0($fp)
		mult $a0, $v0
		mflo $v0
		j fact_return	
		
        # return sequence
	fact_return:
                # restore $ra and $a0 registers
		lw $ra, -4($fp)
		lw $a0, 0($fp)

		move $sp, $fp		
		
		jr $ra	




Is This A Good Question/Topic? 0
  • +

Replies To: Factorial by Recursive Procedure Calls

#2 divyeshchauhan   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 03-October 11

Re: Factorial by Recursive Procedure Calls

Posted 03 October 2011 - 09:33 AM

Great man!!!!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1