Code in C for Factorial

Code in C for Factorial

<p> # Code in C for Factorial: # main () 25 fact: # Subroutine "fact". First setup stack frame. # { Stack: 26 subu $sp,$sp,8 # Stack frame is 8 bytes long # printf ("The factorial of 3 is %d\n", 27 sw $ra,0($sp) # Save return address fact( 3 ) ); 28 sw $a0,4($sp) # Save argument (n) # } 29 # check for ending condition (n <= 0) # 30 lw $v0,4($sp) # Load n # int fact (int n) 31 bgtz $v0,recurse # Branch if n > 0 # { 32 li $v0,1 # Return 1 # if (n < 1) 33 jr return # Jump to code to return # return (1); 34 recurse: # else 35 # compute n-1 and make recursive call # return (n * fact (n - 1)); 36 lw $v1,4($sp) # Load n # } 37 subu $v0,$v1,1 # Compute n - 1 sp 38 move $a0,$v0 # Move value to $a0 1 .data 39 jal fact # Call factorial function 2 answer: 40 # upon returning from the recursion, compute the product 3 .asciiz "The factorial of 3 is: " 41 lw $v1,4($sp) # Load n 4 .text 42 mul $v0,$v0,$v1 # Compute fact(n-1) * n 5 main: 43 return: 6 # Setup stack frame for main() 44 # restore callee-saved registers and return the value in $v0 7 subu $sp,$sp,8 # Stack frame is 8 bytes long 45 lw $ra, 0($sp) # Restore $ra 8 sw $ra,0($sp) # Save return address 46 addiu $sp, $sp, 8 # Pop stack 9 # load parameter for factorial in a0 and call factorial function 47 jr $ra # Return to caller 10 li $a0,3 # Put argument in $a0 11 jal fact # Call factorial function Trace: (pretend addresses are decimal, not hex) 12 $v0 $v1 $a0 $ra $a1 13 # after returning from function, display result string and value 14 move $a1,$v0 # Move fact result to $a1 15 la $a0,answer # Put format string in $a0 16 li $v0, 4 # Code for Print String 17 syscall 18 move $a0,$a1 # Move fact result to $a0 for printing 19 li $v0, 1 # Code for Print Integer 20 syscall 21 # before exiting main(), restore saved reg. and pop stack frame 22 lw $ra,0($sp) # Restore return address 23 addiu $sp,$sp,8 # Pop stack frame 24 jr $ra # Return to caller</p>

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    1 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us