Question

LC3 stack (factorial) I need help in writing factorial in Lc3 language by using stack.. ; Begin ...

LC3 stack (factorial)

I need help in writing factorial in Lc3 language by using stack..

; Begin reserved section: do not change ANYTHING in reserved section!

                .ORIG x3000
                BR Main
                
; Parameter and result
Param           .FILL x0004
Result          .BLKW 1

; Constants
Stack           .FILL x4000
One             .FILL #1
MinusOne        .FILL #-1

; End reserved section: do not change ANYTHING in reserved section!
;-------------------------------------------------------------------------------

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; int Factorial(int N)
; Returns N! (must be a recursive function)
;
Factorial       ;__________________ ; Step 3: allocate space for return value
                ;__________________ ; Step 4: push return address
                ;__________________ ; Step 5: push previous frame pointer
                ;__________________ ; Step 6: setup new frame pointer
                ;__________________ ; Step 7: allocate space for local variable
                
                ;;;;;;;;;;;;;;;;;;;;; Step 8: body of the function
                
Checkpoint1     LDR   R0, R5, #4    ; Load parameter N into a register
                
                LD    R1, MinusOne  ; Calculate N - 1
                ADD   R2, R0, R1    ; R2 will contain N - 1
                
                ;__________________ ; Store N - 1 in the local variable
                
                BRnz  BaseCase      ; Detect base case (N <= 1)
                
                ;;;; Start of the recursive call
                
                ;__________________ ; Step 1: push parameter N - 1
                ;__________________ ; Step 2: call Factorial(N - 1)
                ;__________________ ; Step 13: retrieve return value into R2
                ;__________________ ; Step 14: remove parameter from stack
                
                LDR   R0, R5, #4    ; Multiply N * Factorial(N - 1)
                .ZERO R3            ; R3 will contain the product
MultiplyLoop    ADD   R3, R3, R2    ; Notice that by this point, R0 > 1
                ADD   R0, R0, #-1   ;
                BRp   MultiplyLoop  ;
                
                ;__________________ ; Make return value = N * Factorial(N - 1)
                
                BR    Finish
                
                ;;;; End of the recursive call
                
                ;;;; Start of the base case
                
BaseCase        LD    R0, One       ; Make return value = 1
                STR   R0, R5, #3    ;
                
                ;;;; End of the base case
                
                ;;;;;;;;;;;;;;;;;;;;; End of the body of the function
                
Finish          ;__________________ ; Step 9: remove local variable from stack
                ;__________________ ; Step 10: restore previous frame pointer
                ;__________________ ; Step 11: restore return address
Checkpoint2     RET                 ; Step 12: return to calling subroutine

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Entry point
; Calls Factorial(Param) and stores the return value in Result
;
Main            LD    R6, Stack     ; Initialize stack pointer
                LD    R5, Stack     ; Initialize frame pointer
                
                LD    R0, Param     ; Load parameter into a register
                
                ;__________________ ; Step 1: push parameter
                ;__________________ ; Step 2: call Factorial(Param)
                ;__________________ ; Step 13: retrieve return value
                ;__________________ ; Step 14: remove parameter from stack
                
                ;__________________ ; Store return value in Result
                
TheEnd          HALT
                
               .END
                

Here is a C implementation:

#include <stdio.h>

int Param = 0x0004;
int Result;
  
/** Compute N! recursively */
int Factorial(int N) {
  int Temp = N - 1;
  
  if (Temp > 0) { 
    // Recursive call
    return N * Factorial(Temp);
  } else {
    // Base case (N <= 1)
    return 1;
  }
}

/** Entry point */
int main() {
  Result = Factorial(Param);
  printf("Return value is x%04X\n", Result);
  return 0;
}

Thank you.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

.ORIG x3000

AND R1,R1,#0

ADD R1,R1,x7 ; INPUT - DO FACTORIAL OF 7, STORE IT IN R2

AND R2,R2,#0 ; result store

ADD R2,R2,#1

DECR

AND R3,R3,#0

ADD R3,R3,R1 ; r3=r1

AND R4,R4,#0

MULT

ADD R4,R4,R2

ADD R3,R3,#-1

BRp MULT

AND R2,R2,#0

ADD R2,R2,R4 ; r2=r4

ADD R1,R1,#-1

BRp DECR

.END

