created 06/29/2003

# Chapter 19 Programming Exercises

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

> add | div | mflo | slt, slti
> addi | divu | mult | sltu, sltiu
> addiu | j | multu | sra
> addu | lb | nor | srl
> and | lbu | or | sub
> andi | lh | ori | subu
> beq | lhu | sb | sw
> bgez | lui | sh | xor
> bltz | lw | sll | xori
> bne | mfhi |  |

> 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 -- Sequential Memory Locations

Write a program that stores the number 0 in the first four bytes of the `.data` section, then stores the number 1 in the next four bytes, then stores the number 2 in the four bytes after that and so on. Do this for numbers 0 through 24.

Of course you will do this in a counting loop. The address in the data section is contained in a base register. Increment the base register each time a number is stored.

Click here to go back to the main menu.

## ***Exercise 2 -- Perfect Number Verifier

A perfect number is an integer whose integer divisors sum up to the number. For example, 6 is perfect because 6 is divided by 1, 2, and 3 and 6 = 1 + 2 + 3. Other perfect numbers are 28 and 496.

Write a program that determines if an integer stored in memory is a perfect number. Set a location in memory to 1 if the number is perfect, to 0 if not.

It would be enormously helpful to first do this by hand with a couple of examples. Then draw a flowchard. Check the flowchart by following it with a few examples. Then write the program.

Click here to go back to the main menu.

## ****Exercise 3 -- Perfect Number Searcher

This exercise continues exercise 2.

Write a program that searches for perfect numbers. It has an outer loop that counts upward from two to some limit. Each number is tested (as above) to see if it is a perfect number. If it is a perfect number it is stored at a memory location. Store perfect numbers at successive full-word memory locations. Look at exercise 1 for a way to do this.

Again, to save time and effort, create a flowchart first.

Click here to go back to the main menu.

End of Exercises