ARM Assembly Program to Find Largest of Three Numbers
cmp and bgt instructions, and stores the largest value in a register; for example: ldr r0, =num1; ldr r1, =num2; ldr r2, =num3; cmp r0, r1; bgt check_r0_r2; mov r3, r1; b check_end; check_r0_r2: cmp r0, r2; bgt set_r0; mov r3, r2; b check_end; set_r0: mov r3, r0; check_end: where r3 holds the largest number.Examples
How to Think About It
Algorithm
Code
.data num1: .word 5 num2: .word 3 num3: .word 7 result: .word 0 .text .global _start _start: ldr r0, =num1 ldr r1, [r0] ldr r0, =num2 ldr r2, [r0] ldr r0, =num3 ldr r3, [r0] cmp r1, r2 bgt check_r1_r3 mov r4, r2 b check_end check_r1_r3: mov r4, r1 check_end: cmp r4, r3 bgt store_result mov r4, r3 store_result: ldr r0, =result str r4, [r0] /* Exit syscall for Linux */ mov r7, #1 mov r0, #0 svc #0
Dry Run
Let's trace input num1=5, num2=3, num3=7 through the code
Load numbers
r1=5, r2=3, r3=7
Compare r1 and r2
5 > 3 is true, so r4 = 5
Compare r4 and r3
5 > 7 is false, so r4 = 7
Store result
Store 7 in memory location 'result'
| Step | Register/Memory | Value |
|---|---|---|
| 1 | r1, r2, r3 | 5, 3, 7 |
| 2 | r4 after cmp r1,r2 | 5 |
| 3 | r4 after cmp r4,r3 | 7 |
| 4 | result memory | 7 |
Why This Works
Step 1: Load numbers into registers
The program loads each of the three numbers from memory into registers r1, r2, and r3 to prepare for comparison.
Step 2: Compare first two numbers
Using cmp and bgt, it checks if r1 is greater than r2 and stores the larger in r4.
Step 3: Compare with third number
It then compares the current largest (in r4) with r3 and updates r4 if r3 is larger.
Step 4: Store the largest number
Finally, it stores the largest number from r4 back into memory for later use or output.
Alternative Approaches
ldr r0, =num1
ldr r1, [r0]
ldr r0, =num2
ldr r2, [r0]
ldr r0, =num3
ldr r3, [r0]
mov r4, r1
cmp r2, r4
movgt r4, r2
cmp r3, r4
movgt r4, r3
ldr r0, =result
str r4, [r0]
ldr r0, =num1
ldr r1, [r0]
ldr r0, =num2
ldr r2, [r0]
ldr r0, =num3
ldr r3, [r0]
push {r1, r2, r3}
pop {r4, r5, r6}
cmp r4, r5
movgt r7, r4
movle r7, r5
cmp r7, r6
movgt r7, r7
movle r7, r6
ldr r0, =result
str r7, [r0]
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of comparisons and moves, so it runs in constant time regardless of input.
Space Complexity
Only a few registers and a small fixed memory space are used, so space complexity is constant.
Which Approach is Fastest?
Using conditional execution instructions is fastest because it avoids branching, reducing pipeline stalls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic compare and branch | O(1) | O(1) | Simple and clear logic |
| Conditional execution | O(1) | O(1) | Faster execution with fewer branches |
| Stack and loop | O(1) | O(1) | More complex, less efficient for small fixed inputs |
movgt to simplify comparisons and reduce branching.