Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the code for the .data section that would, 1. Define a global int variable

ID: 3563184 • Letter: W

Question

Write the code for the .data section that would,
1. Define a global int variable named n which is not initialized (however, because n is located in the data segment,
and because the data segment is initialized to all zero bytes, n will be implicitly initialized to 0).
2. Define an array of sixteen ints named f initialized to { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 }.
3. Define a string named s_prompt initialized to: "Enter n (0 <= n <= 15): ".
4. Define a string named s_out1 initialized to: "f(".
5. Define a string named s_out12 initialized to: ") = ".

Continuing, the array f contains the first sixteen Fibonacci numbers1
, i.e., f(0) = 0, f(1) = 1, f(2) = 1, f(3) = 2, ...,
f(15) = 610, where f(n) = f(n-2) + f(n-1) for n > 1. Now, write instructions in the .text section of hw02-05.s that will
implement this pseudocode (which prompts the user to enter n and then displays f(n)):
int n;
int f[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 };
main
PrintString("Enter n (0 <= n <= 15): ")
n = ReadInt()
PrintString("f(")
PrintInt(n)
PrintString(") = ")
PrintInt(f[n])
Exit()
end main
You may certainly use the macros in system.inc that you wrote in Homework Assignment 2. Make sure to properly
format your code and write a comment in column four of each line containing an instruction to document your code.
Also, make sure to call the Exit() system call at the end of your program.

Explanation / Answer

#hw02-05.s

.data
n: .space 4 #4 bytes reserved for int n
f: .word 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
s_prompt: .asciiz "Enter n (0 <= n <= 15):"
s_out1: .asciiz "f("
s_out12: .asciiz ") = "

.text
main :
# print the string
li $v0,4
la $a0,s_prompt
syscall
# Get integer n and store in n
li $v0,5
syscall
#load address of n
la $t0,n
#store the read value at n
sw $v0,0($t0)

#$t1 is set to the first address of the array
la $t1,f
#read n
lw $t2,0($t0)
#as each element in array is 4 bytes, address of f[n] = address of f[0] + 4*n
#find 4*n
add $t2,$t2,$t2
add $t2,$t2,$t2

#f[0] + 4*n
add $t1,$t1,$t2

#read f[n] to $t1
lw $t1,0($t1)

# print the string
li $v0,4
la $a0,s_out1
syscall

# print the value of n
li $v0,1
lw $a0,0($t0)
syscall

# print the string
li $v0,4
la $a0,s_out12
syscall

# print the value of f[n]
li $v0,1
move $a0,$t1
syscall

#exit
li $v0,10
syscall