Recursion & Pointers: Instructor: Alvin R. Lebeck
Recursion & Pointers: Instructor: Alvin R. Lebeck
Recursion & Pointers: Instructor: Alvin R. Lebeck
Instructor:
Alvin
R.
Lebeck
Admin
Homework
#3
Due
Monday
Feb
14
11:59pm
Reading:
Chapter
3
Recursion
Linked List
1
Computer Science 104 Duke University
C
Level
Local
Name
Scope
change
tsame
to
same
Recursion
Arguments/parameters
and
Return
Value
(funcWons)
Assembly
Level
Must
bridge
gap
between
HLL
and
ISA
Saved
Registers
Caller
Stack
Frame
+
Return
address
Local
Pushed
by
call
instrucWon
Variables
Arguments
for
this
call
Argument
Stack
pointer
Build
%esp
3
Computer Science 104 Duke University
“Caller
Save”
Caller
saves
temporary
values
in
its
frame
before
the
call
“Callee
Save”
Callee
saves
temporary
values
in
its
frame
before
using
5
Computer Science 104 Duke University
Sum
array
Task: sum together the integers stored in memory
.text
.globl
_sum
_sum:
# Fill in what goes here
.data
num_array:
.long
35,
16,
42,
19,
55,
91,
24,
61,
53
int
main(void)
{
int
result;
result
=
sum_array(7);
prinn("Array
sum
=
%d\n",result);
return
EXIT_SUCCESS;
}
7
Computer Science 104 Duke University
Sample
FuncWon
.text ! ! !# declare the text segment!
.globl _sum_array ! !# declare the function label (note the _ in this label)!
! ! ! !# the C program calls sum(int)!
_sum_array:!
!pushl %ebp ! !# save old frame pointer!
!movl %esp, %ebp ! !# set new stack pointer!
!movl 8(%ebp), %eax !# read arg1 from stack, put into %eax!
!leal num_array, %edx !# load address of num_array into %edx (p = &num_array)!
!leal (%edx,%eax,4), %ecx !# load address of num_array+arg into %ecx!
!movl $0, %eax ! !# move 0 to running sum (%eax)!
loop: ! ! !# label for loop structure!
!addl (%edx), %eax! !# add value *p to running sum (%eax)!
!addl $4, %edx ! !# increment pointer in memory (p++)!
!cmpl %ecx, %edx ! !# compare pointer to termination (p < (num_array+arg1))!
!jl loop! ! !# jump to loop if (p < (num_array+arg1))!
!leave ! ! !# prepare stack for return (movl %ebp, %esp; popl %ebp)!
!ret ! ! !# return to calling routine (result is in %eax)!
The
C
code
#include
<stdio.h>
#include
<stdlib.h>
extern
int
sum_i_sqr();
int
main(void)
{
int
result;
result
=
sum_i_sqr(100);
prinn("Sum
=
%d\n",result);
return
EXIT_SUCCESS;
}
int
sum_i_sqr(int
max){
int
i;
int
sum
=
0;
Write a recursive
for(i=0;
i
<=
100;
i++)
version of this
sum
=
sum
+
i*i
;
return(sum);
//
put
sum
into
%eax
}
9
Computer Science 104 Duke University
Fibonacci
Number
F
(n)
=
0
if
n
=
0
=
1
if
n
=
1
=
F(n-‐1)
+
F(n-‐2)
if
n
>
1;
CPS 104
11