created 07/07/2003

# Chapter 28 Programming Exercises

NOTE: Use the Frame-based Linkage Convention for these programs.

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.

Run the programs by clicking SimulatorGo and then OK in the pop-up panel.

## Exercise 1 -- Play Compiler

Translate the following little program into MIPS assembly language. Use stack-based variables for the program's local variables. Assemble and run your program under SPIM

    main()
    {
      int f;
      int c;

      f = 50;
      c = toCent( f );
      f = toFahr( c );

      print( "f=", f, "c=", c );
    }

    int toCent( int x )
    {
      int v;
      v =  5*x
      v =  v/9;
      v =  v - 32;
      return v;
    }

    int toFahr( int x )
    {
      int u;
      u = 9*x;
      u = u/5 + 32;
      return u;
    }

You could, of course, write the program using only registers since there are plenty of "T" registers available. But practice using local variables as in the chapter.

Click here to go back to the main menu.

## Exercise 2 -- Triangle Numbers

Write a program that computes the value of triangle numbers using a recursive subroutine. The definition of triangle numbers is:

    Triangle( 1 ) = 1

    Triangle( N ) = N + Triangle( N-1 )

For examples:

    Triangle( 1 ) = 1

    Triangle( 2 ) = 3

    Triangle( 3 ) = 6

    Triangle( 4 ) = 10

Click here to go back to the main menu.

End of Exercises