226k views
0 votes
Using language c, find the nth Fibonacci, knowing that nth Fibonacci is calculated by the following formula: - If n = 1 Or n = 2 then F(n) = 1 - If n>2 then F(n) = F(n-1) + F(n-2)

User Mseebacher
by
3.7k points

1 Answer

2 votes

Answer:

#include <stdio.h>

int fib(int n) {

if (n <= 0) {

return 0;

}

if (n <= 2) {

return 1;

}

return fib(n-1) + fib(n-2);

}

int main(void) {

for(int nr=0; nr<=20; nr++)

printf("Fibonacci %d is %d\\", nr, fib(nr) );

return 0;

}

Step-by-step explanation:

The code is a literal translation of the definition using a recursive function.

The recursive function is not per se a very efficient one.

User Scott Chacon
by
3.7k points