created 06/20/2003

# Chapter 13 Programming Exercises

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

> add | sll
> addi | srl
> addiu | sub
> addu | subu
> and | nor
> andi | xor
> or | xori
> ori |

> 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 -- Column Addition

Write a program that adds up the following integers:

     456
    -229
     325
    -552

Leave the answer in register $8.

Click here to go back to the main menu.

## *Exercise 2 -- Shifting and Adding

Initialize the sum in register $8 to zero. Then add 409610 to $8 sixteen times. You don't know how to loop, yet, so do this by making 16 copies of the same instruction. The value 409610 is 0x1000.

Next initialize register $9 to 409610. Shift $9 left by the correct number of positions so that registers $8 and $9 contain the same bit pattern.

Finally, initialize aregister $10 to 409610. Add $10 to itself the correct number of times so that it contains the same bit pattern as the other two registers.

## *Exercise 3 -- Trapping Overflow

Initialize register $9 to 0x7000. Shift the bit pattern so that $9 contains 0x70000000. Now use `addu` to add $9 to itself. Is the result correct?

Now use the `add` instruction and run the program again. What happens?

This may be the only time in this course that you will use the `add` instruction.

Click here to go back to the main menu.

## *Exercise 4 -- Arithmetic Expression

Let register $8 be `x` and register $9 be `y`. Write a program to evaluate:

    3x - 5y

Leave the result in register $10. Inspect the register after running the program to check that the program works. Run the program several times, initialize `x` and `y` to different values for each run.

## **Exercise 5 -- Two's Complement

Let register $8 be `x`. Write a program that computes `13x`. Leave the result in register $10. Initialize `x` to 1 for debugging. Then try some other positive values.

Extend your program so that it also computes `-13x` and leaves the result in register $11 (This will take one additional instruction.) Now initialize `x` to -1. Look at your result for `13x`. Is it correct?

Click here to go back to the main menu.

End of Exercises