Assembly program to find the factorial of a number

Write an Assembly Language program to find the Factorial of a Number

Program:-

    AREA FACT,CODE,READONLY
    ENTRY
    MOV R0,#4
    MOV R1,R0
FACT SUBS R1,R1,#1
    CMP R1,#1
    BNQ SKIP
    MUL R3,R0,R1
    MOV R0,R3
    BNE FACT
SKIP
STOP B STOP
    END

Explanation:-

The ARM assembly code you provided calculates the factorial of a number. Here’s a step-by-step breakdown of how the code works:

AREA FACT,CODE,READONLY
ENTRY
  • These lines define the program area as read-only code and specify the entry point of the program.
MOV R0,#4
MOV R1,R0
  • These instructions initialize R0 with the value 4 (which is the number for which we want to calculate the factorial) and create a copy of this value in R1. R0 will be used to calculate the factorial, and R1 will be used as a loop counter.
FACT SUBS R1,R1,#1
  • This instruction subtracts 1 from the value in R1. It’s used as a loop counter to decrement the value until it reaches 1.
CMP R1,#1
BNQ SKIP
  • The CMP instruction compares the value in R1 with 1. If R1 is not equal to 1 (i.e., BNQ or “Branch if Not Equal” condition), the program branches to the SKIP label.
MUL R3,R0,R1
MOV R0,R3
  • These instructions calculate the factorial. They multiply the value in R0 (which initially contains 4) by the value in R1. The result is stored in R3 and then moved back to R0. This way, R0 accumulates the factorial value.
BNE FACT
  • If R1 is not equal to 1 (as checked earlier), this branch instruction jumps back to the FACT label to continue the loop, subtracting 1 from R1 and calculating the factorial iteratively.
SKIP
STOP B STOP
  • The SKIP label is the target of the branch instruction. After the factorial is calculated and R1 becomes 1, the program skips the loop and continues execution from here. The STOP B STOP combination creates an infinite loop, effectively halting the program.
END
  • This marks the end of the program.

In summary, this ARM assembly code calculates the factorial of 4 (or any number initially loaded into R0) and stores the result in R0. It uses a loop and iterative multiplication to achieve this.

Leave a Reply

Your email address will not be published. Required fields are marked *