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
R0with the value 4 (which is the number for which we want to calculate the factorial) and create a copy of this value inR1.R0will be used to calculate the factorial, andR1will 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
CMPinstruction compares the value inR1with 1. IfR1is not equal to 1 (i.e.,BNQor “Branch if Not Equal” condition), the program branches to theSKIPlabel.
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 inR1. The result is stored inR3and then moved back toR0. This way,R0accumulates the factorial value.
BNE FACT
- If
R1is not equal to 1 (as checked earlier), this branch instruction jumps back to theFACTlabel to continue the loop, subtracting 1 fromR1and calculating the factorial iteratively.
SKIP STOP B STOP
- The
SKIPlabel is the target of the branch instruction. After the factorial is calculated andR1becomes 1, the program skips the loop and continues execution from here. TheSTOP B STOPcombination 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.
