created 06/29/2003; revised 06/30/2015

Chapter 21 Programming Exercises

For these programming exercises, use only those instructions that have been discussed so far in these notes:

Basic Instructions
and lbu or sub
andi lh ori subu
beq lhu sb sw
bgez lui sh xor
bltz lw sll xori
bne mfhi

PseudoInstructions
la lw nop
li move sw

In the Settings menu of SPIM set Bare Machine OFF, Allow Pseudo Instructions ON, Load Trap File OFF, Delayed Branches ON, Delayed Loads ON, Mapped IO OFF, Quiet OFF.

In these programs do not set up a base register as has been done in previous chapters. Use the `lw` and `sw` instructions with symbolic addresses. Use mnemonic register names in your programs and use registers in their conventional ways.

*Exercise 1 — Horner's Method

(see Exercise 4 of chapter 15)

Evaluate the following polynomial using Horner's method:

```ax3 + bx2 + cx + d
```

Now the values for the coefficients `a, b, c, d` as well as for `x` come from the `.data` section of memory:

```        .data
x:      .word    7
a:      .word   -3
bb:     .word    3
c:      .word    9
d:      .word  -24
result: .word    0
```

Use the pseudoinstruction `lw` to get the coefficients from memory, and `sw` to write the result back to memory.

(Recall that the symbolic address `b` cannot be used in SPIM.)

Declare three arrays, each of the same size:

```         .data
size     .word       7
array1:  .word     -30, -23, 56, -43, 72, -18, 71
array2:  .word      45,  23, 21, -23, -82,  0, 69
result:  .word       0,   0,  0,   0,   0,  0,  0
```

Initialize a base register for each array (use the `la` instruction.) Now implement a loop that adds corresponding elements in the first two arrays and stores the result in the corresponding element of the `result` array. Do this by moving each of the three base registers to its next array element after each addition.

***Exercise 3 — String Comparison

Declare two null-terminated strings:

```         .data
result:  .word     0
string1: .asciiz   "puffin"
string2: .asciiz   "puffins"
```

Initialize a base register for each string (use the `la` instruction.) Write a program that sets `result` to 1 if the two strings are equal and to 0 if the strings are not equal.

Two strings are equal if they are the same length and contain the same character in each location. Otherwise the strings are not equal.

Test your program for a variety of strings. You will have to edit the data section of your program for each pair of strings tested.

Extra: write the program so that it does case insensitive string comparison. Here, two strings are equal if they are the same length and have the same letter (disregarding case) in each location.