Search code examples
mipsmips32

MIPS using the Fibonacci sequence


My code is throwing a few errors and I am not super familiar with the MIPS syntax always. The given problem is:

The original problem investigated in 1202, was how fast rabbits could breed in ideal circumstances.

Suppose a newly born pair of rabbits, one male and one female, are put in a field.

Rabbits are sexually mature after one month so that at the end of its second month a female can produce another pair of rabbits.

Suppose that our rabbits never die and that females always produce one pair (one male, one female) every month from the second month on.

How many pairs will there be in one year?

The code I have so far is:

.data

str: .asciiz "The number of pairs of rabbits in a year are: "

.text
.globl main

li $t0, 12
li $t1, 0
li $t2, 1
li $t4, 0

la $a0, str
li $v0, 4
syscall

loop:

beq $t4, $t0, exit
move $t3, $t2
add $t2, $t1, $t2
move $t1, $t3
addi $t4, $t4, 1

j loop

exit:

move $a0, $t2
li $v0, 1
syscall


li $v0, 10
syscall

Solution

  • Well, you didn't say what the error was... but when I plugged this into spim I received:

    SPIM Version 7.4 of January 1, 2009
    Copyright 1990-2004 by James R. Larus (larus@cs.wisc.edu).
    All Rights Reserved.
    See the file README for a full copyright notice.
    Loaded: /opt/local/share/spim/exceptions.s
    The following symbols are undefined:
    main
    
    Instruction references undefined symbol at 0x00400014
    [0x00400014]    0x0c000000  jal 0x00000000 [main]           ; 180: jal main
    

    Which implies that you are missing the main label. Add it right before your main function:

    .text
    .globl main
    main:
    
    li $t0, 12
    ...
    

    This yielded the expected answer:

    The number of pairs of rabbits in a year are: 233