I am interested in converting the Fibonacci sequence code in C ++ to the ARM assembly language. The code in C ++ is as follows:
#include <iostream>
using namespace std;
int main()
{
int range, first = 0 , second = 1, fibonacci;
cout << "Enter range for the Fibonacci Sequence" << endl;
cin >> range;
for (int i = 0; i < range; i++)
{
if (i <=1)
{
fibonacci = i;
}
else
{
fibonacci = first and second;
first = second;
second = fibonacci;
}
}
cout << fibonacci << endl;
return 0;
}
My attempt to convert this to an assembly is as follows:
ldr r0, =0x00000000 ;loads 0 in r0
ldr r1, =0x00000001 ;loads 1 into r1
ldr r2, =0x00000002 ;loads 2 into r2, this will be the equivalent of 'n' in C++ code,
but I will force the value of 'n' when writing this code
ldr r3, =0x00000000 ;r3 will be used as a counter in the loop
;r4 will be used as 'fibonacci'
loop:
cmp r3,
it lt
movlt r4, r3 ;If r3 is less than
0 or 1.
it eq ;If r3 is equal to 2, run through these instructions
addeq r4, r0, r1
moveq r0,r1
mov r1, r4
adds r3, r3,
it gt ;Similarly, if r3 is greater than 2, run though these instructions
addgt r4, r0, r1
movgt r0, r1
mov r1, r4
adds r3, r3,
I am not entirely sure that this will be done if you make statements in the Assembly, but for me this will be a secondary problem. I'm more interested in how I can include an if statement to check the initial condition in which the โcounterโ is compared to the โrangeโ. If the counter is <range, then it should go to the main part of the code where the Fibonacci operator will be iterated. Then it will continue the cycle to the end = range.
I am not sure how to do the following:
cmp r3, r2
;If r3 < r2
{
<code>
}
;else, stop
Also, for the correct loop, can I add:
cmp r3, r2
bne loop
, , r3 = r2?
:)