created 07/07/2003

Chapter 31 Programming Exercises

NOTE: If you have read the chapters on subroutine linkage, write each exercise as a main program calling a subroutine. Use either the stack-based linkage or the frame-based linkage convention.

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

Exercise 1 — Arithmetic Expression

Write a program that computes value of the following arithmetic expression for values of x and y entered by the user:

5.4xy - 12.3y + 18.23x - 8.23

Click here to go back to the main menu.

Exercise 2 — Harmonic Series

Write a program that computes the sum of the first part of the harmonic series:

1/1 + 1/2 + 1/3 + 1/4 + ...

This sum gets bigger and bigger without limit as more terms are added in. Ask the user for a number of terms to sum, compute the sum and print it out.

Click here to go back to the main menu.

Exercise 3 — Web Page RGB Colors

Colors on a Web page are often coded as a 24 bit integer as follows:


In this, each R, G, or B is a hex digit 0..F. The R digits give the amount of red, the G digits give the amount of green, and the B digits give the amount of blue. Each amount is in the range 0..255 (the range of one byte). Here are some examples:

FFFFFF 7F7F7F FF0000 00FF00 0000FF FF00FF 7F007F 70A0F0 FF7F7F

Another way that color is sometimes expressed is as three fractions 0.0 to 1.0 for each of red, green, and blue. For example, pure red is (1.0, 0.0, 0.0), medium gray is (0.5, 0.5, 0.5) and so on.

Write a program that has a color number declared in the data section and that writes out the amount of each color expressed as a decimal fraction. Put each color number in 32 bits, with the high order byte set to zeros:

color:    .word  0x00FF0000     # pure red, (1.0, 0.0, 0.0)

For extra fun, write a program that prompts the user for a color number and then writes out the fraction of each component.

Click here to go back to the main menu.

Exercise 4 — Polynomial Evaluation (Horner's Method, yet Again!)

Write a program that computes the value of a polynomial using Horner's method. The coefficients of the polynomial are stored in an array of single precision floating point values:

n:        5
a:        .float 4.3, -12.4, 6.8, -0.45, 3.6

The size and the values in the array may change. Write the program to initialize a sum to zero and then loop n times. Each execution of the loop, with loop counter j, does the following:

sum = sum*x + a[j]

To test and debug this program, start with easy values for the coefficients.

Click here to go back to the main menu.

End of Exercises