Transcript PreVersion

CDA 3101 Discussion Section 06
MIPS
Assembly Language
Programming
1
Problem 1
Write a function MinMax(&X, N) to find the minimum and
maximum of an array X of N integers. The address of the
array is passed in $a0, and the number of words in the array
is passed in $a1. The minimum and maximum are returned in
registers $v0 and $v1 respectively.
Also, write a short main program that
1.
Prompts the user for the value of N.
2.
Dynamically allocates memory for storing array X of N
integers. (Remember, 4 bytes per integer!)
3.
Prompts user to enter N integers one by one to fill the
array X.
4.
Calls the MinMax function to find and return the
minimum and maximum of the array X.
5.
Prints the minimum and the maximum value.
2
Problem 1
Write a function MinMax(&X, N) to find the minimum and
maximum of an array X of N integers. The address of the
array is passed in $a0, and the number of words in the array
is passed in $a1. The minimum and maximum are returned in
registers $v0 and $v1 respectively.
Also, write a short main program that
1.
Prompts the user for the value of N.
2.
Dynamically allocates memory for storing array X of N
integers. (Remember, 4 bytes per integer!)
3.
Prompts user to enter N integers one by one to fill the
array X.
4.
Calls the MinMax function to find and return the
minimum and maximum of the array X.
5.
Prints the minimum and the maximum value.
3
Problem 2
•
Implement a recursive function fib(n) to compute
Fibonacci numbers. Also write a short main function that
prompts the user to enter the integer N, calls the function
fib(N) and prints the value returned by the fib(N) function.
Note that:
– fib(0)=0; fib(1)=1;
– fib(n)=fib(n-1)+ fib(n-2), n>1.
4
Problem 2
•
Implement a recursive function fib(n) to compute
Fibonacci numbers. Also write a short main function that
prompts the user to enter the integer N, calls the function
fib(N) and prints the value returned by the fib(N) function.
int fib(int N)
{
if(N == 0) return 0;
else if(N == 1) return 1;
else return fib(N-1) + fib(N-2);
}
5
Key Points
• Dynamically allocate memory
li
$v0, 9
li
$a0, <int>
syscall
move $t0, $v0
# Memory allocation service
# Allocate <int> bytes of mem.
# Move address of array to safety.
• Recursion
self:
…
addi
sw
jal
lw
addi
$sp, $sp, -4
$ra, 0($sp)
self
$ra, 0($sp)
$sp, $sp, 4
#
#
#
#
#
Allocate stack space
Save old return address
Jump to self
Load old return address
Restore stack to old state
6