// Listing 2.25.cpp // A recursive function that returns the sum // of the first
ID: 3547227 • Letter: #
Question
// Listing 2.25.cpp
// A recursive function that returns the sum
// of the first n numbers in an array
#include <iostream>
using namespace std;
int list[4];
int sum (int a[], int n){
// Returns the sum of the elements of a between a[0] and a[n]
if (n == 0){
return a[0];
}
else{
return a[n] + sum(a, n-1);
}
}
int main() {
cout << "Enter four integers: ";
cin >> list[0] >> list[1] >> list[2] >> list[3];
cout << "Their sum is: " << sum(list,3) << endl;
return 0;
}
Explanation / Answer
.Ltext0: .local_ZStL8__ioinit .comm _ZStL8__ioinit,1,1 .globl list .bss .align 16 list: .zero 16 .text .globl _Z3sumPii _Z3sumPii: .LFB966: .cfi_startproc pushq %rbp .LCFI0: .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .LCFI1: .cfi_def_cfa_register 6 pushq %rbx subq $24, %rsp movq %rdi, -24(%rbp) movl %esi, -28(%rbp) cmpl $0, -28(%rbp) jne .L2 .cfi_offset 3, -24 movq -24(%rbp), %rax movl (%rax), %eax jmp .L3 .L2: movl -28(%rbp), %eax cltq salq $2, %rax addq -24(%rbp), %rax movl (%rax), %ebx movl -28(%rbp), %eax leal -1(%rax), %edx movq -24(%rbp), %rax movl %edx, %esi movq %rax, %rdi call _Z3sumPii addl %ebx, %eax .L3: addq $24, %rsp popq %rbx popq %rbp .LCFI2: .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE966: .section .rodata .LC0: .string "Enter four integers: " .LC1: .string "Their sum is: " .text .globl main main: .LFB967: .cfi_startproc pushq %rbp .LCFI3: .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .LCFI4: .cfi_def_cfa_register 6 pushq %rbx subq $8, %rsp movl $.LC0, %esi movl $_ZSt4cout, %edi .cfi_offset 3, -24 call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc movl $list, %esi movl $_ZSt3cin, %edi call _ZNSirsERi movl $list+4, %esi movq %rax, %rdi call _ZNSirsERi movl $list+8, %esi movq %rax, %rdi call _ZNSirsERi movl $list+12, %esi movq %rax, %rdi call _ZNSirsERi movl $3, %esi movl $list, %edi call _Z3sumPii movl %eax, %ebx movl $.LC1, %esi movl $_ZSt4cout, %edi call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc movl %ebx, %esi movq %rax, %rdi call _ZNSolsEi movl $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_, %esi movq %rax, %rdi call _ZNSolsEPFRSoS_E movl $0, %eax addq $8, %rsp popq %rbx popq %rbp .LCFI5: .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE967: _Z41__static_initialization_and_destruction_0ii: .LFB976: .cfi_startproc pushq %rbp .LCFI6: .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .LCFI7:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.