Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

a) Compute and display the nth number in the Fibonacci sequence. You must use a

ID: 3604624 • Letter: A

Question

a) Compute and display the nth number in the Fibonacci sequence. You must use a for loop in this solution. (The Fibonacci sequence is explained below.)

b) Compute and display the nth number in the Fibonacci sequence. You must use a while loop in this solution. (The Fibonacci sequence is explained below.)

The next number in the Fibonacci sequence is computed by adding the two previous numbers. For example, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, …. Mathematically, we define the Fibonacci sequence as follows:

F1 = 1 first number in sequence is 1.

F2 = 1 second number in sequence is 1.

Fn = Fn-1 + Fn-2 for n>2 next number in sequence is sum of two previous numbers.

Explanation / Answer

a)

#include<stdio.h>

int fib(int n)
{

int f[n+1];
int i;

f[0] = 0;
f[1] = 1;

for (i = 2; i <= n; i++)
{
f[i] = f[i-1] + f[i-2];
}

return f[n];
}

int main ()
{
int n = 5;
printf("%d", fib(n));
return 0;
}

(b)

#include<stdio.h>

int fib(int n)
{

int f[n+1];
int i;

f[0] = 0;
f[1] = 1;
i=2;
while (i <= n)
{
f[i] = f[i-1] + f[i-2];
i++;
}

return f[n];
}

int main ()
{
int n = 9;
printf("%d", fib(n));
return 0;
}