/* Fibonacci .c */ /* Shows how a (doubly) recursive program can be directly * translated from the MIPS code given in Pervin's book. * Of course it is a very, very inefficient way to do the * calculations but it shows that this can be done. */ #include #include "db_utils.h" #include "registers.h" /* Now can use usual names */ #include int fib(int); int i; /* Global */ int main(void) { char buffer[10]; while(1) { DBPRINTF("\nPlease input an integer (negative to quit):\n"); i = 0; /* buffer is not reinitialized */ while (i++ <= 9) buffer[i] = '\0'; DBGETS(buffer, 10); i = atoi(buffer); if (i < 0) break; if (i > 30) {DBPRINTF("\nTakes too long!!\n"); continue;} DBPRINTF("Fibonacci(%d) = %d\n", i, fib(i)); }; /* end while */ DBPUTS("\nProgram terminated. \n"); DBPUTS("Click HALT=F5 and then RESET=F6 to stop the microcontroller.\n"); return 0; } int fib(int n) /* Modified fibonacci.s from page 82 of PGA */ { asm(" 1: addiu $sp, $sp, -12 ;\ sw $ra, 0($sp) ;\ sw $a0, 4($sp) ;\ sw $s0, 8($sp) ;\ li $s0, 1 ;\ ble $a0, $s0, 2f ;\ addiu $a0, $a0, -1 ;\ jal 1b ;\ move $s0, $v0 ;\ addiu $a0, $a0, -1 ;\ jal 1b ;\ add $v0, $v0, $s0 ;\ j 3f ;\ 2: move $v0, $a0 ;\ 3: lw $s0, 8($sp) ;\ lw $a0, 4($sp) ;\ lw $ra, 0($sp) ;\ addiu $sp, $sp, 12 ;\ jr $ra ;\ " ); }