0 Replies - 1051 Views - Last Post: 30 January 2013 - 10:05 AM

#1 ninjawesome222  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 106
  • Joined: 27-January 10

Converting C code to MIPS

Posted 30 January 2013 - 10:05 AM

I am trying to rewrite the following C code to MIPS:

# int fact(int n){ 
#  if(n<1) return 1; 
#  else return n * fact(n-1); 
# }    
#   int perm(int n, int k) 
#  { 
#  return fact(n)/fact(n-k);//calls another procedure 
#  }  
#  int main(){
#   int n = 10, k=5; 
#   printf(%d\n, perm(n,k)); 
#   return 1; 
#  }


However, I am a beginner and I am unsure how to correctly write the permutation function (perm). I believe I have written the factorial section properly, but I have no idea whether or not I am going in the right direction. Any help is appreciated. Code below.

.data
	msg1: .asciiz "Enter n: "
	msg2: .asciiz "Factorial of n is: "

.text
	la	$a0, msg1	#user input
	li	$v0, 4
	syscall			

	li	$v0, 5
	syscall			
	move	$t0, $v0

	addi	$sp, $sp, -12	#allocate bytes
	sw	$t0, 0($sp)	#n arguments
	sw	$ra, 8($sp)	#save counter
	jal	fact		#call function
	lw	$ra, 8($sp)	#recall counter
	lw	$s0, 4($sp)	#return value
	addi	$sp, $sp, 12	#deallocate bytes

	la	$a0, msg2	#print results
	li	$v0, 4
	syscall
	
	move	$a0, $s0
	li	$v0, 1
	syscall

	li	$v0, 10
	syscall

perm:
	sub	$t4, $t0, $t3	#n - k

	addi	$sp, $sp, -12	#allocate bytes
	sw	$t0, 0($sp)	#save value
	sw	$ra, 8($sp)	#save return
	jal	fact		#call recursion fact(n)

	lw	$ra, 8($sp)	#load return
	lw	$t1, 4($sp)	#load value
	addiu	$sp, $sp, 12	#deallocate bytes

	addiu	$sp, $sp, -12	#allocate bytes
	sw	$t4, 0($sp)	#save value
	sw	$ra, 8($sp)	#save return
	jal	fact		#call recursion fact(n-k)

	lw	$ra, 8($sp)	#load return
	lw	$t1, 4($sp)	#load value
	addiu	$sp, $sp, 12	#deallocate bytes

	div	$t5, $t0, $t4	#divide values

fact:
	lw	$t0, 0($sp)	#default case
	beq	$t0, 0, rtrn	#return 1
	addi	$t0, $t0, -1

	addi	$sp, $sp, -12	#allocate bytes
	sw	$t0, 0($sp)	#save value
	sw	$ra, 8($sp)	#save return
	jal	fact		#call recursion
	
	lw	$ra, 8($sp)	#load return
	lw	$t1, 4($sp)	#load value
	addiu	$sp, $sp, 12	#deallocate bytes

	lw	$t0, 0($sp)	#load value
	mul	$t2, $t1, $t0	#multiply n, (n - 1)
	sw	$t2, 16($sp)	#save value
	jr	$ra		#return value

rtrn:
	li	$t0, 1
	sw	$t0, 4($sp)	#save value
	jr	$ra		#return value


Is This A Good Question/Topic? 0
  • +

Page 1 of 1