228,118 views
26 votes
26 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 Uclajatt
by
2.3k points

1 Answer

20 votes
20 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 Kingraam
by
3.2k points