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 inR1
.R0
will be used to calculate the factorial, andR1
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 inR1
with 1. IfR1
is not equal to 1 (i.e.,BNQ
or “Branch if Not Equal” condition), the program branches to theSKIP
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 inR1
. The result is stored inR3
and then moved back toR0
. 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 theFACT
label to continue the loop, subtracting 1 fromR1
and calculating the factorial iteratively.
SKIP STOP B STOP
- The
SKIP
label is the target of the branch instruction. After the factorial is calculated andR1
becomes 1, the program skips the loop and continues execution from here. TheSTOP 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.