PEP 8 Assembly Language Programming Write a program to calculate the sum of the
ID: 3826644 • Letter: P
Question
PEP 8 Assembly Language Programming
Write a program to calculate the sum of the first n integers.
Main should input an integer and then call RecSum, which is a recursive function.
Add trace tags.
The code for sum is:
if (n==0) return 0;
else return n+ RecSum(n-1);
You should test it with several different inputs. You can use the formula to check whether you are getting the correct answer.
The formula is Sum(n) = n* (n+1)/2
Note: you are not coding the formula - you need to code the recursive method.
recSum1:
BR main
num: .equate 0 ;local variable #2d
n: .equate 0;parameter #2d
retVal: .equate 2 ;#2d
main: subsp 2,i ; allocate #num
deci num, s
lda num,s
subsp 4,i ;;allocate #retVal #n
sta num,s
;call RecSum
addsp 2,i ;deallocate #n
deco 0,s ; output answer;
addsp 4,i ;deallocate #retVal #num
stop
.end
Rec Sum 2:
BR main
num: .equate 0 ;local variable #2d
n: .equate 2;parameter #2d
retVal: .equate 4 ;#2d
RecSum: lda 2,s
cpa 0,i
brgt else
br done
else: lda 1,i
done: sta retVal,s
ret0
main: subsp 2,i ; allocate #num
deci num, s
lda num,s
subsp 4,i ;;allocate #retVal #n
sta num,s
call RecSum
addsp 2,i ;deallocate #n
deco 0,s ; output answer;
addsp 4,i ;deallocate #retVal #num
stop
.end
Explanation / Answer
CODE:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movq %fs:40, %rax
movq %rax, -8(%rbp)
xorl %eax, %eax
movl $.LC0, %edi
movl $0, %eax
call printf
leaq -12(%rbp), %rax
movq %rax, %rsi
movl $.LC1, %edi
movl $0, %eax
call __isoc99_scanf
movl -12(%rbp), %eax
movl %eax, %edi
call addNumbers
movl %eax, %esi
movl $.LC2, %edi
movl $0, %eax
call printf
movl $0, %eax
movq -8(%rbp), %rdx
xorq %fs:40, %rdx
je .L3
call __stack_chk_fail
.L3:
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.globl addNumbers
.type addNumbers, @function
addNumbers:
.LFB1:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl %edi, -4(%rbp)
cmpl $0, -4(%rbp)
je .L5
movl -4(%rbp), %eax
subl $1, %eax
movl %eax, %edi
call addNumbers
movl %eax, %edx
movl -4(%rbp), %eax
addl %edx, %eax
jmp .L6
.L5:
movl -4(%rbp), %eax
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.