# Fibonacci with Loop int fib1(int i) { int f1 = 1; int f2 = 1; int f3;

## Presentation on theme: "Fibonacci with Loop int fib1(int i) { int f1 = 1; int f2 = 1; int f3;"— Presentation transcript:

Fibonacci with Loop int fib1(int i) { int f1 = 1; int f2 = 1; int f3;
while (i >= 3) { f3 = f1+f2; f1 = f2; f2 = f3; i--; } return f2;

Fibonacci with loop fib: li \$t0, 1 li \$v0, 1 li \$t1, 3
L1: blt \$a0, \$t1, fibExit add \$t2, \$t0, \$v0 move \$t0, \$v0 move \$v0, \$t2 addi \$a0, \$a0, -1 j L1 fibExit: jr \$ra

Fibonacci with Recursion
int fib(int i) { if (i < 3) return 1; int j = fib(i-1); int k = fib(i-2); return j+k; }

Fibonacci with recursion
addi \$sp, \$sp, -16 sw \$s0, 12(\$sp) sw \$s1, 8(\$sp) sw \$a0, 4(\$sp) sw \$ra, 0(\$sp) li \$s0, 0 li \$s1, 1 li \$t1, 3 L1: blt \$a0, \$t1, fibExit addi \$a0, \$a0, -1 jal fib first recursive call move \$s0, \$v0 jal fib second recursive call move \$s1, \$v0

Fibonacci with recursion
fibExit: add \$v0, \$s0,\$s1 lw \$s0, 12(\$sp) lw \$s1, 8(\$sp) lw \$a0, 4(\$sp) lw \$ra, 0(\$sp) addi \$sp, \$sp, 16 jr \$ra

Main program .text .align 2 .globl main main: li \$v0, 4 la \$a0, PR
syscall li \$v0, 5 move \$a0, \$v0 jal fib li \$v0, 1 la \$a0, LF li \$v0,10

Main program .data .align 4 PR: .asciiz "Enter a positive integer "
LF: .asciiz "\n"

Execute spim gendreaus-computer:fall10 tom\$ spim