created 06/19/2003; edited 07/22/15

# Chapter 14 Programming Exercises

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

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

Run the programs by setting the value of the PC to 0x400000 and then single stepping (pushing F10) or by multiple stepping (push F11 and enter a number of steps). Observing the results in the SPIM window.

## *Exercise 1

Write a program to evaluate a polynomial, similar to `newMult.asm` from the chapter. Evaluate the polynomial:

```3x2 + 5x - 12
```

Pick a register to contain `x` and initialize it to an integer value (positive or negative) at the beginning of the program. Assume that `x` is small enough so that all results remain in the `lo` result register. Evaluate the polynomial and leave its value in a register.

Verify that the program works by using several initial values for `x`. Use `x = 0` and `x = 1` to start since this will make debugging easy.

Optional: write the program following the hardware rule that two or more instructions must follow a `mflo` instruction before another `mult` instruction. Try to put useful instructions in the two slots that follow the `mflo`. Otherwise put no-op instructions, `sll \$0,\$0,0`, in the two slots.

## *Exercise 2

Write a program similar to `divEg.asm` from the chapter to evaluate a rational function:

```(3x+7)/(2x+8)
```

Verify that the program works by using several initial values for `x`. Use `x = 0` and `x = 1` to start since this will make debugging easy. Try some other values, then check what happens when `x = -4`.

## *Exercise 3

Write a program that multiplies the contents of two registers which you have initialized using an immediate operand with the `ori` instruction. Determine (by inspection) the number of significant bits in each of the following numbers, represented in two's complement. Use the program to form their product and then determine the number of significant bits in it.

Operand 1 Significant Bits Operand 2 Significant Bits 0x00001000 0x00000FFF 0x0000FF00 0x00008000 13 0x00001000 0x00000FFF 0x0000FFFF 0x00001000 13 0X1000000 25

## *Exercise 4

Write a program that determines the value of the following expression:

```(x*y)/z
```

Use `x = 1600000` (=0x186A00), `y = 80000` (=0x13880), and `z = 400000` (=61A80). Initialize three registers to these values. Since the immediate operand of the `ori` instruction is only 16 bits wide, use shift instructions to move bits into the correct locations of the registers.

Choose wisely the order of multiply and divide operations so that the significant bits always remain in the `lo` result register.