created 06/27/2003

Chapter 18 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 — Sum of Evens; Sum of Odds

Write a program that computes three sums:

1 + 2 + 3 + 4 + ... + 99 + 100

1 + 3 + 5 + 7 + ... + 97 + 99

2 + 4 + 6 + 8 + ... + 98 + 100

Use a register (say $8) for the sum of evens, a register (say $9) for the sum of odds, and another (say $10) for the sum of all numbers.

Do this with one counting loop. The loop body contains logic to add the count to the proper sums.

Click here to go back to the main menu.

*Exercise 2 — Significant Bits

With an ori instruction, initialize $8 to a bit pattern that represents a positive integer. Now the program determines how many significant bits are in the pattern. The significant bits are the leftmost one bit and all bits to its right. So the bit pattern:

0000 0000 0010 1001 1000 1101 0111 1101

... has 22 significant bits. (To load register $8 with the above pattern, 0x00298D7D, use an ori followed by a left shift followed by another ori.)

Click here to go back to the main menu.

**Exercise 3 — Allowed Ranges

A temperature in $8 is allowed to be within either of two ranges: 20 <= temp <= 40 and 60 <= temp <= 80. Write a program that sets a flag (register $3) to 1 if the temperature is in an allowed range and to 0 if the temperature is not in an allowed range.

It would be helpful to draw a flowchart before you start programming.

Click here to go back to the main menu.

****Exercise 4 — Median of Three

Write a program that computes the median of three values in memory. After it has been found, store the median in memory.

A:    .word 23
B:    .word 98
C:    .word 17    

The median of three integers is greater than or equal to one integer and less than or equal to the other. With the above three integers the median is "23". Assume that the data changes from run to run. Here is some more possible data:

A:    .word 9
B:    .word 98
C:    .word 9    

With the new data, the median is "9".

Click here to go back to the main menu.

End of Exercises