Add a comment
Know the answer?
Add Answer to:
LC3 stack (factorial) I need help in writing factorial in Lc3 language by using stack.. ; Begin ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • LC-3 Programming Help!! The Stack Protocol The following outline is the protocol for passing arguments to...

    LC-3 Programming Help!! The Stack Protocol The following outline is the protocol for passing arguments to a function and returning values. Everything is stored on the runtime stack so that space is used only when the function is executing. As a result the actual address of arguments and locals may change from call to call. However, the layout of the stack frame (activation record) is constant. Thus, the offests from the frame pointer (FP) to the parameters/locals are constant. All...

  • You must implement the following methods using Java's Stack Object. /**    * Computes the factorial of...

    You must implement the following methods using Java's Stack Object. /**    * Computes the factorial of n    * @param n-integer value greater or equal to 0    * @return n!    */    public static int factorial( int n ) { } /**    * Computes the nth term of the Fibonacci sequence    * @param n -nth term to find    * @return -the nth term    */    public static int fibonacci( int n ) {}    /**    * Find the min value using the comparable interface...

  • ASSEMBLY LANGUAGE (Mars MIPS) Starting code: Factorial: #Factorial Recursive function subu $sp, $sp, 4 sw $ra,...

    ASSEMBLY LANGUAGE (Mars MIPS) Starting code: Factorial: #Factorial Recursive function subu $sp, $sp, 4 sw $ra, 4($sp) # save the return address on stack beqz $a0, terminate # test for termination subu $sp, $sp, 4 # do not terminate yet sw $a0, 4($sp) # save the parameter sub $a0, $a0, 1 # will call with a smaller argument jal Factorial # after the termination condition is reached these lines # will be executed lw $t0, 4($sp) # the argument I...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Call stack question! Long one... The call stack is part of main memory that is reserved...

    Call stack question! Long one... The call stack is part of main memory that is reserved for function calling. Like all r memory it is finite, so can be exhausted resulting in a stack overflow. Recursive functions allocate space on the stack for each recursive call: if there are many such recursive calls a stack overflow can result. The questions that follow ask you to investigate recursive functions and stack overflows. Note that when running programs in the Linux terminal...

  • I just need to add comment for the code blow. Pleas add comment for each method...

    I just need to add comment for the code blow. Pleas add comment for each method and class if comments left out. package exercise01; /*************************************************************************** * <p> This program demonstrates the technique of recursion and includes * recursive methods that are defined for a variety of mathematical * functions. *    * <br>A recursive method is one that directly or indirectly calls itself * and must include: * <br>(1) end case: stopping condition * which terminates/ends recursion * <br>(2) reduction:...

  • // I need help with the following questions. Please use java programming ECLIPSE language to solve...

    // I need help with the following questions. Please use java programming ECLIPSE language to solve the questions. YOU ONLY NEED TO DIRECTLY COPY IT IN YOUR ECLIPSE APPLICATION AND RUN IT. I NEED THOSE PART WHICH IS SAYS --> "TO BE COMPLETED" I NEED HELP WITH [GET*] AND [REPLACE ALL] AND [ADD INT DOUBLE] PLEASE. import java.util.ArrayList; public class CustomArrayList { //instance variables public int[] data; //data.length gives the capacity public int nItems; //nItems gives items currently in the...

  • Need help. write a C program stack-ptr.c that implements a stack using a link list. Below...

    Need help. write a C program stack-ptr.c that implements a stack using a link list. Below is a skeleton code to start with.Jjust edit to make thread friendly. examplpe: push(5, &top); push(10, &top); push(15, &top); int value = pop(&top); value = pop(&top); value = pop(&top); this program currently has a race condition. use Pthread mutex locks to fix the race conditions. test you now thread safe stack by creating 200 concurrent threads in main() that push and pop values. -use...

  • Note: The question needs to be answered in "C Programming Languange ". And after the question fin...

    Note: The question needs to be answered in "C Programming Languange ". And after the question find 3 pages for needed informations. Spring CE4717 Language Processors Q1. Consider the following LEx program. return R1 return R2 return R3 return R4 return R5; return R6; IA-2a-z)[A-Za-z0-9]- -2 10-91+ 10-9a-EA-FI Ihi] [01] [01] 이삐 t Vtin) int main (void) int tcode; do f tcode -yylex()i printf ("token type td \"%s\"\n", tcode, yytext); ) while (tcode)i return 0; i. Explain the steps needed...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT